From 26dd688124d16087526690330062e4fd6f62e040 Mon Sep 17 00:00:00 2001 From: Cyberarm Date: Mon, 14 Dec 2020 16:04:31 -0600 Subject: [PATCH] Ran rubocop -a --- Gemfile | 2 +- Rakefile | 2 +- cyberarm_engine.gemspec | 15 +- lib/cyberarm_engine.rb | 2 +- lib/cyberarm_engine/animator.rb | 10 +- lib/cyberarm_engine/background.rb | 34 +++-- lib/cyberarm_engine/bounding_box.rb | 36 ++--- lib/cyberarm_engine/cache.rb | 2 +- lib/cyberarm_engine/cache/download_manager.rb | 22 +-- lib/cyberarm_engine/common.rb | 26 ++-- lib/cyberarm_engine/config_file.rb | 2 +- lib/cyberarm_engine/game_object.rb | 135 ++++++++---------- lib/cyberarm_engine/game_state.rb | 9 +- lib/cyberarm_engine/model.rb | 50 +++---- lib/cyberarm_engine/model/material.rb | 3 +- lib/cyberarm_engine/model/model_object.rb | 21 +-- lib/cyberarm_engine/model/parser.rb | 9 +- .../model/parsers/collada_parser.rb | 27 ++-- .../model/parsers/wavefront_parser.rb | 80 +++++------ lib/cyberarm_engine/model_cache.rb | 12 +- lib/cyberarm_engine/opengl.rb | 8 +- lib/cyberarm_engine/opengl/light.rb | 23 +-- .../opengl/orthographic_camera.rb | 14 +- .../opengl/perspective_camera.rb | 4 +- .../opengl/renderer/bounding_box_renderer.rb | 81 +++++------ .../opengl/renderer/g_buffer.rb | 68 ++++----- .../opengl/renderer/opengl_renderer.rb | 20 +-- lib/cyberarm_engine/opengl/shader.rb | 96 +++++++------ lib/cyberarm_engine/opengl/texture.rb | 14 +- lib/cyberarm_engine/ray.rb | 10 +- lib/cyberarm_engine/stats.rb | 4 +- lib/cyberarm_engine/text.rb | 60 ++++---- lib/cyberarm_engine/timer.rb | 2 +- lib/cyberarm_engine/transform.rb | 44 +++--- lib/cyberarm_engine/ui/border_canvas.rb | 7 +- lib/cyberarm_engine/ui/dsl.rb | 26 ++-- lib/cyberarm_engine/ui/element.rb | 22 +-- lib/cyberarm_engine/ui/elements/button.rb | 54 +++---- lib/cyberarm_engine/ui/elements/check_box.rb | 2 +- lib/cyberarm_engine/ui/elements/container.rb | 51 ++++--- lib/cyberarm_engine/ui/elements/edit_box.rb | 47 +++--- lib/cyberarm_engine/ui/elements/edit_line.rb | 71 +++++---- lib/cyberarm_engine/ui/elements/flow.rb | 2 +- lib/cyberarm_engine/ui/elements/image.rb | 21 +-- lib/cyberarm_engine/ui/elements/label.rb | 26 ++-- lib/cyberarm_engine/ui/elements/list_box.rb | 16 ++- lib/cyberarm_engine/ui/elements/progress.rb | 10 +- lib/cyberarm_engine/ui/elements/radio.rb | 2 +- lib/cyberarm_engine/ui/elements/slider.rb | 29 ++-- lib/cyberarm_engine/ui/elements/stack.rb | 2 +- .../ui/elements/toggle_button.rb | 12 +- lib/cyberarm_engine/ui/event.rb | 14 +- lib/cyberarm_engine/ui/gui_state.rb | 24 ++-- lib/cyberarm_engine/ui/style.rb | 19 +-- lib/cyberarm_engine/ui/theme.rb | 16 ++- lib/cyberarm_engine/vector.rb | 52 +++---- lib/cyberarm_engine/version.rb | 4 +- lib/cyberarm_engine/window.rb | 33 +++-- test/test_helper.rb | 2 +- 59 files changed, 770 insertions(+), 741 deletions(-) diff --git a/Gemfile b/Gemfile index 5718269..e017bf7 100644 --- a/Gemfile +++ b/Gemfile @@ -1,6 +1,6 @@ source "https://rubygems.org" -git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } +git_source(:github) { |repo_name| "https://github.com/#{repo_name}" } # Specify your gem's dependencies in cyberarm_engine.gemspec gemspec diff --git a/Rakefile b/Rakefile index d433a1e..3d52175 100644 --- a/Rakefile +++ b/Rakefile @@ -7,4 +7,4 @@ Rake::TestTask.new(:test) do |t| t.test_files = FileList["test/**/*_test.rb"] end -task :default => :test +task default: :test diff --git a/cyberarm_engine.gemspec b/cyberarm_engine.gemspec index 51016f4..a9c0199 100644 --- a/cyberarm_engine.gemspec +++ b/cyberarm_engine.gemspec @@ -1,5 +1,4 @@ - -lib = File.expand_path("../lib", __FILE__) +lib = File.expand_path("lib", __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "cyberarm_engine/version" @@ -9,8 +8,8 @@ Gem::Specification.new do |spec| spec.authors = ["Cyberarm"] spec.email = ["matthewlikesrobots@gmail.com"] - spec.summary = %q{Make games quickly and easily with gosu} - spec.description = %q{Yet another game making framework around gosu} + spec.summary = "Make games quickly and easily with gosu" + spec.description = "Yet another game making framework around gosu" spec.homepage = "https://github.com/cyberarm/cyberarm_engine" spec.license = "MIT" @@ -21,20 +20,20 @@ Gem::Specification.new do |spec| "public gem pushes." end - spec.files = `git ls-files -z`.split("\x0").reject do |f| + spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } - spec.require_paths = ["lib", "assets"] + spec.require_paths = %w[lib assets] + spec.add_dependency "clipboard", "~> 1.3.4" spec.add_dependency "excon", "~> 0.76.0" spec.add_dependency "gosu", "~> 0.15.0" spec.add_dependency "gosu_more_drawables", "~> 0.3" - spec.add_dependency "clipboard", "~> 1.3.4" # spec.add_dependency "ffi", :platforms => [:mswin, :mingw] # Required by Clipboard on Windows spec.add_development_dependency "bundler", "~> 1.16" - spec.add_development_dependency "rake", "~> 13.0" spec.add_development_dependency "minitest", "~> 5.0" + spec.add_development_dependency "rake", "~> 13.0" end diff --git a/lib/cyberarm_engine.rb b/lib/cyberarm_engine.rb index 0d1d195..273d251 100644 --- a/lib/cyberarm_engine.rb +++ b/lib/cyberarm_engine.rb @@ -1,4 +1,4 @@ -CYBERARM_ENGINE_ROOT_PATH = File.expand_path("../..", __FILE__) +CYBERARM_ENGINE_ROOT_PATH = File.expand_path("..", __dir__) begin require File.expand_path("../../ffi-gosu/lib/gosu", File.dirname(__FILE__)) diff --git a/lib/cyberarm_engine/animator.rb b/lib/cyberarm_engine/animator.rb index 09f63b7..6440d9e 100644 --- a/lib/cyberarm_engine/animator.rb +++ b/lib/cyberarm_engine/animator.rb @@ -2,8 +2,10 @@ module CyberarmEngine class Animator DEFAULT_TWEEN = :linear def initialize(start_time:, duration:, from:, to:, &block) - @start_time, @duration = start_time, duration - @from, @to = from.dup, to.dup + @start_time = start_time + @duration = duration + @from = from.dup + @to = to.dup @block = block end @@ -23,7 +25,7 @@ module CyberarmEngine from + (to - from) * send("tween_#{tween}", progress) end - def color_transition(from, to, tween = DEFAULT_TWEEN) + def color_transition(from, to, _tween = DEFAULT_TWEEN) r = transition(from.red, to.red) g = transition(from.green, to.green) b = transition(from.blue, to.blue) @@ -51,4 +53,4 @@ module CyberarmEngine Math.sin(t) * t end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/background.rb b/lib/cyberarm_engine/background.rb index 7166d9f..3f6a431 100644 --- a/lib/cyberarm_engine/background.rb +++ b/lib/cyberarm_engine/background.rb @@ -2,9 +2,13 @@ module CyberarmEngine class Background attr_accessor :x, :y, :z, :width, :height, :angle, :debug attr_reader :background + def initialize(x: 0, y: 0, z: 0, width: 0, height: 0, background: Gosu::Color::BLACK, angle: 0, debug: false) - @x,@y,@z = x,y,z - @width,@height = width,height + @x = x + @y = y + @z = z + @width = width + @height = height @debug = debug @paint = Paint.new(background) @@ -31,8 +35,8 @@ module CyberarmEngine end def update - origin_x = (@x + (@width/2)) - origin_y = (@y + (@height/2)) + origin_x = (@x + (@width / 2)) + origin_y = (@y + (@height / 2)) points = [ @top_left = Vector.new(@x, @y), @@ -47,8 +51,8 @@ module CyberarmEngine # 90 is up here, while gosu uses 0 for up. radians = (@angle + 90).gosu_to_radians - vector.x = (@x + (@width/2)) + ((temp_x * Math.cos(radians)) - (temp_y * Math.sin(radians))) - vector.y = (@y + (@height/2)) + ((temp_x * Math.sin(radians)) + (temp_y * Math.cos(radians))) + vector.x = (@x + (@width / 2)) + ((temp_x * Math.cos(radians)) - (temp_y * Math.sin(radians))) + vector.y = (@y + (@height / 2)) + ((temp_x * Math.sin(radians)) + (temp_y * Math.cos(radians))) end # [ @@ -67,11 +71,11 @@ module CyberarmEngine a = la.x - lb.x b = la.y - lb.y c = Gosu.distance(la.x, la.y, lb.x, lb.y) - p a,b,c - d = (a * point.x + b * point.y + c).abs / (Math.sqrt(a * a + b * b)) + p a, b, c + d = (a * point.x + b * point.y + c).abs / Math.sqrt(a * a + b * b) puts "Distance: #{d}" exit! - return d + d end def debug_outline @@ -117,6 +121,7 @@ module CyberarmEngine class Paint attr_accessor :top_left, :top_right, :bottom_left, :bottom_right + def initialize(background) set(background) end @@ -124,7 +129,6 @@ module CyberarmEngine def set(background) @background = background - if background.is_a?(Numeric) @top_left = background @top_right = background @@ -167,9 +171,9 @@ end # Add <=> method to support Range based gradients module Gosu - class Color - def <=>(other) - self - end - end + class Color + def <=>(_other) + self + end + end end diff --git a/lib/cyberarm_engine/bounding_box.rb b/lib/cyberarm_engine/bounding_box.rb index b93040b..9bce777 100644 --- a/lib/cyberarm_engine/bounding_box.rb +++ b/lib/cyberarm_engine/bounding_box.rb @@ -23,7 +23,7 @@ module CyberarmEngine def ==(other) @min == other.min && - @max == other.max + @max == other.max end # returns a new bounding box that includes both bounding boxes @@ -37,7 +37,7 @@ module CyberarmEngine temp.max.y = [@max.y, other.max.y].max temp.max.z = [@max.z, other.max.z].max - return temp + temp end # returns the difference between both bounding boxes @@ -46,7 +46,7 @@ module CyberarmEngine temp.min = @min - other.min temp.max = @max - other.max - return temp + temp end # returns whether bounding box intersects other @@ -55,8 +55,8 @@ module CyberarmEngine other.intersect?(self) elsif other.is_a?(BoundingBox) (@min.x <= other.max.x && @max.x >= other.min.x) && - (@min.y <= other.max.y && @max.y >= other.min.y) && - (@min.z <= other.max.z && @max.z >= other.min.z) + (@min.y <= other.max.y && @max.y >= other.min.y) && + (@min.z <= other.max.z && @max.z >= other.min.z) else raise "Unknown collider: #{other.class}" end @@ -65,20 +65,20 @@ module CyberarmEngine # does this bounding box envelop other bounding box? (inclusive of border) def contains?(other) other.min.x >= min.x && other.min.y >= min.y && other.min.z >= min.z && - other.max.x <= max.x && other.max.y <= max.y && other.max.z <= max.z + other.max.x <= max.x && other.max.y <= max.y && other.max.z <= max.z end # returns whether the 3D vector is inside of the bounding box def inside?(vector) (vector.x.between?(@min.x, @max.x) || vector.x.between?(@max.x, @min.x)) && - (vector.y.between?(@min.y, @max.y) || vector.y.between?(@max.y, @min.y)) && - (vector.z.between?(@min.z, @max.z) || vector.z.between?(@max.z, @min.z)) + (vector.y.between?(@min.y, @max.y) || vector.y.between?(@max.y, @min.y)) && + (vector.z.between?(@min.z, @max.z) || vector.z.between?(@max.z, @min.z)) end # returns whether the 2D vector is inside of the bounding box def point?(vector) (vector.x.between?(@min.x, @max.x) || vector.x.between?(@max.x, @min.x)) && - (vector.y.between?(@min.y, @max.y) || vector.y.between?(@max.y, @min.y)) + (vector.y.between?(@min.y, @max.y) || vector.y.between?(@max.y, @min.y)) end def volume @@ -107,7 +107,7 @@ module CyberarmEngine temp.max.y = @max.y.to_f * entity.scale.y temp.max.z = @max.z.to_f * entity.scale.z - return temp + temp end def normalize_with_offset(entity) @@ -120,23 +120,23 @@ module CyberarmEngine temp.max.y = @max.y.to_f * entity.scale.y + entity.position.y temp.max.z = @max.z.to_f * entity.scale.z + entity.position.z - return temp + temp end def +(other) box = BoundingBox.new - box.min = self.min + other.min - box.min = self.max + other.max + box.min = min + other.min + box.min = max + other.max - return box + box end def -(other) box = BoundingBox.new - box.min = self.min - other.min - box.min = self.max - other.max + box.min = min - other.min + box.min = max - other.max - return box + box end def sum @@ -147,4 +147,4 @@ module CyberarmEngine BoundingBox.new(@min.x, @min.y, @min.z, @max.x, @max.y, @max.z) end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/cache.rb b/lib/cyberarm_engine/cache.rb index 170c764..f314a7f 100644 --- a/lib/cyberarm_engine/cache.rb +++ b/lib/cyberarm_engine/cache.rb @@ -1,4 +1,4 @@ module CyberarmEngine module Cache end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/cache/download_manager.rb b/lib/cyberarm_engine/cache/download_manager.rb index e9278fc..031d3bf 100644 --- a/lib/cyberarm_engine/cache/download_manager.rb +++ b/lib/cyberarm_engine/cache/download_manager.rb @@ -27,13 +27,14 @@ module CyberarmEngine remaining_bytes = @downloads.map { |d| d.remaining_bytes }.sum total_bytes = @downloads.map { |d| d.total_bytes }.sum - v = 1.0 - (remaining_bytes.to_f / total_bytes.to_f) + v = 1.0 - (remaining_bytes.to_f / total_bytes) return 0.0 if v.nan? - return v + + v end def active_downloads - @downloads.select { |d| [:pending, :downloading].include?(d.status) } + @downloads.select { |d| %i[pending downloading].include?(d.status) } end def update @@ -53,6 +54,7 @@ module CyberarmEngine attr_accessor :status attr_reader :uri, :save_as, :callback, :remaining_bytes, :total_downloaded_bytes, :total_bytes, :error_message, :started_at, :finished_at + def initialize(uri:, save_as:, callback: nil) @uri = uri @save_as = save_as @@ -68,9 +70,10 @@ module CyberarmEngine end def progress - v = 1.0 - (@remaining_bytes.to_f / total_bytes.to_f) + v = 1.0 - (@remaining_bytes.to_f / total_bytes) return 0.0 if v.nan? - return v + + v end def download @@ -103,17 +106,16 @@ module CyberarmEngine @finished_at = Time.now # TODO: monotonic time @callback.call(self) if @callback end - rescue => e # TODO: cherrypick errors to cature + rescue StandardError => e # TODO: cherrypick errors to cature @status = :failed @finished_at = Time.now # TODO: monotonic time @error_message = e.message @callback.call(self) if @callback end - - ensure - io.close if io + ensure + io.close if io end end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/common.rb b/lib/cyberarm_engine/common.rb index 51b6c32..108f7c6 100644 --- a/lib/cyberarm_engine/common.rb +++ b/lib/cyberarm_engine/common.rb @@ -1,6 +1,6 @@ module CyberarmEngine module Common - def push_state(klass, options={}) + def push_state(klass, options = {}) window.push_state(klass, options) end @@ -20,7 +20,7 @@ module CyberarmEngine window.show_cursor end - def show_cursor=boolean + def show_cursor=(boolean) window.show_cursor = boolean end @@ -34,24 +34,24 @@ module CyberarmEngine def lighten(color, amount = 25) if defined?(color.alpha) - return Gosu::Color.rgba(color.red + amount, color.green + amount, color.blue + amount, color.alpha) + Gosu::Color.rgba(color.red + amount, color.green + amount, color.blue + amount, color.alpha) else - return Gosu::Color.rgb(color.red + amount, color.green + amount, color.blue + amount) + Gosu::Color.rgb(color.red + amount, color.green + amount, color.blue + amount) end end def darken(color, amount = 25) if defined?(color.alpha) - return Gosu::Color.rgba(color.red - amount, color.green - amount, color.blue - amount, color.alpha) + Gosu::Color.rgba(color.red - amount, color.green - amount, color.blue - amount, color.alpha) else - return Gosu::Color.rgb(color.red - amount, color.green - amount, color.blue - amount) + Gosu::Color.rgb(color.red - amount, color.green - amount, color.blue - amount) end end def opacity(color, ratio = 1.0) alpha = 255 * ratio - return Gosu::Color.rgba(color.red, color.green, color.blue, alpha) + Gosu::Color.rgba(color.red, color.green, color.blue, alpha) end def get_asset(path, hash, klass, retro = false, tileable = false) @@ -65,16 +65,16 @@ module CyberarmEngine unless asset instance = nil - if klass == Gosu::Image - instance = klass.new(path, retro: retro, tileable: tileable) - else - instance = klass.new(path) - end + instance = if klass == Gosu::Image + klass.new(path, retro: retro, tileable: tileable) + else + klass.new(path) + end hash[path] = instance asset = instance end - return asset + asset end def get_image(path, retro: false, tileable: false) diff --git a/lib/cyberarm_engine/config_file.rb b/lib/cyberarm_engine/config_file.rb index 0d63dd1..17f5d61 100644 --- a/lib/cyberarm_engine/config_file.rb +++ b/lib/cyberarm_engine/config_file.rb @@ -10,7 +10,7 @@ module CyberarmEngine end end - def []= *keys, value + def []=(*keys, value) last_key = keys.last if keys.size == 1 diff --git a/lib/cyberarm_engine/game_object.rb b/lib/cyberarm_engine/game_object.rb index 26e1cf1..dbc25ac 100644 --- a/lib/cyberarm_engine/game_object.rb +++ b/lib/cyberarm_engine/game_object.rb @@ -5,55 +5,60 @@ module CyberarmEngine attr_accessor :image, :angle, :position, :velocity, :center_x, :center_y, :scale_x, :scale_y, :color, :mode, :options, :paused, :radius, :last_position attr_reader :alpha - def initialize(options={}) - if options[:auto_manage] || options[:auto_manage] == nil - $window.current_state.add_game_object(self) - end + + def initialize(options = {}) + $window.current_state.add_game_object(self) if options[:auto_manage] || options[:auto_manage].nil? @options = options @image = options[:image] ? image(options[:image]) : nil - x = options[:x] ? options[:x] : 0 - y = options[:y] ? options[:y] : 0 - z = options[:z] ? options[:z] : 0 + x = options[:x] || 0 + y = options[:y] || 0 + z = options[:z] || 0 @position = Vector.new(x, y, z) @velocity = Vector.new @last_position = Vector.new - @angle = options[:angle] ? options[:angle] : 0 + @angle = options[:angle] || 0 - @center_x = options[:center_x] ? options[:center_x] : 0.5 - @center_y = options[:center_y] ? options[:center_y] : 0.5 + @center_x = options[:center_x] || 0.5 + @center_y = options[:center_y] || 0.5 - @scale_x = options[:scale_x] ? options[:scale_x] : 1 - @scale_y = options[:scale_y] ? options[:scale_y] : 1 + @scale_x = options[:scale_x] || 1 + @scale_y = options[:scale_y] || 1 - @color = options[:color] ? options[:color] : Gosu::Color.argb(0xff_ffffff) - @alpha = options[:alpha] ? options[:alpha] : 255 - @mode = options[:mode] ? options[:mode] : :default + @color = options[:color] || Gosu::Color.argb(0xff_ffffff) + @alpha = options[:alpha] || 255 + @mode = options[:mode] || :default @paused = false @speed = 0 @debug_color = Gosu::Color::GREEN - @world_center_point = Vector.new(0,0) + @world_center_point = Vector.new(0, 0) setup - @debug_text = Text.new("", color: @debug_color, y: @position.y-(self.height*self.scale), z: 9999) + @debug_text = Text.new("", color: @debug_color, y: @position.y - (height * scale), z: 9999) @debug_text.x = @position.x - if @radius == 0 || @radius == nil - @radius = options[:radius] ? options[:radius] : defined?(@image.width) ? ((@image.width+@image.height)/4)*scale : 1 + if @radius == 0 || @radius.nil? + @radius = if options[:radius] + options[:radius] + else + defined?(@image.width) ? ((@image.width + @image.height) / 4) * scale : 1 + end end end def draw if @image - @image.draw_rot(@position.x, @position.y, @position.z, @angle, @center_x, @center_y, @scale_x, @scale_y, @color, @mode) + @image.draw_rot(@position.x, @position.y, @position.z, @angle, @center_x, @center_y, @scale_x, @scale_y, + @color, @mode) end if $debug show_debug_heading $window.draw_circle(@position.x, @position.y, radius, 9999, @debug_color) if @debug_text.text != "" - $window.draw_rect(@debug_text.x-10, (@debug_text.y-10), @debug_text.width+20, @debug_text.height+20, Gosu::Color.rgba(0,0,0,200), 9999) + $window.draw_rect(@debug_text.x - 10, (@debug_text.y - 10), @debug_text.width + 20, @debug_text.height + 20, + Gosu::Color.rgba(0, 0, 0, 200), 9999) @debug_text.draw end end @@ -64,13 +69,13 @@ module CyberarmEngine def debug_text(text) @debug_text.text = text - @debug_text.x = @position.x-(@debug_text.width / 2) - @debug_text.y = @position.y-(@debug_text.height + self.radius + self.height) + @debug_text.x = @position.x - (@debug_text.width / 2) + @debug_text.y = @position.y - (@debug_text.height + radius + height) end def scale if @scale_x == @scale_y - return @scale_x + @scale_x else false # maths? @@ -80,7 +85,7 @@ module CyberarmEngine def scale=(int) self.scale_x = int self.scale_y = int - self.radius = ((@image.width+@image.height)/4)*self.scale + self.radius = ((@image.width + @image.height) / 4) * scale end def visible @@ -97,16 +102,16 @@ module CyberarmEngine end def _x_visible - self.x.between?(($window.width/2)-(@world_center_point.x), ($window.width/2)+@world_center_point.x) || - self.x.between?(((@world_center_point.x)-$window.width/2), ($window.width/2)+@world_center_point.x) + x.between?(($window.width / 2) - @world_center_point.x, ($window.width / 2) + @world_center_point.x) || + x.between?((@world_center_point.x - $window.width / 2), ($window.width / 2) + @world_center_point.x) end def _y_visible - self.y.between?(($window.height/2)-(@world_center_point.y), ($window.height/2)+@world_center_point.y) || - self.y.between?((@world_center_point.y)-($window.height/2), ($window.height/2)+@world_center_point.y) + y.between?(($window.height / 2) - @world_center_point.y, ($window.height / 2) + @world_center_point.y) || + y.between?(@world_center_point.y - ($window.height / 2), ($window.height / 2) + @world_center_point.y) end - def heading(ahead_by = 100, object = nil, angle_only = false) + def heading(ahead_by = 100, _object = nil, angle_only = false) direction = Gosu.angle(@last_position.x, @last_position.x, @position.x, position.y).gosu_to_radians _x = @position.x + (ahead_by * Math.cos(direction)) @@ -122,11 +127,11 @@ module CyberarmEngine end def width - @image ? @image.width * self.scale : 0 + @image ? @image.width * scale : 0 end def height - @image ? @image.height * self.scale : 0 + @image ? @image.height * scale : 0 end def pause @@ -138,8 +143,8 @@ module CyberarmEngine end def rotate(int) - self.angle+=int - self.angle%=360 + self.angle += int + self.angle %= 360 end def alpha=(int) # 0-255 @@ -149,7 +154,7 @@ module CyberarmEngine end def draw_rect(x, y, width, height, color, z = 0) - $window.draw_rect(x,y,width,height,color,z) + $window.draw_rect(x, y, width, height, color, z) end def button_up(id) @@ -163,14 +168,14 @@ module CyberarmEngine best_distance = 100_000_000_000 # Huge default number game_object_class.all.each do |object| - distance = Gosu::distance(self.x, self.y, object.x, object.y) + distance = Gosu.distance(x, y, object.x, object.y) if distance <= best_distance best_object = object best_distance = distance end end - return best_object + best_object end def look_at(object) @@ -178,31 +183,24 @@ module CyberarmEngine end def circle_collision?(object) - distance = Gosu.distance(self.x, self.y, object.x, object.y) - if distance <= self.radius+object.radius - true - else - false - end + distance = Gosu.distance(x, y, object.x, object.y) + distance <= radius + object.radius end # Duplication... so DRY. - def each_circle_collision(object, resolve_with = :width, &block) + def each_circle_collision(object, _resolve_with = :width, &block) if object.class != Class && object.instance_of?(object.class) - $window.current_state.game_objects.select {|i| i.class == object.class}.each do |o| - distance = Gosu.distance(self.x, self.y, object.x, object.y) - if distance <= self.radius+object.radius - block.call(o, object) if block - end + $window.current_state.game_objects.select { |i| i.instance_of?(object.class) }.each do |o| + distance = Gosu.distance(x, y, object.x, object.y) + block.call(o, object) if distance <= radius + object.radius && block end else - list = $window.current_state.game_objects.select {|i| i.class == object} + list = $window.current_state.game_objects.select { |i| i.instance_of?(object) } list.each do |o| next if self == o - distance = Gosu.distance(self.x, self.y, o.x, o.y) - if distance <= self.radius+o.radius - block.call(self, o) if block - end + + distance = Gosu.distance(x, y, o.x, o.y) + block.call(self, o) if distance <= radius + o.radius && block end end end @@ -210,35 +208,30 @@ module CyberarmEngine def destroy if $window.current_state $window.current_state.game_objects.each do |o| - if o.is_a?(self.class) && o == self - $window.current_state.game_objects.delete(o) - end + $window.current_state.game_objects.delete(o) if o.is_a?(self.class) && o == self end end end # NOTE: This could be implemented more reliably def all - INSTANCES.select {|i| i.class == self} + INSTANCES.select { |i| i.instance_of?(self) } end - def self.each_circle_collision(object, resolve_with = :width, &block) + def self.each_circle_collision(object, _resolve_with = :width, &block) if object.class != Class && object.instance_of?(object.class) - $window.current_state.game_objects.select {|i| i.class == self}.each do |o| + $window.current_state.game_objects.select { |i| i.instance_of?(self) }.each do |o| distance = Gosu.distance(o.x, o.y, object.x, object.y) - if distance <= o.radius+object.radius - block.call(o, object) if block - end + block.call(o, object) if distance <= o.radius + object.radius && block end else - lista = $window.current_state.game_objects.select {|i| i.class == self} - listb = $window.current_state.game_objects.select {|i| i.class == object} + lista = $window.current_state.game_objects.select { |i| i.instance_of?(self) } + listb = $window.current_state.game_objects.select { |i| i.instance_of?(object) } lista.product(listb).each do |o, o2| next if o == o2 + distance = Gosu.distance(o.x, o.y, o2.x, o2.y) - if distance <= o.radius+o2.radius - block.call(o, o2) if block - end + block.call(o, o2) if distance <= o.radius + o2.radius && block end end end @@ -247,11 +240,9 @@ module CyberarmEngine INSTANCES.clear if $window.current_state $window.current_state.game_objects.each do |o| - if o.is_a?(self.class) - $window.current_state.game_objects.delete(o) - end + $window.current_state.game_objects.delete(o) if o.is_a?(self.class) end end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/game_state.rb b/lib/cyberarm_engine/game_state.rb index 21f9809..5d64833 100644 --- a/lib/cyberarm_engine/game_state.rb +++ b/lib/cyberarm_engine/game_state.rb @@ -5,7 +5,7 @@ module CyberarmEngine attr_accessor :options, :global_pause attr_reader :game_objects - def initialize(options={}) + def initialize(options = {}) @options = options @game_objects = [] @global_pause = false @@ -26,7 +26,10 @@ module CyberarmEngine end def draw_bounding_box(box) - x,y, max_x, max_y = box.x, box.y, box.max_x, box.max_y + x = box.x + y = box.y + max_x = box.max_x + max_y = box.max_y color = Gosu::Color.rgba(255, 127, 64, 240) @@ -86,4 +89,4 @@ module CyberarmEngine @game_objects << object end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/model.rb b/lib/cyberarm_engine/model.rb index f038def..494febd 100644 --- a/lib/cyberarm_engine/model.rb +++ b/lib/cyberarm_engine/model.rb @@ -1,55 +1,48 @@ module CyberarmEngine class Model - attr_accessor :objects, :materials, :vertices, :uvs, :texures, :normals, :faces, :colors, :bones - attr_accessor :material_file, :current_material, :current_object, :vertex_count, :smoothing - attr_reader :position, :bounding_box, :textured_material, :file_path - - attr_reader :positions_buffer_id, :colors_buffer_id, :normals_buffer_id, :uvs_buffer_id, :textures_buffer_id - attr_reader :vertex_array_id - attr_reader :aabb_tree + attr_accessor :objects, :materials, :vertices, :uvs, :texures, :normals, :faces, :colors, :bones, :material_file, + :current_material, :current_object, :vertex_count, :smoothing + attr_reader :position, :bounding_box, :textured_material, :file_path, :positions_buffer_id, :colors_buffer_id, + :normals_buffer_id, :uvs_buffer_id, :textures_buffer_id, :vertex_array_id, :aabb_tree def initialize(file_path:) @file_path = file_path @material_file = nil @current_object = nil - @current_material=nil - @vertex_count = 0 + @current_material = nil + @vertex_count = 0 - @objects = [] - @materials= {} + @objects = [] + @materials = {} @vertices = [] @colors = [] @uvs = [] @normals = [] @faces = [] @bones = [] - @smoothing= 0 + @smoothing = 0 @bounding_box = BoundingBox.new start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) type = File.basename(file_path).split(".").last.to_sym parser = Model::Parser.find(type) - unless parser - raise "Unsupported model type '.#{type}', supported models are: #{Model::Parser.supported_formats}" - end + raise "Unsupported model type '.#{type}', supported models are: #{Model::Parser.supported_formats}" unless parser parse(parser) @has_texture = false - @materials.each do |key, material| - if material.texture_id - @has_texture = true - end + @materials.each do |_key, material| + @has_texture = true if material.texture_id end allocate_gl_objects populate_vertex_buffer configure_vao - @objects.each {|o| @vertex_count+=o.vertices.size} + @objects.each { |o| @vertex_count += o.vertices.size } start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) # build_collision_tree @@ -87,28 +80,28 @@ module CyberarmEngine @vertex_array_id = nil buffer = " " * 4 glGenVertexArrays(1, buffer) - @vertex_array_id = buffer.unpack('L2').first + @vertex_array_id = buffer.unpack1("L2") # Allocate buffers for future use @positions_buffer_id = nil buffer = " " * 4 glGenBuffers(1, buffer) - @positions_buffer_id = buffer.unpack('L2').first + @positions_buffer_id = buffer.unpack1("L2") @colors_buffer_id = nil buffer = " " * 4 glGenBuffers(1, buffer) - @colors_buffer_id = buffer.unpack('L2').first + @colors_buffer_id = buffer.unpack1("L2") @normals_buffer_id = nil buffer = " " * 4 glGenBuffers(1, buffer) - @normals_buffer_id = buffer.unpack('L2').first + @normals_buffer_id = buffer.unpack1("L2") @uvs_buffer_id = nil buffer = " " * 4 glGenBuffers(1, buffer) - @uvs_buffer_id = buffer.unpack('L2').first + @uvs_buffer_id = buffer.unpack1("L2") end def populate_vertex_buffer @@ -122,16 +115,15 @@ module CyberarmEngine colors << face.colors.map { |color| [color.red, color.green, color.blue] } norms << face.normals.map { |vert| [vert.x, vert.y, vert.z, vert.weight] } - if has_texture? - uvs << face.uvs.map { |vert| [vert.x, vert.y, vert.z] } - end + uvs << face.uvs.map { |vert| [vert.x, vert.y, vert.z] } if has_texture? end glBindBuffer(GL_ARRAY_BUFFER, @positions_buffer_id) glBufferData(GL_ARRAY_BUFFER, pos.flatten.size * Fiddle::SIZEOF_FLOAT, pos.flatten.pack("f*"), GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, @colors_buffer_id) - glBufferData(GL_ARRAY_BUFFER, colors.flatten.size * Fiddle::SIZEOF_FLOAT, colors.flatten.pack("f*"), GL_STATIC_DRAW) + glBufferData(GL_ARRAY_BUFFER, colors.flatten.size * Fiddle::SIZEOF_FLOAT, colors.flatten.pack("f*"), + GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, @normals_buffer_id) glBufferData(GL_ARRAY_BUFFER, norms.flatten.size * Fiddle::SIZEOF_FLOAT, norms.flatten.pack("f*"), GL_STATIC_DRAW) diff --git a/lib/cyberarm_engine/model/material.rb b/lib/cyberarm_engine/model/material.rb index 1e27cb3..8e3d068 100644 --- a/lib/cyberarm_engine/model/material.rb +++ b/lib/cyberarm_engine/model/material.rb @@ -3,11 +3,12 @@ module CyberarmEngine class Material attr_accessor :name, :ambient, :diffuse, :specular attr_reader :texture_id + def initialize(name) @name = name @ambient = Color.new(1, 1, 1, 1) @diffuse = Color.new(1, 1, 1, 1) - @specular= Color.new(1, 1, 1, 1) + @specular = Color.new(1, 1, 1, 1) @texture = nil @texture_id = nil end diff --git a/lib/cyberarm_engine/model/model_object.rb b/lib/cyberarm_engine/model/model_object.rb index 9faf28a..3fca694 100644 --- a/lib/cyberarm_engine/model/model_object.rb +++ b/lib/cyberarm_engine/model/model_object.rb @@ -13,7 +13,7 @@ module CyberarmEngine @faces = [] @materials = [] @bounding_box = BoundingBox.new - @debug_color = Color.new(1.0,1.0,1.0) + @debug_color = Color.new(1.0, 1.0, 1.0) @scale = 1.0 @@ -46,9 +46,10 @@ module CyberarmEngine @faces.each do |face| face.vertices.each do |v| next unless v - list << v.x*@scale - list << v.y*@scale - list << v.z*@scale + + list << v.x * @scale + list << v.y * @scale + list << v.z * @scale list << v.weight end end @@ -57,7 +58,7 @@ module CyberarmEngine @vertices_list = list.pack("f*") end - return @vertices_list + @vertices_list end def flattened_vertices_size @@ -70,6 +71,7 @@ module CyberarmEngine @faces.each do |face| face.uvs.each do |v| next unless v + list << v.x list << v.y list << v.z @@ -80,7 +82,7 @@ module CyberarmEngine @uvs_list = list.pack("f*") end - return @uvs_list + @uvs_list end def flattened_normals @@ -89,6 +91,7 @@ module CyberarmEngine @faces.each do |face| face.normals.each do |n| next unless n + list << n.x list << n.y list << n.z @@ -99,7 +102,7 @@ module CyberarmEngine @normals_list = list.pack("f*") end - return @normals_list + @normals_list end def flattened_materials @@ -108,8 +111,8 @@ module CyberarmEngine @faces.each do |face| material = face.material next unless material - face.vertices.each do # Add material to each vertex + face.vertices.each do # Add material to each vertex list << material.diffuse.red list << material.diffuse.green list << material.diffuse.blue @@ -121,7 +124,7 @@ module CyberarmEngine @materials_list = list.pack("f*") end - return @materials_list + @materials_list end end end diff --git a/lib/cyberarm_engine/model/parser.rb b/lib/cyberarm_engine/model/parser.rb index 1d9ba89..3aa803c 100644 --- a/lib/cyberarm_engine/model/parser.rb +++ b/lib/cyberarm_engine/model/parser.rb @@ -9,7 +9,8 @@ module CyberarmEngine @@parsers = [] def self.handles - raise NotImplementedError, "Model::Parser#handles must return an array of file extensions that this parser supports" + raise NotImplementedError, + "Model::Parser#handles must return an array of file extensions that this parser supports" end def self.inherited(parser) @@ -17,11 +18,9 @@ module CyberarmEngine end def self.find(file_type) - found_parser = @@parsers.find do |parser| + @@parsers.find do |parser| parser.handles.include?(file_type) end - - return found_parser end def self.supported_formats @@ -72,4 +71,4 @@ module CyberarmEngine end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/model/parsers/collada_parser.rb b/lib/cyberarm_engine/model/parsers/collada_parser.rb index 18064e6..8db39cd 100644 --- a/lib/cyberarm_engine/model/parsers/collada_parser.rb +++ b/lib/cyberarm_engine/model/parsers/collada_parser.rb @@ -57,7 +57,7 @@ module CyberarmEngine array = positions.at_css("[id=\"#{id}-positions-array\"]") stride = Integer(positions.at_css("[source=\"##{id}-positions-array\"]").attributes["stride"].value) - list = array.children.first.to_s.split(" ").map{ |f| Float(f) }.each_slice(stride).each do |slice| + list = array.children.first.to_s.split(" ").map { |f| Float(f) }.each_slice(stride).each do |slice| position = Vector.new(*slice) @model.current_object.vertices << position @model.vertices << position @@ -69,7 +69,7 @@ module CyberarmEngine array = normals.at_css("[id=\"#{id}-normals-array\"]") stride = Integer(normals.at_css("[source=\"##{id}-normals-array\"]").attributes["stride"].value) - list = array.children.first.to_s.split(" ").map{ |f| Float(f) }.each_slice(stride).each do |slice| + list = array.children.first.to_s.split(" ").map { |f| Float(f) }.each_slice(stride).each do |slice| normal = Vector.new(*slice) @model.current_object.normals << normal @model.normals << normal @@ -81,20 +81,23 @@ module CyberarmEngine def project_node(name) @collada.css("library_visual_scenes visual_scene node").each do |node| - if node.attributes["name"].value == name - transform = Transform.new( node.at_css("matrix").children.first.to_s.split(" ").map { |f| Float(f) } ) + next unless node.attributes["name"].value == name - @model.current_object.vertices.each do |vert| - v = vert.multiply_transform(transform) - vert.x, vert.y, vert.z, vert.w = v.x, v.y, v.z, v.w - end + transform = Transform.new(node.at_css("matrix").children.first.to_s.split(" ").map { |f| Float(f) }) - break + @model.current_object.vertices.each do |vert| + v = vert.multiply_transform(transform) + vert.x = v.x + vert.y = v.y + vert.z = v.z + vert.w = v.w end + + break end end - def build_faces(id, mesh) + def build_faces(_id, mesh) material_name = mesh.at_css("triangles").attributes["material"].value set_material(material_name) @@ -116,7 +119,7 @@ module CyberarmEngine face.normals = [] face.colors = [] face.material = current_material - face.smoothing= @model.smoothing + face.smoothing = @model.smoothing slice.each do |index| face.vertices << @model.vertices[index] @@ -132,4 +135,4 @@ module CyberarmEngine end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/model/parsers/wavefront_parser.rb b/lib/cyberarm_engine/model/parsers/wavefront_parser.rb index 274bee8..5dfc8af 100644 --- a/lib/cyberarm_engine/model/parsers/wavefront_parser.rb +++ b/lib/cyberarm_engine/model/parsers/wavefront_parser.rb @@ -8,29 +8,29 @@ module CyberarmEngine lines = 0 list = File.read(@model.file_path).split("\n") list.each do |line| - lines+=1 + lines += 1 line = line.strip - array = line.split(' ') + array = line.split(" ") case array[0] - when 'mtllib' + when "mtllib" @model.material_file = array[1] parse_mtllib - when 'usemtl' + when "usemtl" set_material(array[1]) - when 'o' + when "o" change_object(nil, array[1]) - when 's' + when "s" set_smoothing(array[1]) - when 'v' + when "v" add_vertex(array) - when 'vt' + when "vt" add_texture_coordinate(array) - when 'vn' + when "vn" add_normal(array) - when 'f' + when "f" verts = [] uvs = [] norms = [] @@ -46,22 +46,21 @@ module CyberarmEngine face.normals = [] face.colors = [] face.material = current_material - face.smoothing= @model.smoothing + face.smoothing = @model.smoothing mat = face.material.diffuse color = mat verts.each_with_index do |v, index| - if uvs.first != "" - face.vertices << @model.vertices[Integer(v)-1] - face.uvs << @model.uvs[Integer(uvs[index])-1] - face.normals << @model.normals[Integer(norms[index])-1] + face.vertices << @model.vertices[Integer(v) - 1] + face.uvs << @model.uvs[Integer(uvs[index]) - 1] + face.normals << @model.normals[Integer(norms[index]) - 1] face.colors << color else - face.vertices << @model.vertices[Integer(v)-1] + face.vertices << @model.vertices[Integer(v) - 1] face.uvs << nil - face.normals << @model.normals[Integer(norms[index])-1] + face.normals << @model.normals[Integer(norms[index]) - 1] face.colors << color end end @@ -78,43 +77,42 @@ module CyberarmEngine end def parse_mtllib - file = File.open(@model.file_path.sub(File.basename(@model.file_path), '')+@model.material_file, 'r') + file = File.open(@model.file_path.sub(File.basename(@model.file_path), "") + @model.material_file, "r") file.readlines.each do |line| - array = line.strip.split(' ') + array = line.strip.split(" ") case array.first - when 'newmtl' + when "newmtl" material = Model::Material.new(array.last) @model.current_material = array.last @model.materials[array.last] = material - when 'Ns' # Specular Exponent - when 'Ka' # Ambient color - @model.materials[@model.current_material].ambient = Color.new(Float(array[1]), Float(array[2]), Float(array[3])) - when 'Kd' # Diffuse color - @model.materials[@model.current_material].diffuse = Color.new(Float(array[1]), Float(array[2]), Float(array[3])) - when 'Ks' # Specular color - @model.materials[@model.current_material].specular = Color.new(Float(array[1]), Float(array[2]), Float(array[3])) - when 'Ke' # Emissive - when 'Ni' # Unknown (Blender Specific?) - when 'd' # Dissolved (Transparency) - when 'illum' # Illumination model - when 'map_Kd' # Diffuse texture + when "Ns" # Specular Exponent + when "Ka" # Ambient color + @model.materials[@model.current_material].ambient = Color.new(Float(array[1]), Float(array[2]), + Float(array[3])) + when "Kd" # Diffuse color + @model.materials[@model.current_material].diffuse = Color.new(Float(array[1]), Float(array[2]), + Float(array[3])) + when "Ks" # Specular color + @model.materials[@model.current_material].specular = Color.new(Float(array[1]), Float(array[2]), + Float(array[3])) + when "Ke" # Emissive + when "Ni" # Unknown (Blender Specific?) + when "d" # Dissolved (Transparency) + when "illum" # Illumination model + when "map_Kd" # Diffuse texture texture = File.basename(array[1]) - texture_path = "#{File.expand_path("../../", @model.file_path)}/textures/#{texture}" + texture_path = "#{File.expand_path('../../', @model.file_path)}/textures/#{texture}" @model.materials[@model.current_material].set_texture(texture_path) end end end def set_smoothing(value) - if value == "1" - @model.smoothing = true - else - @model.smoothing = false - end + @model.smoothing = value == "1" end def add_vertex(array) - @model.vertex_count+=1 + @model.vertex_count += 1 vert = nil if array.size == 5 vert = Vector.new(Float(array[1]), Float(array[2]), Float(array[3]), Float(array[4])) @@ -143,9 +141,9 @@ module CyberarmEngine def add_texture_coordinate(array) texture = nil if array.size == 4 - texture = Vector.new(Float(array[1]), 1-Float(array[2]), Float(array[3])) + texture = Vector.new(Float(array[1]), 1 - Float(array[2]), Float(array[3])) elsif array.size == 3 - texture = Vector.new(Float(array[1]), 1-Float(array[2]), 1.0) + texture = Vector.new(Float(array[1]), 1 - Float(array[2]), 1.0) else raise end diff --git a/lib/cyberarm_engine/model_cache.rb b/lib/cyberarm_engine/model_cache.rb index ca123a3..3eb89d3 100644 --- a/lib/cyberarm_engine/model_cache.rb +++ b/lib/cyberarm_engine/model_cache.rb @@ -8,23 +8,19 @@ module CyberarmEngine type = File.basename(model_file).split(".").last.to_sym if model = load_model_from_cache(type, model_file) - return model + model else model = CyberarmEngine::Model.new(file_path: model_file) cache_model(type, model_file, model) - return model + model end end def self.load_model_from_cache(type, model_file) - if CACHE[type].is_a?(Hash) - if CACHE[type][model_file] - return CACHE[type][model_file] - end - end + return CACHE[type][model_file] if CACHE[type].is_a?(Hash) && (CACHE[type][model_file]) - return false + false end def self.cache_model(type, model_file, model) diff --git a/lib/cyberarm_engine/opengl.rb b/lib/cyberarm_engine/opengl.rb index 3eb17f5..870eba9 100644 --- a/lib/cyberarm_engine/opengl.rb +++ b/lib/cyberarm_engine/opengl.rb @@ -7,10 +7,10 @@ end module CyberarmEngine def gl_error? - e = glGetError() + e = glGetError if e != GL_NO_ERROR - $stderr.puts "OpenGL error detected by handler at: #{caller[0]}" - $stderr.puts " #{gluErrorString(e)} (#{e})\n" + warn "OpenGL error detected by handler at: #{caller[0]}" + warn " #{gluErrorString(e)} (#{e})\n" exit if window.exit_on_opengl_error? end end @@ -25,4 +25,4 @@ require_relative "opengl/orthographic_camera" require_relative "opengl/renderer/g_buffer" require_relative "opengl/renderer/bounding_box_renderer" require_relative "opengl/renderer/opengl_renderer" -require_relative "opengl/renderer/renderer" \ No newline at end of file +require_relative "opengl/renderer/renderer" diff --git a/lib/cyberarm_engine/opengl/light.rb b/lib/cyberarm_engine/opengl/light.rb index 8301567..cbeea7e 100644 --- a/lib/cyberarm_engine/opengl/light.rb +++ b/lib/cyberarm_engine/opengl/light.rb @@ -6,16 +6,17 @@ module CyberarmEngine attr_reader :light_id attr_accessor :type, :ambient, :diffuse, :specular, :position, :direction, :intensity + def initialize( - id:, - type: Light::POINT, - ambient: Vector.new(0.5, 0.5, 0.5), - diffuse: Vector.new(1, 1, 1), - specular: Vector.new(0.2, 0.2, 0.2), - position: Vector.new(0, 0, 0), - direction: Vector.new(0, 0, 0), - intensity: 1 - ) + id:, + type: Light::POINT, + ambient: Vector.new(0.5, 0.5, 0.5), + diffuse: Vector.new(1, 1, 1), + specular: Vector.new(0.2, 0.2, 0.2), + position: Vector.new(0, 0, 0), + direction: Vector.new(0, 0, 0), + intensity: 1 + ) @light_id = id @type = type @@ -40,9 +41,9 @@ module CyberarmEngine def convert(struct, apply_intensity = false) if apply_intensity - return struct.to_a.compact.map{ |i| i * @intensity } + struct.to_a.compact.map { |i| i * @intensity } else - return struct.to_a.compact + struct.to_a.compact end end end diff --git a/lib/cyberarm_engine/opengl/orthographic_camera.rb b/lib/cyberarm_engine/opengl/orthographic_camera.rb index 2df57a6..6eef8b8 100644 --- a/lib/cyberarm_engine/opengl/orthographic_camera.rb +++ b/lib/cyberarm_engine/opengl/orthographic_camera.rb @@ -2,17 +2,21 @@ module CyberarmEngine class OrthographicCamera attr_accessor :position, :orientation, :zoom, :left, :right, :bottom, :top, :min_view_distance, :max_view_distance + def initialize( - position:, orientation: Vector.new(0, 0, 0), - zoom: 1, left: 0, right:, bottom: 0, top:, - min_view_distance: 0.1, max_view_distance: 200.0 - ) + position:, right:, top:, orientation: Vector.new(0, 0, 0), + zoom: 1, left: 0, bottom: 0, + min_view_distance: 0.1, max_view_distance: 200.0 + ) @position = position @orientation = orientation @zoom = zoom - @left, @right, @bottom, @top = left, right, bottom, top + @left = left + @right = right + @bottom = bottom + @top = top @min_view_distance = min_view_distance @max_view_distance = max_view_distance diff --git a/lib/cyberarm_engine/opengl/perspective_camera.rb b/lib/cyberarm_engine/opengl/perspective_camera.rb index 4ba029c..1eb7fff 100644 --- a/lib/cyberarm_engine/opengl/perspective_camera.rb +++ b/lib/cyberarm_engine/opengl/perspective_camera.rb @@ -2,7 +2,9 @@ module CyberarmEngine class PerspectiveCamera attr_accessor :position, :orientation, :aspect_ratio, :field_of_view, :min_view_distance, :max_view_distance - def initialize(position:, orientation: Vector.new(0, 0, 0), aspect_ratio:, field_of_view: 70.0, min_view_distance: 0.1, max_view_distance: 155.0) + + def initialize(position:, aspect_ratio:, orientation: Vector.new(0, 0, + 0), field_of_view: 70.0, min_view_distance: 0.1, max_view_distance: 155.0) @position = position @orientation = orientation diff --git a/lib/cyberarm_engine/opengl/renderer/bounding_box_renderer.rb b/lib/cyberarm_engine/opengl/renderer/bounding_box_renderer.rb index 3048288..cbb424e 100644 --- a/lib/cyberarm_engine/opengl/renderer/bounding_box_renderer.rb +++ b/lib/cyberarm_engine/opengl/renderer/bounding_box_renderer.rb @@ -1,6 +1,7 @@ module CyberarmEngine class BoundingBoxRenderer attr_reader :bounding_boxes, :vertex_count + def initialize @bounding_boxes = {} @vertex_count = 0 @@ -8,7 +9,7 @@ module CyberarmEngine def render(entities) entities.each do |entity| - create_bounding_box(entity,color = nil) + create_bounding_box(entity, color = nil) draw_bounding_boxes end @@ -43,7 +44,7 @@ module CyberarmEngine colors = mesh_colors(color) vertices = mesh_vertices(box) - @vertex_count+=vertices.size + @vertex_count += vertices.size @bounding_boxes[entity_id][:vertices_size] = vertices.size @bounding_boxes[entity_id][:vertices] = vertices.pack("f*") @@ -58,7 +59,7 @@ module CyberarmEngine colors = mesh_colors(mesh.debug_color) vertices = mesh_vertices(box) - @vertex_count+=vertices.size + @vertex_count += vertices.size data[:vertices_size] = vertices.size data[:vertices] = vertices.pack("f*") @@ -71,48 +72,48 @@ module CyberarmEngine def mesh_normals [ - 0,1,0, - 0,1,0, - 0,1,0, - 0,1,0, - 0,1,0, - 0,1,0, + 0, 1, 0, + 0, 1, 0, + 0, 1, 0, + 0, 1, 0, + 0, 1, 0, + 0, 1, 0, - 0,-1,0, - 0,-1,0, - 0,-1,0, - 0,-1,0, - 0,-1,0, - 0,-1,0, + 0, -1, 0, + 0, -1, 0, + 0, -1, 0, + 0, -1, 0, + 0, -1, 0, + 0, -1, 0, - 0,0,1, - 0,0,1, - 0,0,1, - 0,0,1, - 0,0,1, - 0,0,1, + 0, 0, 1, + 0, 0, 1, + 0, 0, 1, + 0, 0, 1, + 0, 0, 1, + 0, 0, 1, - 1,0,0, - 1,0,0, - 1,0,0, - 1,0,0, - 1,0,0, - 1,0,0, + 1, 0, 0, + 1, 0, 0, + 1, 0, 0, + 1, 0, 0, + 1, 0, 0, + 1, 0, 0, - -1,0,0, - -1,0,0, - -1,0,0, - -1,0,0, - -1,0,0, - -1,0,0, + -1, 0, 0, + -1, 0, 0, + -1, 0, 0, + -1, 0, 0, + -1, 0, 0, + -1, 0, 0, - -1,0,0, - -1,0,0, - -1,0,0, + -1, 0, 0, + -1, 0, 0, + -1, 0, 0, - -1,0,0, - -1,0,0, - -1,0,0 + -1, 0, 0, + -1, 0, 0, + -1, 0, 0 ] end @@ -219,7 +220,7 @@ module CyberarmEngine bounding_box[:entity].position.z ) draw_bounding_box(bounding_box) - @bounding_boxes[key][:objects].each {|o| draw_bounding_box(o)} + @bounding_boxes[key][:objects].each { |o| draw_bounding_box(o) } glPopMatrix end diff --git a/lib/cyberarm_engine/opengl/renderer/g_buffer.rb b/lib/cyberarm_engine/opengl/renderer/g_buffer.rb index a9ee892..302bc78 100644 --- a/lib/cyberarm_engine/opengl/renderer/g_buffer.rb +++ b/lib/cyberarm_engine/opengl/renderer/g_buffer.rb @@ -1,11 +1,13 @@ module CyberarmEngine class GBuffer attr_reader :screen_vbo, :vertices, :uvs + def initialize(width:, height:) - @width, @height = width, height + @width = width + @height = height @framebuffer = nil - @buffers = [:position, :diffuse, :normal, :texcoord] + @buffers = %i[position diffuse normal texcoord] @textures = {} @screen_vbo = nil @ready = false @@ -16,9 +18,9 @@ module CyberarmEngine -1.0, 1.0, 0, -1.0, 1.0, 0, - 1.0, -1.0, 0, - 1.0, 1.0, 0, - ].freeze + 1.0, -1.0, 0, + 1.0, 1.0, 0 + ].freeze @uvs = [ 0, 0, @@ -35,9 +37,9 @@ module CyberarmEngine end def create_framebuffer - buffer = ' ' * 4 + buffer = " " * 4 glGenFramebuffers(1, buffer) - @framebuffer = buffer.unpack('L2').first + @framebuffer = buffer.unpack1("L2") glBindFramebuffer(GL_DRAW_FRAMEBUFFER, @framebuffer) @@ -48,20 +50,20 @@ module CyberarmEngine if status != GL_FRAMEBUFFER_COMPLETE message = "" - case status - when GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT - message = "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT" - when GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT - message = "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT" - when GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER - message = "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER" - when GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER - message = "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER" - when GL_FRAMEBUFFER_UNSUPPORTED - message = "GL_FRAMEBUFFER_UNSUPPORTED" - else - message = "Unknown error!" - end + message = case status + when GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT + "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT" + when GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT + "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT" + when GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER + "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER" + when GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER + "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER" + when GL_FRAMEBUFFER_UNSUPPORTED + "GL_FRAMEBUFFER_UNSUPPORTED" + else + "Unknown error!" + end puts "Incomplete framebuffer: #{status}\nError: #{message}" else @ready = true @@ -72,9 +74,9 @@ module CyberarmEngine def create_textures @buffers.size.times do |i| - buffer = ' ' * 4 + buffer = " " * 4 glGenTextures(1, buffer) - texture_id = buffer.unpack('L2').first + texture_id = buffer.unpack1("L2") @textures[@buffers[i]] = texture_id glBindTexture(GL_TEXTURE_2D, texture_id) @@ -84,39 +86,39 @@ module CyberarmEngine glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, texture_id, 0) end - buffer = ' ' * 4 + buffer = " " * 4 glGenTextures(1, buffer) - texture_id = buffer.unpack('L2').first + texture_id = buffer.unpack1("L2") @textures[:depth] = texture_id glBindTexture(GL_TEXTURE_2D, texture_id) glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, @width, @height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nil) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texture_id, 0) - draw_buffers = [ GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 ] + draw_buffers = [GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3] glDrawBuffers(draw_buffers.size, draw_buffers.pack("I*")) end def create_screen_vbo - buffer = ' ' * 4 + buffer = " " * 4 glGenVertexArrays(1, buffer) - @screen_vbo = buffer.unpack('L2').first + @screen_vbo = buffer.unpack1("L2") buffer = " " * 4 glGenBuffers(1, buffer) - @positions_buffer_id = buffer.unpack('L2').first + @positions_buffer_id = buffer.unpack1("L2") buffer = " " * 4 glGenBuffers(1, buffer) - @uvs_buffer_id = buffer.unpack('L2').first + @uvs_buffer_id = buffer.unpack1("L2") glBindVertexArray(@screen_vbo) glBindBuffer(GL_ARRAY_BUFFER, @positions_buffer_id) - glBufferData(GL_ARRAY_BUFFER, @vertices.size * Fiddle::SIZEOF_FLOAT, @vertices.pack("f*"), GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, @vertices.size * Fiddle::SIZEOF_FLOAT, @vertices.pack("f*"), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nil) glBindBuffer(GL_ARRAY_BUFFER, @uvs_buffer_id) - glBufferData(GL_ARRAY_BUFFER, @uvs.size * Fiddle::SIZEOF_FLOAT, @uvs.pack("f*"), GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, @uvs.size * Fiddle::SIZEOF_FLOAT, @uvs.pack("f*"), GL_STATIC_DRAW) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nil) glEnableVertexAttribArray(0) @@ -159,4 +161,4 @@ module CyberarmEngine gl_error? end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/opengl/renderer/opengl_renderer.rb b/lib/cyberarm_engine/opengl/renderer/opengl_renderer.rb index 7d6b06c..d60fcb6 100644 --- a/lib/cyberarm_engine/opengl/renderer/opengl_renderer.rb +++ b/lib/cyberarm_engine/opengl/renderer/opengl_renderer.rb @@ -3,8 +3,10 @@ module CyberarmEngine @@immediate_mode_warning = false attr_accessor :show_wireframe + def initialize(width:, height:, show_wireframe: false) - @width, @height = width, height + @width = width + @height = height @show_wireframe = show_wireframe @g_buffer = GBuffer.new(width: @width, height: @height) @@ -63,7 +65,9 @@ module CyberarmEngine @g_buffer.unbind_framebuffer gl_error? else - puts "Shaders are disabled or failed to compile, using immediate mode for rendering..." unless @@immediate_mode_warning + unless @@immediate_mode_warning + puts "Shaders are disabled or failed to compile, using immediate mode for rendering..." + end @@immediate_mode_warning = true gl_error? @@ -141,8 +145,8 @@ module CyberarmEngine glBindTexture(GL_TEXTURE_2D, @g_buffer.texture(:depth)) shader.uniform_integer("depth", 4) - lights.each_with_index do |light, i| - shader.uniform_integer("light[0].type", light.type); + lights.each_with_index do |light, _i| + shader.uniform_integer("light[0].type", light.type) shader.uniform_vec3("light[0].direction", light.direction) shader.uniform_vec3("light[0].position", light.position) shader.uniform_vec3("light[0].diffuse", light.diffuse) @@ -229,7 +233,7 @@ module CyberarmEngine end def draw_mesh(model) - model.objects.each_with_index do |o, i| + model.objects.each_with_index do |o, _i| glEnable(GL_COLOR_MATERIAL) glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE) glShadeModel(GL_FLAT) unless o.faces.first[4] @@ -255,16 +259,16 @@ module CyberarmEngine glPolygonOffset(2, 0.5) glLineWidth(3) - glDrawArrays(GL_TRIANGLES, 0, o.flattened_vertices_size/4) + glDrawArrays(GL_TRIANGLES, 0, o.flattened_vertices_size / 4) glLineWidth(1) glPolygonOffset(0, 0) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glEnable(GL_LIGHTING) - glDrawArrays(GL_TRIANGLES, 0, o.flattened_vertices_size/4) + glDrawArrays(GL_TRIANGLES, 0, o.flattened_vertices_size / 4) else - glDrawArrays(GL_TRIANGLES, 0, o.flattened_vertices_size/4) + glDrawArrays(GL_TRIANGLES, 0, o.flattened_vertices_size / 4) end # glBindBuffer(GL_ARRAY_BUFFER, 0) diff --git a/lib/cyberarm_engine/opengl/shader.rb b/lib/cyberarm_engine/opengl/shader.rb index 0d214f1..79bbea9 100644 --- a/lib/cyberarm_engine/opengl/shader.rb +++ b/lib/cyberarm_engine/opengl/shader.rb @@ -22,9 +22,7 @@ module CyberarmEngine if shader @@shaders.delete(name) - if shader.compiled? - glDeleteProgram(shader.program) - end + glDeleteProgram(shader.program) if shader.compiled? end end @@ -68,15 +66,15 @@ module CyberarmEngine # returns currently active {Shader}, if one is active # # @return [Shader?] - def self.active_shader - @active_shader + class << self + attr_reader :active_shader end # sets currently active {Shader} # # @param instance [Shader] instance of {Shader} to set as active - def self.active_shader=(instance) - @active_shader = instance + class << self + attr_writer :active_shader end # stops using currently active {Shader} @@ -94,7 +92,8 @@ module CyberarmEngine # # @param variable [String] def self.attribute_location(variable) - raise RuntimeError, "No active shader!" unless Shader.active_shader + raise "No active shader!" unless Shader.active_shader + Shader.active_shader.attribute_location(variable) end @@ -103,12 +102,14 @@ module CyberarmEngine # @param variable [String] # @param value def self.set_uniform(variable, value) - raise RuntimeError, "No active shader!" unless Shader.active_shader + raise "No active shader!" unless Shader.active_shader + Shader.active_shader.set_uniform(variable, value) end attr_reader :name, :program - def initialize(name:, includes_dir: nil, vertex: "shaders/default.vert", fragment:) + + def initialize(name:, fragment:, includes_dir: nil, vertex: "shaders/default.vert") raise "Shader name can not be blank" if name.length == 0 @name = name @@ -120,7 +121,7 @@ module CyberarmEngine @error_buffer_size = 1024 * 8 @variable_missing = {} - @data = {shaders: {}} + @data = { shaders: {} } unless shader_files_exist?(vertex: vertex, fragment: fragment) raise ArgumentError, "Shader files not found: #{vertex} or #{fragment}" @@ -133,7 +134,7 @@ module CyberarmEngine compile_shader(type: :fragment) link_shaders - @data[:shaders].each { |key, id| glDeleteShader(id) } + @data[:shaders].each { |_key, id| glDeleteShader(id) } # Only add shader if it successfully compiles if @compiled @@ -175,7 +176,7 @@ module CyberarmEngine _size = [processed_source.length].pack("I") glShaderSource(_shader, 1, _source, _size) - @data[:shaders][type] =_shader + @data[:shaders][type] = _shader end # evaluates shader preprocessors @@ -199,22 +200,25 @@ module CyberarmEngine lines = source.lines lines.each_with_index do |line, i| - if line.start_with?(PREPROCESSOR_CHARACTER) - preprocessor = line.strip.split(" ") - lines.delete(line) + next unless line.start_with?(PREPROCESSOR_CHARACTER) - case preprocessor.first - when "@include" - raise ArgumentError, "Shader preprocessor include directory was not given for shader #{@name}" unless @includes_dir + preprocessor = line.strip.split(" ") + lines.delete(line) - preprocessor[1..preprocessor.length - 1].join.scan(/"([^"]*)"/).flatten.each do |file| - source = File.read("#{@includes_dir}/#{file}.glsl") - - lines.insert(i, source) - end - else - warn "Unsupported preprocessor #{preprocessor.first} for #{@name}" + case preprocessor.first + when "@include" + unless @includes_dir + raise ArgumentError, + "Shader preprocessor include directory was not given for shader #{@name}" end + + preprocessor[1..preprocessor.length - 1].join.scan(/"([^"]*)"/).flatten.each do |file| + source = File.read("#{@includes_dir}/#{file}.glsl") + + lines.insert(i, source) + end + else + warn "Unsupported preprocessor #{preprocessor.first} for #{@name}" end end @@ -230,12 +234,12 @@ module CyberarmEngine raise ArgumentError, "No shader for #{type.inspect}" unless _shader glCompileShader(_shader) - buffer = ' ' + buffer = " " glGetShaderiv(_shader, GL_COMPILE_STATUS, buffer) - compiled = buffer.unpack('L')[0] + compiled = buffer.unpack1("L") if compiled == 0 - log = ' ' * @error_buffer_size + log = " " * @error_buffer_size glGetShaderInfoLog(_shader, @error_buffer_size, nil, log) puts "Shader Error: Program \"#{@name}\"" puts " #{type.to_s.capitalize} Shader InfoLog:", " #{log.strip.split("\n").join("\n ")}\n\n" @@ -246,7 +250,7 @@ module CyberarmEngine _compiled = true end - return _compiled + _compiled end # link compiled OpenGL Shaders in to a OpenGL Program @@ -261,18 +265,18 @@ module CyberarmEngine end glLinkProgram(@program) - buffer = ' ' + buffer = " " glGetProgramiv(@program, GL_LINK_STATUS, buffer) - linked = buffer.unpack('L')[0] + linked = buffer.unpack1("L") if linked == 0 - log = ' ' * @error_buffer_size + log = " " * @error_buffer_size glGetProgramInfoLog(@program, @error_buffer_size, nil, log) puts "Shader Error: Program \"#{@name}\"" puts " Program InfoLog:", " #{log.strip.split("\n").join("\n ")}\n\n" end - @compiled = linked == 0 ? false : true + @compiled = !(linked == 0) end # Returns the location of a uniform _variable_ @@ -281,18 +285,22 @@ module CyberarmEngine # @return [Integer] location of uniform def variable(variable) loc = glGetUniformLocation(@program, variable) - if (loc == -1) - puts "Shader Error: Program \"#{@name}\" has no such uniform named \"#{variable}\"", " Is it used in the shader? GLSL may have optimized it out.", " Is it miss spelled?" unless @variable_missing[variable] + if loc == -1 + unless @variable_missing[variable] + puts "Shader Error: Program \"#{@name}\" has no such uniform named \"#{variable}\"", + " Is it used in the shader? GLSL may have optimized it out.", " Is it miss spelled?" + end @variable_missing[variable] = true end - return loc + loc end # @see Shader.use Shader.use def use(&block) return unless compiled? raise "Another shader is already in use! #{Shader.active_shader.name.inspect}" if Shader.active_shader - Shader.active_shader=self + + Shader.active_shader = self glUseProgram(@program) @@ -331,7 +339,7 @@ module CyberarmEngine # @param location [Integer] # @return [void] def uniform_transform(variable, value, location = nil) - attr_loc = location ? location : attribute_location(variable) + attr_loc = location || attribute_location(variable) glUniformMatrix4fv(attr_loc, 1, GL_FALSE, value.to_gl.pack("F16")) end @@ -343,7 +351,7 @@ module CyberarmEngine # @param location [Integer] # @return [void] def uniform_boolean(variable, value, location = nil) - attr_loc = location ? location : attribute_location(variable) + attr_loc = location || attribute_location(variable) glUniform1i(attr_loc, value ? 1 : 0) end @@ -354,7 +362,7 @@ module CyberarmEngine # @param location [Integer] # @return [void] def uniform_integer(variable, value, location = nil) - attr_loc = location ? location : attribute_location(variable) + attr_loc = location || attribute_location(variable) glUniform1i(attr_loc, value) end @@ -366,7 +374,7 @@ module CyberarmEngine # @param location [Integer] # @return [void] def uniform_float(variable, value, location = nil) - attr_loc = location ? location : attribute_location(variable) + attr_loc = location || attribute_location(variable) glUniform1f(attr_loc, value) end @@ -378,7 +386,7 @@ module CyberarmEngine # @param location [Integer] # @return [void] def uniform_vec3(variable, value, location = nil) - attr_loc = location ? location : attribute_location(variable) + attr_loc = location || attribute_location(variable) glUniform3f(attr_loc, *value.to_a[0..2]) end @@ -390,7 +398,7 @@ module CyberarmEngine # @param location [Integer] # @return [void] def uniform_vec4(variable, value, location = nil) - attr_loc = location ? location : attribute_location(variable) + attr_loc = location || attribute_location(variable) glUniform4f(attr_loc, *value.to_a) end diff --git a/lib/cyberarm_engine/opengl/texture.rb b/lib/cyberarm_engine/opengl/texture.rb index 8df9836..a1e9b60 100644 --- a/lib/cyberarm_engine/opengl/texture.rb +++ b/lib/cyberarm_engine/opengl/texture.rb @@ -1,6 +1,6 @@ module CyberarmEngine class Texture - DEFAULT_TEXTURE = "#{CYBERARM_ENGINE_ROOT_PATH}/assets/textures/default.png" + DEFAULT_TEXTURE = "#{CYBERARM_ENGINE_ROOT_PATH}/assets/textures/default.png".freeze CACHE = {} @@ -11,12 +11,14 @@ module CyberarmEngine end def self.from_cache(path, retro) - return CACHE.dig("#{path}?retro=#{retro}") + CACHE.dig("#{path}?retro=#{retro}") end attr_reader :id + def initialize(path: nil, image: nil, retro: false) raise "keyword :path or :image must be provided!" if path.nil? && image.nil? + @retro = retro @path = path @@ -47,9 +49,9 @@ module CyberarmEngine def create_from_image(image) array_of_pixels = image.to_blob - tex_names_buf = ' ' * 4 + tex_names_buf = " " * 4 glGenTextures(1, tex_names_buf) - texture_id = tex_names_buf.unpack('L2').first + texture_id = tex_names_buf.unpack1("L2") glBindTexture(GL_TEXTURE_2D, texture_id) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, array_of_pixels) @@ -61,7 +63,7 @@ module CyberarmEngine glGenerateMipmap(GL_TEXTURE_2D) gl_error? - return texture_id + texture_id end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ray.rb b/lib/cyberarm_engine/ray.rb index 76aa62a..21e379e 100644 --- a/lib/cyberarm_engine/ray.rb +++ b/lib/cyberarm_engine/ray.rb @@ -4,7 +4,7 @@ module CyberarmEngine raise "Origin must be a Vector!" unless origin.is_a?(Vector) raise "Direction must be a Vector!" unless direction.is_a?(Vector) - @origin = origin + @origin = origin @direction = direction @range = range @@ -42,15 +42,15 @@ module CyberarmEngine tmin = max(tmin, min(tz1, tz2)) tmax = min(tmax, max(tz1, tz2)) - return tmax >= max(tmin, 0.0); + tmax >= max(tmin, 0.0) end def min(x, y) - ((x) < (y) ? (x) : (y)) + ((x) < (y) ? x : y) end def max(x, y) - ((x) > (y) ? (x) : (y)) + ((x) > (y) ? x : y) end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/stats.rb b/lib/cyberarm_engine/stats.rb index 9a9205a..459c296 100644 --- a/lib/cyberarm_engine/stats.rb +++ b/lib/cyberarm_engine/stats.rb @@ -13,9 +13,9 @@ module CyberarmEngine end def self.clear - @@hash.each do |key, value| + @@hash.each do |key, _value| @@hash[key] = 0 end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/text.rb b/lib/cyberarm_engine/text.rb index f1d4c72..1bfb982 100644 --- a/lib/cyberarm_engine/text.rb +++ b/lib/cyberarm_engine/text.rb @@ -5,7 +5,7 @@ module CyberarmEngine attr_accessor :x, :y, :z, :size, :options attr_reader :text, :textobject, :factor_x, :factor_y, :color, :shadow, :shadow_size, :shadow_alpha, :shadow_color - def initialize(text, options={}) + def initialize(text, options = {}) @text = text.to_s || "" @options = options @size = options[:size] || 18 @@ -17,28 +17,28 @@ module CyberarmEngine @factor_y = options[:factor_y] || 1 @color = options[:color] || Gosu::Color::WHITE @mode = options[:mode] || :default - @alignment= options[:alignment] || nil + @alignment = options[:alignment] || nil @shadow = true if options[:shadow] == true @shadow = false if options[:shadow] == false - @shadow = true if options[:shadow] == nil - @shadow_size = options[:shadow_size] ? options[:shadow_size] : 1 - @shadow_alpha= options[:shadow_alpha] ? options[:shadow_alpha] : 30 - @shadow_alpha= options[:shadow_alpha] ? options[:shadow_alpha] : 30 - @shadow_color= options[:shadow_color] + @shadow = true if options[:shadow].nil? + @shadow_size = options[:shadow_size] || 1 + @shadow_alpha = options[:shadow_alpha] || 30 + @shadow_alpha = options[:shadow_alpha] || 30 + @shadow_color = options[:shadow_color] @textobject = check_cache(@size, @font) if @alignment case @alignment when :left - @x = 0+BUTTON_PADDING + @x = 0 + BUTTON_PADDING when :center - @x = ($window.width/2)-(@textobject.text_width(@text)/2) + @x = ($window.width / 2) - (@textobject.text_width(@text) / 2) when :right - @x = $window.width-BUTTON_PADDING-@textobject.text_width(@text) + @x = $window.width - BUTTON_PADDING - @textobject.text_width(@text) end end - return self + self end def check_cache(size, font_name) @@ -62,7 +62,7 @@ module CyberarmEngine CACHE[@size][@font] = font end - return font + font end def text=(string) @@ -74,26 +74,32 @@ module CyberarmEngine @rendered_shadow = nil @factor_x = n end + def factor_y=(n) @rendered_shadow = nil @factor_y = n end + def color=(color) @rendered_shadow = nil @color = color end + def shadow=(boolean) @rendered_shadow = nil @shadow = boolean end + def shadow_size=(n) @rendered_shadow = nil @shadow_size = n end + def shadow_alpha=(n) @rendered_shadow = nil @shadow_alpha = n end + def shadow_color=(n) @rendered_shadow = nil @shadow_color = n @@ -108,32 +114,33 @@ module CyberarmEngine end def height(text = @text) - text.lines.count > 0 ? (text.lines.count) * textobject.height : @textobject.height + text.lines.count > 0 ? text.lines.count * textobject.height : @textobject.height end def draw(method = :draw_markup) if @shadow && !ARGV.join.include?("--no-shadow") shadow_alpha = @color.alpha <= 30 ? @color.alpha : @shadow_alpha - shadow_color = @shadow_color ? @shadow_color : Gosu::Color.rgba(@color.red, @color.green, @color.blue, shadow_alpha) - white = Gosu::Color::WHITE + shadow_color = @shadow_color || Gosu::Color.rgba(@color.red, @color.green, @color.blue, + shadow_alpha) + white = Gosu::Color::WHITE _x = @shadow_size _y = @shadow_size - @rendered_shadow ||= Gosu.render((self.width+(shadow_size*2)).ceil, (self.height+(@shadow_size*2)).ceil) do - @textobject.send(method, @text, _x-@shadow_size, _y, @z, @factor_x, @factor_y, white, :add) - @textobject.send(method, @text, _x-@shadow_size, _y-@shadow_size, @z, @factor_x, @factor_y, white, :add) + @rendered_shadow ||= Gosu.render((width + (shadow_size * 2)).ceil, (height + (@shadow_size * 2)).ceil) do + @textobject.send(method, @text, _x - @shadow_size, _y, @z, @factor_x, @factor_y, white, :add) + @textobject.send(method, @text, _x - @shadow_size, _y - @shadow_size, @z, @factor_x, @factor_y, white, :add) - @textobject.send(method, @text, _x, _y-@shadow_size, @z, @factor_x, @factor_y, white, :add) - @textobject.send(method, @text, _x+@shadow_size, _y-@shadow_size, @z, @factor_x, @factor_y, white, :add) + @textobject.send(method, @text, _x, _y - @shadow_size, @z, @factor_x, @factor_y, white, :add) + @textobject.send(method, @text, _x + @shadow_size, _y - @shadow_size, @z, @factor_x, @factor_y, white, :add) - @textobject.send(method, @text, _x, _y+@shadow_size, @z, @factor_x, @factor_y, white, :add) - @textobject.send(method, @text, _x-@shadow_size, _y+@shadow_size, @z, @factor_x, @factor_y, white, :add) + @textobject.send(method, @text, _x, _y + @shadow_size, @z, @factor_x, @factor_y, white, :add) + @textobject.send(method, @text, _x - @shadow_size, _y + @shadow_size, @z, @factor_x, @factor_y, white, :add) - @textobject.send(method, @text, _x+@shadow_size, _y, @z, @factor_x, @factor_y, white, :add) - @textobject.send(method, @text, _x+@shadow_size, _y+@shadow_size, @z, @factor_x, @factor_y, white, :add) + @textobject.send(method, @text, _x + @shadow_size, _y, @z, @factor_x, @factor_y, white, :add) + @textobject.send(method, @text, _x + @shadow_size, _y + @shadow_size, @z, @factor_x, @factor_y, white, :add) end - @rendered_shadow.draw(@x-@shadow_size, @y-@shadow_size, @z, @factor_x, @factor_y, shadow_color) + @rendered_shadow.draw(@x - @shadow_size, @y - @shadow_size, @z, @factor_x, @factor_y, shadow_color) end @textobject.send(method, @text, @x, @y, @z, @factor_x, @factor_y, @color, @mode) @@ -147,6 +154,7 @@ module CyberarmEngine @color.alpha end - def update; end + def update + end end end diff --git a/lib/cyberarm_engine/timer.rb b/lib/cyberarm_engine/timer.rb index 092dfc9..ec153c5 100644 --- a/lib/cyberarm_engine/timer.rb +++ b/lib/cyberarm_engine/timer.rb @@ -20,4 +20,4 @@ module CyberarmEngine end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/transform.rb b/lib/cyberarm_engine/transform.rb index f5878b6..88c9489 100644 --- a/lib/cyberarm_engine/transform.rb +++ b/lib/cyberarm_engine/transform.rb @@ -2,11 +2,12 @@ module CyberarmEngine # Basic 4x4 matrix operations class Transform attr_reader :elements + def initialize(matrix) @elements = matrix raise "Transform is wrong size! Got #{@elements.size}, expected 16" if 16 != @elements.size - raise "Invalid value for matrix, must all be numeric!" if @elements.any? { |e| e.nil? || !e.is_a?(Numeric)} + raise "Invalid value for matrix, must all be numeric!" if @elements.any? { |e| e.nil? || !e.is_a?(Numeric) } end def self.identity @@ -27,10 +28,10 @@ module CyberarmEngine double c = Math.cos(angle).degrees_to_radians double s = Math.sin(angle).degrees_to_radians matrix = [ - +c, +s, 0, 0, - -s, +c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1, + +c, +s, 0, 0, + -s, +c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 ] rotate_matrix = Transform.new(matrix, rows: 4, columns: 4) @@ -44,7 +45,7 @@ module CyberarmEngine ) end - return rotate_matrix + rotate_matrix end # 2d translate operation, replicates Gosu's Gosu.translate function @@ -54,7 +55,7 @@ module CyberarmEngine 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, - x, y, z, 1, + x, y, z, 1 ] Transform.new(matrix) @@ -67,7 +68,7 @@ module CyberarmEngine scale_x, 0, 0, 0, 0, scale_y, 0, 0, 0, 0, scale_z, 0, - 0, 0, 0, 1, + 0, 0, 0, 1 ] scale_matrix = Transform.new(matrix) @@ -81,7 +82,7 @@ module CyberarmEngine ) end - return scale_matrix + scale_matrix end def self.concat(left, right) @@ -107,13 +108,13 @@ module CyberarmEngine 1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, - 0, 0, 0, 1, + 0, 0, 0, 1 ] Transform.new(matrix) end - def self.rotate_3d(vector, order = "zyx") + def self.rotate_3d(vector, _order = "zyx") x, y, z = vector.to_a[0..2].map { |axis| axis * Math::PI / 180.0 } rotation_x = Transform.new( @@ -163,7 +164,7 @@ module CyberarmEngine x * x * n + c, x * y * n - z * s, x * z * n + y * s, 0, y * x * n + z * s, y * y * n + c, y * z * n - x * s, 0, x * z * n - y * s, y * z * n + x * s, z * z * n + c, 0, - 0, 0, 0, 1.0 + 0, 0, 0, 1.0 ] ) end @@ -190,7 +191,7 @@ module CyberarmEngine [ f / aspect_ratio, 0.0, 0.0, 0.0, 0.0, f, 0.0, 0.0, - 0.0, 0.0, zn, zf, + 0.0, 0.0, zn, zf, 0.0, 0.0, -1.0, 0.0 ] ) @@ -200,13 +201,13 @@ module CyberarmEngine s = Vector.new( 2 / (right - left.to_f), 2 / (top - bottom.to_f), - -2 / (far - near.to_f), + -2 / (far - near.to_f) ) t = Vector.new( (right + left.to_f) / (right - left.to_f), (top + bottom.to_f) / (top - bottom.to_f), - (far + near.to_f) / (far - near.to_f), + (far + near.to_f) / (far - near.to_f) ) Transform.new( @@ -232,16 +233,15 @@ module CyberarmEngine Transform.new( [ - x_axis.x, y_axis.y, z_axis.z, 0, - x_axis.x, y_axis.y, z_axis.z, 0, - x_axis.x, y_axis.y, z_axis.z, 0, + x_axis.x, y_axis.y, z_axis.z, 0, + x_axis.x, y_axis.y, z_axis.z, 0, + x_axis.x, y_axis.y, z_axis.z, 0, -x_axis.dot(eye), -y_axis.dot(eye), -z_axis.dot(eye), 1 ] ) end def *(other) - case other when CyberarmEngine::Vector matrix = @elements.clone @@ -254,7 +254,7 @@ module CyberarmEngine Transform.new(matrix) when CyberarmEngine::Transform - return multiply_matrices(other) + multiply_matrices(other) else p other.class raise TypeError, "Expected CyberarmEngine::Vector or CyberarmEngine::Transform got #{other.class}" @@ -279,7 +279,7 @@ module CyberarmEngine end end - return Transform.new(matrix) + Transform.new(matrix) end # arranges Matrix in column major form @@ -293,4 +293,4 @@ module CyberarmEngine ] end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/border_canvas.rb b/lib/cyberarm_engine/ui/border_canvas.rb index 7fc945d..96a495c 100644 --- a/lib/cyberarm_engine/ui/border_canvas.rb +++ b/lib/cyberarm_engine/ui/border_canvas.rb @@ -1,6 +1,7 @@ module CyberarmEngine class BorderCanvas attr_reader :element, :top, :right, :bottom, :left + def initialize(element:) @element = element @@ -25,7 +26,7 @@ module CyberarmEngine elsif color.is_a?(Array) if color.size == 1 - color=color.first + color = color.first elsif color.size == 2 @top.background = color.first @@ -61,7 +62,7 @@ module CyberarmEngine def update # TOP - @top.x = @element.x# + @element.border_thickness_left + @top.x = @element.x # + @element.border_thickness_left @top.y = @element.y @top.z = @element.z @@ -98,4 +99,4 @@ module CyberarmEngine @left.update end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/dsl.rb b/lib/cyberarm_engine/ui/dsl.rb index cefb3fe..b47d6d4 100644 --- a/lib/cyberarm_engine/ui/dsl.rb +++ b/lib/cyberarm_engine/ui/dsl.rb @@ -12,70 +12,70 @@ module CyberarmEngine options[:parent] = element_parent options[:theme] = current_theme - add_element( Element::Label.new(text, options, block) ) + add_element(Element::Label.new(text, options, block)) end def button(text, options = {}, &block) options[:parent] = element_parent options[:theme] = current_theme - add_element( Element::Button.new(text, options, block) { if block.is_a?(Proc); block.call; end } ) + add_element(Element::Button.new(text, options, block) { block.call if block.is_a?(Proc) }) end def list_box(options = {}, &block) options[:parent] = element_parent options[:theme] = current_theme - add_element( Element::ListBox.new(options, block) { if block.is_a?(Proc); block.call; end } ) + add_element(Element::ListBox.new(options, block) { block.call if block.is_a?(Proc) }) end def edit_line(text, options = {}, &block) options[:parent] = element_parent options[:theme] = current_theme - add_element( Element::EditLine.new(text, options, block) ) + add_element(Element::EditLine.new(text, options, block)) end def edit_box(text, options = {}, &block) options[:parent] = element_parent options[:theme] = current_theme - add_element( Element::EditBox.new(text, options, block) ) + add_element(Element::EditBox.new(text, options, block)) end def toggle_button(options = {}, &block) options[:parent] = element_parent options[:theme] = current_theme - add_element( Element::ToggleButton.new(options, block) ) + add_element(Element::ToggleButton.new(options, block)) end def check_box(text, options = {}, &block) options[:parent] = element_parent options[:theme] = current_theme - add_element( Element::CheckBox.new(text, options, block) ) + add_element(Element::CheckBox.new(text, options, block)) end def image(path, options = {}, &block) options[:parent] = element_parent options[:theme] = current_theme - add_element( Element::Image.new(path, options, block) ) + add_element(Element::Image.new(path, options, block)) end def progress(options = {}, &block) options[:parent] = element_parent options[:theme] = current_theme - add_element( Element::Progress.new(options, block) ) + add_element(Element::Progress.new(options, block)) end def slider(options = {}, &block) options[:parent] = element_parent options[:theme] = current_theme - add_element( Element::Slider.new(options, block) ) + add_element(Element::Slider.new(options, block)) end def background(color = Gosu::Color::NONE) @@ -93,7 +93,7 @@ module CyberarmEngine private def add_element(element) element_parent.add(element) - return element + element end private def element_parent @@ -114,7 +114,7 @@ module CyberarmEngine $__current_container__ = old_parent - return _container + _container end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/element.rb b/lib/cyberarm_engine/ui/element.rb index ab9a5b0..2b49eae 100644 --- a/lib/cyberarm_engine/ui/element.rb +++ b/lib/cyberarm_engine/ui/element.rb @@ -16,7 +16,7 @@ module CyberarmEngine @focus = false @enabled = true @visible = true - @tip = @options[:tip] ? @options[:tip] : "" + @tip = @options[:tip] || "" @style = Style.new(options) @@ -102,7 +102,7 @@ module CyberarmEngine end def default_events - [:left, :middle, :right].each do |button| + %i[left middle right].each do |button| event(:"#{button}_mouse_button") event(:"released_#{button}_mouse_button") event(:"clicked_#{button}_mouse_button") @@ -152,7 +152,7 @@ module CyberarmEngine @style.background_canvas.draw @style.border_canvas.draw - Gosu.clip_to(@x,@y, width, height) do + Gosu.clip_to(@x, @y, width, height) do render end end @@ -166,7 +166,7 @@ module CyberarmEngine def button_up(id) end - def draggable?(button) + def draggable?(_button) false end @@ -175,7 +175,7 @@ module CyberarmEngine def hit?(x, y) x.between?(@x, @x + width) && - y.between?(@y, @y + height) + y.between?(@y, @y + height) end def width @@ -227,11 +227,11 @@ module CyberarmEngine end def dimensional_size(size, dimension) - raise "dimension must be either :width or :height" unless dimension == :width || dimension == :height + raise "dimension must be either :width or :height" unless %i[width height].include?(dimension) if size && size.is_a?(Numeric) if size.between?(0.0, 1.0) - ((@parent.send(:"content_#{dimension}") - self.send(:"noncontent_#{dimension}")) * size).round + ((@parent.send(:"content_#{dimension}") - send(:"noncontent_#{dimension}")) * size).round else size end @@ -239,7 +239,7 @@ module CyberarmEngine end def background=(_background) - @style.background_canvas.background=(_background) + @style.background_canvas.background = (_background) update_background end @@ -288,12 +288,12 @@ module CyberarmEngine raise "#{self.class}#value was not overridden!" end - def value=(value) + def value=(_value) raise "#{self.class}#value= was not overridden!" end def to_s - "#{self.class} x=#{x} y=#{y} width=#{width} height=#{height} value=#{ value.is_a?(String) ? "\"#{value}\"" : value }" + "#{self.class} x=#{x} y=#{y} width=#{width} height=#{height} value=#{value.is_a?(String) ? "\"#{value}\"" : value}" end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/elements/button.rb b/lib/cyberarm_engine/ui/elements/button.rb index 0ce7b86..64cd8bb 100644 --- a/lib/cyberarm_engine/ui/elements/button.rb +++ b/lib/cyberarm_engine/ui/elements/button.rb @@ -2,11 +2,11 @@ module CyberarmEngine class Element class Button < Label def initialize(text_or_image, options = {}, block = nil) - @image, @scale_x, @scale_y = nil, 1, 1 + @image = nil + @scale_x = 1 + @scale_y = 1 - if text_or_image.is_a?(Gosu::Image) - @image = text_or_image - end + @image = text_or_image if text_or_image.is_a?(Gosu::Image) super(text_or_image, options, block) @@ -26,14 +26,15 @@ module CyberarmEngine @style.border_thickness_left + @style.padding_left + @x, @style.border_thickness_top + @style.padding_top + @y, @z + 2, - @scale_x, @scale_y, @text.color) + @scale_x, @scale_y, @text.color + ) end def draw_text @text.draw end - def enter(sender) + def enter(_sender) @focus = false unless window.button_down?(Gosu::MsLeft) if @focus @@ -44,49 +45,50 @@ module CyberarmEngine @text.color = default(:hover, :color) end - return :handled + :handled end - def left_mouse_button(sender, x, y) + def left_mouse_button(_sender, _x, _y) @focus = true @style.background_canvas.background = default(:active, :background) window.current_state.focus = self @text.color = default(:active, :color) - return :handled + :handled end - def released_left_mouse_button(sender,x, y) + def released_left_mouse_button(sender, _x, _y) enter(sender) - return :handled + :handled end - def clicked_left_mouse_button(sender, x, y) + def clicked_left_mouse_button(_sender, _x, _y) @block.call(self) if @block - return :handled + :handled end - def leave(sender) + def leave(_sender) @style.background_canvas.background = default(:background) @text.color = default(:color) - return :handled + :handled end - def blur(sender) + def blur(_sender) @focus = false - return :handled + :handled end def recalculate if @image - @width, @height = 0, 0 + @width = 0 + @height = 0 _width = dimensional_size(@style.image_width, :width) - _height= dimensional_size(@style.image_height,:height) + _height = dimensional_size(@style.image_height, :height) if _width && _height @scale_x = _width.to_f / @image.width @@ -98,11 +100,12 @@ module CyberarmEngine @scale_y = _height.to_f / @image.height @scale_x = @scale_y else - @scale_x, @scale_y = 1, 1 + @scale_x = 1 + @scale_y = 1 end - @width = _width ? _width : @image.width.round * @scale_x - @height= _height ? _height : @image.height.round * @scale_y + @width = _width || @image.width.round * @scale_x + @height = _height || @image.height.round * @scale_y update_background else @@ -111,7 +114,7 @@ module CyberarmEngine end def value - @image ? @image : super + @image || super end def value=(value) @@ -121,7 +124,8 @@ module CyberarmEngine super end - old_width, old_height = width, height + old_width = width + old_height = height recalculate root.gui_state.request_recalculate if old_width != width || old_height != height @@ -130,4 +134,4 @@ module CyberarmEngine end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/elements/check_box.rb b/lib/cyberarm_engine/ui/elements/check_box.rb index 47958dc..f456314 100644 --- a/lib/cyberarm_engine/ui/elements/check_box.rb +++ b/lib/cyberarm_engine/ui/elements/check_box.rb @@ -48,4 +48,4 @@ module CyberarmEngine end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/elements/container.rb b/lib/cyberarm_engine/ui/elements/container.rb index 38ecf12..4c29d1f 100644 --- a/lib/cyberarm_engine/ui/elements/container.rb +++ b/lib/cyberarm_engine/ui/elements/container.rb @@ -4,14 +4,14 @@ module CyberarmEngine include Common attr_accessor :stroke_color, :fill_color - attr_reader :children, :gui_state - attr_reader :scroll_x, :scroll_y + attr_reader :children, :gui_state, :scroll_x, :scroll_y def initialize(options = {}, block = nil) @gui_state = options.delete(:gui_state) super - @scroll_x, @scroll_y = 0, 0 + @scroll_x = 0 + @scroll_y = 0 @scroll_speed = 10 @text_color = options[:color] @@ -49,27 +49,27 @@ module CyberarmEngine @children.each(&:draw) end - if false#DEBUG + if false # DEBUG Gosu.flush Gosu.draw_line( - self.x, self.y, Gosu::Color::RED, - self.x + outer_width, self.y, Gosu::Color::RED, + x, y, Gosu::Color::RED, + x + outer_width, y, Gosu::Color::RED, Float::INFINITY ) Gosu.draw_line( - self.x + outer_width, self.y, Gosu::Color::RED, - self.x + outer_width, self.y + outer_height, Gosu::Color::RED, + x + outer_width, y, Gosu::Color::RED, + x + outer_width, y + outer_height, Gosu::Color::RED, Float::INFINITY ) Gosu.draw_line( - self.x + outer_width, self.y + outer_height, Gosu::Color::RED, - self.x, self.y + outer_height, Gosu::Color::RED, + x + outer_width, y + outer_height, Gosu::Color::RED, + x, y + outer_height, Gosu::Color::RED, Float::INFINITY ) Gosu.draw_line( - self.x, outer_height, Gosu::Color::RED, - self.x, self.y, Gosu::Color::RED, + x, outer_height, Gosu::Color::RED, + x, y, Gosu::Color::RED, Float::INFINITY ) end @@ -110,13 +110,14 @@ module CyberarmEngine @width = @style.width = window.width @height = @style.height = window.height else - @width, @height = 0, 0 + @width = 0 + @height = 0 _width = dimensional_size(@style.width, :width) - _height= dimensional_size(@style.height,:height) + _height = dimensional_size(@style.height, :height) - @width = _width ? _width : (@children.map {|c| c.x + c.outer_width }.max || 0).round - @height = _height ? _height : (@children.map {|c| c.y + c.outer_height}.max || 0).round + @width = _width || (@children.map { |c| c.x + c.outer_width }.max || 0).round + @height = _height || (@children.map { |c| c.y + c.outer_height }.max || 0).round end # Move child to parent after positioning @@ -140,13 +141,17 @@ module CyberarmEngine def max_width _width = dimensional_size(@style.width, :width) - _width ? outer_width : window.width - (@parent ? @parent.style.margin_right + @style.margin_right : @style.margin_right) + if _width + outer_width + else + window.width - (@parent ? @parent.style.margin_right + @style.margin_right : @style.margin_right) + end end def fits_on_line?(element) # Flow p [@options[:id], @width] if @options[:id] @current_position.x + element.outer_width <= max_width && - @current_position.x + element.outer_width <= window.width + @current_position.x + element.outer_width <= window.width end def position_on_current_line(element) # Flow @@ -157,14 +162,14 @@ module CyberarmEngine @current_position.x = @style.margin_left if @current_position.x >= max_width end - def tallest_neighbor(querier, y_position) # Flow + def tallest_neighbor(querier, _y_position) # Flow response = querier @children.each do |child| response = child if child.outer_height > response.outer_height break if child == querier end - return response + response end def position_on_next_line(child) # Flow @@ -195,17 +200,17 @@ module CyberarmEngine # end def value - @children.map {|c| c.class}.join(", ") + @children.map { |c| c.class }.join(", ") end def to_s "#{self.class} x=#{x} y=#{y} width=#{width} height=#{height} children=#{@children.size}" end - def write_tree(indent = "", index = 0) + def write_tree(indent = "", _index = 0) puts self - indent = indent + " " + indent += " " @children.each_with_index do |child, i| print "#{indent}#{i}: " diff --git a/lib/cyberarm_engine/ui/elements/edit_box.rb b/lib/cyberarm_engine/ui/elements/edit_box.rb index b5c7162..f92fd36 100644 --- a/lib/cyberarm_engine/ui/elements/edit_box.rb +++ b/lib/cyberarm_engine/ui/elements/edit_box.rb @@ -12,14 +12,14 @@ module CyberarmEngine down: false, repeat_delay: 50, last_repeat: 0, - action: proc {move(:up)} + action: proc { move(:up) } }, { key: Gosu::KB_DOWN, down: false, repeat_delay: 50, last_repeat: 0, - action: proc {move(:down)} + action: proc { move(:down) } } ] end @@ -31,26 +31,26 @@ module CyberarmEngine calculate_active_line @repeatable_keys.each do |key| - if key[:down] - if Gosu.milliseconds > key[:last_repeat] + key[:repeat_delay] - key[:action].call - key[:last_repeat] = Gosu.milliseconds - end + if key[:down] && (Gosu.milliseconds > key[:last_repeat] + key[:repeat_delay]) + key[:action].call + key[:last_repeat] = Gosu.milliseconds end end end def draw_caret - Gosu.draw_rect(caret_position, @text.y + @active_line * @text.textobject.height, @caret_width, @caret_height, @caret_color, @z) + Gosu.draw_rect(caret_position, @text.y + @active_line * @text.textobject.height, @caret_width, @caret_height, + @caret_color, @z) end def draw_selection selection_width = caret_position - selection_start_position - Gosu.draw_rect(selection_start_position, @text.y, selection_width, @text.textobject.height, default(:selection_color), @z) + Gosu.draw_rect(selection_start_position, @text.y, selection_width, @text.textobject.height, + default(:selection_color), @z) end - def text_input_position_for(method) + def text_input_position_for(_method) line = @text_input.text[0...@text_input.caret_pos].lines.last _x = @text.x + @offset_x @@ -68,11 +68,11 @@ module CyberarmEngine def calculate_active_line sub_text = @text_input.text[0...@text_input.caret_pos] - @active_line = sub_text.lines.size-1 + @active_line = sub_text.lines.size - 1 end def caret_stay_left_of_last_newline - @text_input.text+="\n" unless @text_input.text.end_with?("\n") + @text_input.text += "\n" unless @text_input.text.end_with?("\n") eof = @text_input.text.chomp.length set_position(eof) if @text_input.caret_pos > eof @@ -94,7 +94,7 @@ module CyberarmEngine end def move_caret_to_mouse(mouse_x, mouse_y) - set_position( caret_position_under_mouse(mouse_x, mouse_y) ) + set_position(caret_position_under_mouse(mouse_x, mouse_y)) end def row_at(y) @@ -108,27 +108,27 @@ module CyberarmEngine buffer = @text_input.text.lines.first if row == 0 line = @text_input.text.lines[row] - line = "" unless line + line ||= "" column = 0 - line.length.times do |i| + line.length.times do |_i| break if @text.textobject.text_width(line[0...column]) >= (x - @text.x).clamp(0.0, Float::INFINITY) column += 1 end - return column + column end def button_down(id) super @repeatable_keys.detect do |key| - if key[:key] == id - key[:down] = true - key[:last_repeat] = Gosu.milliseconds + key[:repeat_delay] - return true - end + next unless key[:key] == id + + key[:down] = true + key[:last_repeat] = Gosu.milliseconds + key[:repeat_delay] + return true end case id @@ -159,6 +159,7 @@ module CyberarmEngine return if @active_line == 0 when :down return if @active_line == @text_input.text.chomp.lines + text = @text_input.text.chomp.lines[0..@active_line].join("\n") pos = text.length end @@ -166,7 +167,7 @@ module CyberarmEngine set_position(pos) end - def drag_update(sender, x, y, button) + def drag_update(_sender, x, y, _button) int = caret_position_under_mouse(x, y) int = 0 if int < 0 @text_input.caret_pos = int @@ -175,4 +176,4 @@ module CyberarmEngine end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/elements/edit_line.rb b/lib/cyberarm_engine/ui/elements/edit_line.rb index 49f56e0..31a17aa 100644 --- a/lib/cyberarm_engine/ui/elements/edit_line.rb +++ b/lib/cyberarm_engine/ui/elements/edit_line.rb @@ -8,11 +8,11 @@ module CyberarmEngine @type = default(:type) @caret_width = default(:caret_width) - @caret_height= @text.textobject.height + @caret_height = @text.textobject.height @caret_color = default(:caret_color) @caret_interval = default(:caret_interval) @caret_last_interval = Gosu.milliseconds - @show_caret = true + @show_caret = true @text_input = Gosu::TextInput.new @text_input.text = text @@ -26,7 +26,8 @@ module CyberarmEngine end end - @offset_x, @offset_y = 0, 0 + @offset_x = 0 + @offset_y = 0 event(:begin_drag) event(:drag_update) @@ -58,16 +59,16 @@ module CyberarmEngine end def update - if @type == :password - @text.text = default(:password_character) * @text_input.text.length - else - @text.text = @text_input.text - end + @text.text = if @type == :password + default(:password_character) * @text_input.text.length + else + @text_input.text + end - if @last_text_value != self.value - @last_text_value = self.value + if @last_text_value != value + @last_text_value = value - publish(:changed, self.value) + publish(:changed, value) end if Gosu.milliseconds >= @caret_last_interval + @caret_interval @@ -85,7 +86,8 @@ module CyberarmEngine def handle_keyboard_shortcuts(id) return unless @focus && @enabled - if Gosu.button_down?(Gosu::KB_LEFT_CONTROL) or Gosu.button_down?(Gosu::KB_RIGHT_CONTROL) + + if Gosu.button_down?(Gosu::KB_LEFT_CONTROL) || Gosu.button_down?(Gosu::KB_RIGHT_CONTROL) case id when Gosu::KB_A @text_input.selection_start = 0 @@ -113,7 +115,8 @@ module CyberarmEngine when Gosu::KB_V if instance_of?(EditLine) # EditLine assumes a single line of text - @text_input.text = @text_input.text.insert(@text_input.caret_pos, Clipboard.paste.encode("UTF-8").gsub("\n", "")) + @text_input.text = @text_input.text.insert(@text_input.caret_pos, + Clipboard.paste.encode("UTF-8").gsub("\n", "")) else @text_input.text = @text_input.text.insert(@text_input.caret_pos, Clipboard.paste.encode("UTF-8")) end @@ -123,15 +126,13 @@ module CyberarmEngine def caret_position_under_mouse(mouse_x) 1.upto(@text.text.length) do |i| - if mouse_x < @text.x - @offset_x + @text.width(@text.text[0...i]) - return i - 1 - end + return i - 1 if mouse_x < @text.x - @offset_x + @text.width(@text.text[0...i]) end @text_input.text.length end - def move_caret_to_mouse(mouse_x, mouse_y) + def move_caret_to_mouse(mouse_x, _mouse_y) @text_input.caret_pos = @text_input.selection_start = caret_position_under_mouse(mouse_x) end @@ -144,16 +145,15 @@ module CyberarmEngine @last_text = @text.text @last_pos = caret_pos - if caret_pos.between?(@offset_x, @width + @offset_x) # Do nothing elsif caret_pos < @offset_x - if caret_pos > @width - @offset_x = caret_pos + @width - else - @offset_x = 0 - end + @offset_x = if caret_pos > @width + caret_pos + @width + else + 0 + end elsif caret_pos > @width @offset_x = caret_pos - @width @@ -189,10 +189,10 @@ module CyberarmEngine move_caret_to_mouse(x, y) - return :handled + :handled end - def enter(sender) + def enter(_sender) if @focus @style.background_canvas.background = default(:active, :background) @text.color = default(:active, :color) @@ -201,31 +201,29 @@ module CyberarmEngine @text.color = default(:hover, :color) end - return :handled + :handled end def leave(sender) - unless @focus - super - end + super unless @focus - return :handled + :handled end - def blur(sender) + def blur(_sender) @focus = false @style.background_canvas.background = default(:background) @text.color = default(:color) window.text_input = nil - return :handled + :handled end def draggable?(button) button == :left end - def begin_drag(sender, x, y, button) + def begin_drag(_sender, x, _y, _button) @drag_start = x @offset_drag_start = @offset_x @drag_caret_position = @text_input.caret_pos @@ -233,14 +231,13 @@ module CyberarmEngine :handled end - def drag_update(sender, x, y, button) + def drag_update(_sender, x, _y, _button) @text_input.caret_pos = caret_position_under_mouse(x) :handled end - def end_drag(sender, x, y, button) - + def end_drag(_sender, _x, _y, _button) :handled end @@ -256,4 +253,4 @@ module CyberarmEngine end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/elements/flow.rb b/lib/cyberarm_engine/ui/elements/flow.rb index 9574f5c..11c6d8d 100644 --- a/lib/cyberarm_engine/ui/elements/flow.rb +++ b/lib/cyberarm_engine/ui/elements/flow.rb @@ -12,4 +12,4 @@ module CyberarmEngine end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/elements/image.rb b/lib/cyberarm_engine/ui/elements/image.rb index 059ce21..9e42111 100644 --- a/lib/cyberarm_engine/ui/elements/image.rb +++ b/lib/cyberarm_engine/ui/elements/image.rb @@ -6,7 +6,8 @@ module CyberarmEngine @path = path @image = Gosu::Image.new(path, retro: @options[:image_retro]) - @scale_x, @scale_y = 1, 1 + @scale_x = 1 + @scale_y = 1 end def render @@ -14,18 +15,19 @@ module CyberarmEngine @style.border_thickness_left + @style.padding_left + @x, @style.border_thickness_top + @style.padding_top + @y, @z + 2, - @scale_x, @scale_y, @style.color) + @scale_x, @scale_y, @style.color + ) end - def clicked_left_mouse_button(sender, x, y) + def clicked_left_mouse_button(_sender, _x, _y) @block.call(self) if @block - return :handled + :handled end def recalculate _width = dimensional_size(@style.width, :width) - _height= dimensional_size(@style.height,:height) + _height = dimensional_size(@style.height, :height) if _width && _height @scale_x = _width.to_f / @image.width @@ -37,11 +39,12 @@ module CyberarmEngine @scale_y = _height.to_f / @image.height @scale_x = @scale_y else - @scale_x, @scale_y = 1, 1 + @scale_x = 1 + @scale_y = 1 end - @width = _width ? _width : @image.width.round * @scale_x - @height= _height ? _height : @image.height.round * @scale_y + @width = _width || @image.width.round * @scale_x + @height = _height || @image.height.round * @scale_y end def value @@ -49,4 +52,4 @@ module CyberarmEngine end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/elements/label.rb b/lib/cyberarm_engine/ui/elements/label.rb index 0c671b9..178877e 100644 --- a/lib/cyberarm_engine/ui/elements/label.rb +++ b/lib/cyberarm_engine/ui/elements/label.rb @@ -5,11 +5,11 @@ module CyberarmEngine super(options, block) @text = Text.new( - text, font: @options[:font], z: @z, color: @options[:color], - size: @options[:text_size], shadow: @options[:text_shadow], - shadow_size: @options[:text_shadow_size], - shadow_color: @options[:text_shadow_color] - ) + text, font: @options[:font], z: @z, color: @options[:color], + size: @options[:text_size], shadow: @options[:text_shadow], + shadow_size: @options[:text_shadow_size], + shadow_color: @options[:text_shadow_color] + ) @raw_text = text end @@ -18,7 +18,7 @@ module CyberarmEngine @text.draw end - def clicked_left_mouse_button(sender, x, y) + def clicked_left_mouse_button(_sender, _x, _y) @block&.call(self) # return :handled @@ -44,11 +44,11 @@ module CyberarmEngine when :left @text.x = @style.border_thickness_left + @style.padding_left + @x when :center - if @text.width <= outer_width - @text.x = @x + outer_width / 2 - @text.width / 2 - else # Act as left aligned - @text.x = @style.border_thickness_left + @style.padding_left + @x - end + @text.x = if @text.width <= outer_width + @x + outer_width / 2 - @text.width / 2 + else # Act as left aligned + @style.border_thickness_left + @style.padding_left + @x + end when :right @text.x = @x + outer_width - (@text.width + @style.border_thickness_right + @style.padding_right) end @@ -84,7 +84,7 @@ module CyberarmEngine if wrap_behavior == :word_wrap max_reach.times do |i| reach = i - break if copy[line_end.floor - i].to_s.match(/[[:punct:]]|[ ]/) + break if copy[line_end.floor - i].to_s.match(/[[:punct:]]| /) end puts "Max width: #{max_width}/#{line_width(@raw_text)} Reach: {#{reach}/#{max_reach}} Line Start: #{line_start}/#{line_end.floor} (#{copy.length}|#{@raw_text.length}) [#{entering_line_end}] '#{copy}' {#{copy[line_start...line_end]}}" @@ -128,4 +128,4 @@ module CyberarmEngine end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/elements/list_box.rb b/lib/cyberarm_engine/ui/elements/list_box.rb index b14aac1..8508e2e 100644 --- a/lib/cyberarm_engine/ui/elements/list_box.rb +++ b/lib/cyberarm_engine/ui/elements/list_box.rb @@ -5,8 +5,8 @@ module CyberarmEngine attr_reader :choose def initialize(options = {}, block = nil) - @items = options[:items] ? options[:items] : [] - @choose = options[:choose] ? options[:choose] : @items.first + @items = options[:items] || [] + @choose = options[:choose] || @items.first super(@choose, options, block) @@ -29,6 +29,7 @@ module CyberarmEngine def choose=(item) valid = @items.detect { |i| i == item } return unless valid # TODO: Throw an error? + @choose = item self.value = item.to_s @@ -36,18 +37,19 @@ module CyberarmEngine recalculate end - def released_left_mouse_button(sender, x, y) + def released_left_mouse_button(_sender, _x, _y) show_menu - return :handled + :handled end def show_menu @menu.clear @items.each do |item| - [ @block] + [@block] block = proc { self.choose = item; @block.call(item) if @block } - b = Button.new(item, { parent: @menu, width: 1.0, theme: @options[:theme], margin: 0, border_color: 0x00ffffff }, block) + b = Button.new(item, + { parent: @menu, width: 1.0, theme: @options[:theme], margin: 0, border_color: 0x00ffffff }, block) @menu.add(b) end @@ -63,4 +65,4 @@ module CyberarmEngine end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/elements/progress.rb b/lib/cyberarm_engine/ui/elements/progress.rb index d54a24d..b566552 100644 --- a/lib/cyberarm_engine/ui/elements/progress.rb +++ b/lib/cyberarm_engine/ui/elements/progress.rb @@ -5,7 +5,7 @@ module CyberarmEngine super(options, block) @fraction_background = Background.new(background: @style.fraction_background) - self.value = options[:fraction] ? options[:fraction] : 0.0 + self.value = options[:fraction] || 0.0 end def render @@ -14,9 +14,9 @@ module CyberarmEngine def recalculate _width = dimensional_size(@style.width, :width) - _height= dimensional_size(@style.height,:height) + _height = dimensional_size(@style.height, :height) @width = _width - @height= _height + @height = _height update_background end @@ -44,8 +44,8 @@ module CyberarmEngine update_background publish(:changed, @fraction) - return @fraction + @fraction end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/elements/radio.rb b/lib/cyberarm_engine/ui/elements/radio.rb index b847ca7..e38abb9 100644 --- a/lib/cyberarm_engine/ui/elements/radio.rb +++ b/lib/cyberarm_engine/ui/elements/radio.rb @@ -3,4 +3,4 @@ module CyberarmEngine class Radio < Element end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/elements/slider.rb b/lib/cyberarm_engine/ui/elements/slider.rb index 603b1d4..cd05f7e 100644 --- a/lib/cyberarm_engine/ui/elements/slider.rb +++ b/lib/cyberarm_engine/ui/elements/slider.rb @@ -9,13 +9,13 @@ module CyberarmEngine event(:drag_update) event(:end_drag) - subscribe :begin_drag do |sender, x, y, button| + subscribe :begin_drag do |_sender, x, y, _button| @drag_start_pos = Vector.new(x, y) :handled end - subscribe :drag_update do |sender, x, y, button| + subscribe :drag_update do |_sender, x, y, _button| @parent.handle_dragged_to(x, y) :handled @@ -33,21 +33,22 @@ module CyberarmEngine end end - attr_reader :range, :step_size + attr_reader :range, :step_size, :value + def initialize(options = {}, block = nil) super(options, block) - @range = @options[:range] ? @options[:range] : 0.0..1.0 - @step_size = @options[:step] ? @options[:step] : 0.1 - @value = @options[:value] ? @options[:value] : (@range.first + @range.last) / 2 + @range = @options[:range] || (0.0..1.0) + @step_size = @options[:step] || 0.1 + @value = @options[:value] || (@range.first + @range.last) / 2 @handle = Handle.new("", parent: self, width: 8, height: 1.0) { close } - self.add(@handle) + add(@handle) end def recalculate _width = dimensional_size(@style.width, :width) - _height= dimensional_size(@style.height,:height) + _height = dimensional_size(@style.height, :height) @width = _width @height = _height @@ -61,7 +62,7 @@ module CyberarmEngine def position_handle @handle.x = @x + @style.padding_left + @style.border_thickness_left + - ((content_width - @handle.outer_width) * (@value - @range.min) / (@range.max - @range.min).to_f) + ((content_width - @handle.outer_width) * (@value - @range.min) / (@range.max - @range.min).to_f) @handle.y = @y + @style.border_thickness_top + @style.padding_top end @@ -79,22 +80,18 @@ module CyberarmEngine @handle.tip = @tip end - def holding_left_mouse_button(sender, x, y) + def holding_left_mouse_button(_sender, x, y) handle_dragged_to(x, y) :handled end - def handle_dragged_to(x, y) + def handle_dragged_to(x, _y) @ratio = ((x - @handle.width / 2) - @x) / (content_width - @handle.outer_width) self.value = @ratio.clamp(0.0, 1.0) * (@range.max - @range.min) + @range.min end - def value - @value - end - def value=(n) @value = n position_handle @@ -104,4 +101,4 @@ module CyberarmEngine end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/elements/stack.rb b/lib/cyberarm_engine/ui/elements/stack.rb index ae93925..3558e3f 100644 --- a/lib/cyberarm_engine/ui/elements/stack.rb +++ b/lib/cyberarm_engine/ui/elements/stack.rb @@ -8,4 +8,4 @@ module CyberarmEngine end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/elements/toggle_button.rb b/lib/cyberarm_engine/ui/elements/toggle_button.rb index 939de54..56152d9 100644 --- a/lib/cyberarm_engine/ui/elements/toggle_button.rb +++ b/lib/cyberarm_engine/ui/elements/toggle_button.rb @@ -1,7 +1,7 @@ module CyberarmEngine class Element class ToggleButton < Button - attr_reader :toggled + attr_reader :toggled, :value def initialize(options, block = nil) if options.dig(:theme, :ToggleButton, :checkmark_image) @@ -24,12 +24,12 @@ module CyberarmEngine end end - def clicked_left_mouse_button(sender, x, y) + def clicked_left_mouse_button(_sender, _x, _y) self.value = !@value @block.call(self) if @block - return :handled + :handled end def recalculate @@ -45,10 +45,6 @@ module CyberarmEngine update_background end - def value - @value - end - def value=(boolean) @value = boolean @@ -66,4 +62,4 @@ module CyberarmEngine end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/event.rb b/lib/cyberarm_engine/ui/event.rb index 0e86ca8..29c1b1d 100644 --- a/lib/cyberarm_engine/ui/event.rb +++ b/lib/cyberarm_engine/ui/event.rb @@ -15,20 +15,18 @@ module CyberarmEngine return unless enabled? - if respond_to?(event) - return :handled if send(event, self, *args) == :handled - end + return :handled if respond_to?(event) && (send(event, self, *args) == :handled) @event_handler[event].reverse_each do |handler| return :handled if handler.call(self, *args) == :handled end parent.publish(event, *args) if parent - return nil + nil end def event(event) - @event_handler ||= Hash.new + @event_handler ||= {} @event_handler[event] ||= [] end end @@ -37,11 +35,13 @@ module CyberarmEngine attr_reader :publisher, :event, :handler def initialize(publisher, event, handler) - @publisher, @event, @handler = publisher, event, handler + @publisher = publisher + @event = event + @handler = handler end def unsubscribe @publisher.unsubscribe(self) end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/gui_state.rb b/lib/cyberarm_engine/ui/gui_state.rb index 14d357f..a8892c2 100644 --- a/lib/cyberarm_engine/ui/gui_state.rb +++ b/lib/cyberarm_engine/ui/gui_state.rb @@ -35,7 +35,7 @@ module CyberarmEngine # throws :blur event to focused element and sets GuiState focused element # Does NOT throw :focus event at element or set element as focused def focus=(element) - @focus.publish(:blur) if @focus and element && @focus != element + @focus.publish(:blur) if @focus && element && @focus != element @focus = element end @@ -88,7 +88,8 @@ module CyberarmEngine if Vector.new(window.mouse_x, window.mouse_y) == @last_mouse_pos if @mouse_over && (Gosu.milliseconds - @mouse_moved_at) > tool_tip_delay @tip.text = @mouse_over.tip if @mouse_over - @tip.x, @tip.y = window.mouse_x - @tip.width / 2, window.mouse_y - @tip.height - 4 + @tip.x = window.mouse_x - @tip.width / 2 + @tip.y = window.mouse_y - @tip.height - 4 else @tip.text = "" end @@ -146,7 +147,7 @@ module CyberarmEngine end def redirect_mouse_button(button) - hide_menu unless @menu and (@menu == @mouse_over) or (@mouse_over&.parent == @menu) + hide_menu unless @menu && (@menu == @mouse_over) || (@mouse_over&.parent == @menu) if @focus && @mouse_over != @focus @focus.publish(:blur) @@ -165,11 +166,14 @@ module CyberarmEngine end def redirect_released_mouse_button(button) - hide_menu if @menu and (@menu == @mouse_over) or (@mouse_over&.parent == @menu) + hide_menu if @menu && (@menu == @mouse_over) || (@mouse_over&.parent == @menu) if @mouse_over @mouse_over.publish(:"released_#{button}_mouse_button", window.mouse_x, window.mouse_y) - @mouse_over.publish(:"clicked_#{button}_mouse_button", window.mouse_x, window.mouse_y) if @mouse_over == @mouse_down_on[button] + if @mouse_over == @mouse_down_on[button] + @mouse_over.publish(:"clicked_#{button}_mouse_button", window.mouse_x, + window.mouse_y) + end end if @dragging_element @@ -184,13 +188,13 @@ module CyberarmEngine def redirect_holding_mouse_button(button) if !@dragging_element && @mouse_down_on[button] && @mouse_down_on[button].draggable?(button) && @mouse_pos.distance(@mouse_down_position[button]) > @min_drag_distance @dragging_element = @mouse_down_on[button] - @dragging_element.publish(:"begin_drag", window.mouse_x, window.mouse_y, button) + @dragging_element.publish(:begin_drag, window.mouse_x, window.mouse_y, button) end if @dragging_element - @dragging_element.publish(:"drag_update", window.mouse_x, window.mouse_y, button) if @dragging_element - else - @mouse_over.publish(:"holding_#{button}_mouse_button", window.mouse_x, window.mouse_y) if @mouse_over + @dragging_element.publish(:drag_update, window.mouse_x, window.mouse_y, button) if @dragging_element + elsif @mouse_over + @mouse_over.publish(:"holding_#{button}_mouse_button", window.mouse_x, window.mouse_y) end end @@ -211,4 +215,4 @@ module CyberarmEngine @menu = nil end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/style.rb b/lib/cyberarm_engine/ui/style.rb index d815450..21dc675 100644 --- a/lib/cyberarm_engine/ui/style.rb +++ b/lib/cyberarm_engine/ui/style.rb @@ -1,11 +1,11 @@ module Gosu class Color - def _dump(level) + def _dump(_level) [ - "%02X" % self.alpha, - "%02X" % self.red, - "%02X" % self.green, - "%02X" % self.blue + "%02X" % alpha, + "%02X" % red, + "%02X" % green, + "%02X" % blue ].join end @@ -21,17 +21,18 @@ module CyberarmEngine @hash = Marshal.load(Marshal.dump(hash)) end - def method_missing(method, *args, &block) + def method_missing(method, *args) if method.to_s.end_with?("=") raise "Did not expect more than 1 argument" if args.size > 1 - return @hash[method.to_s.sub("=", "").to_sym] = args.first + + @hash[method.to_s.sub("=", "").to_sym] = args.first elsif args.size == 0 - return @hash[method] + @hash[method] else raise ArgumentError, "Did not expect arguments" end end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/ui/theme.rb b/lib/cyberarm_engine/ui/theme.rb index 504b271..0854afe 100644 --- a/lib/cyberarm_engine/ui/theme.rb +++ b/lib/cyberarm_engine/ui/theme.rb @@ -11,17 +11,21 @@ module CyberarmEngine def theme_defaults(options) raise "Error" unless self.class.ancestors.include?(CyberarmEngine::Element) + _theme = THEME _theme = deep_merge(_theme, options[:theme]) if options[:theme] _theme.delete(:theme) if options[:theme] hash = {} class_names = self.class.ancestors - class_names = class_names[0..class_names.index(CyberarmEngine::Element)].map! {|c| c.to_s.split("::").last.to_sym}.reverse! + class_names = class_names[0..class_names.index(CyberarmEngine::Element)].map! do |c| + c.to_s.split("::").last.to_sym + end.reverse! class_names.each do |klass| next unless data = _theme.dig(klass) - data.each do |key, value| + + data.each do |_key, _value| hash.merge!(data) end end @@ -32,7 +36,7 @@ module CyberarmEngine # Derived from Rails Hash#deep_merge! # Enables passing partial themes through Element options without issue def deep_merge(original, intergrate, &block) - hash = original.merge(intergrate) do |key, this_val, other_val| + original.merge(intergrate) do |key, this_val, other_val| if this_val.is_a?(Hash) && other_val.is_a?(Hash) deep_merge(this_val, other_val, &block) elsif block_given? @@ -41,8 +45,6 @@ module CyberarmEngine other_val end end - - return hash end THEME = { @@ -73,8 +75,8 @@ module CyberarmEngine text_wrap: :none, hover: { - color: Gosu::Color.rgb(200,200,200), - background: ["ffB23E41".to_i(16), "ffFF7C00".to_i(16)] + color: Gosu::Color.rgb(200, 200, 200), + background: ["ffB23E41".to_i(16), "ffFF7C00".to_i(16)] }, active: { diff --git a/lib/cyberarm_engine/vector.rb b/lib/cyberarm_engine/vector.rb index f601ea1..8842b49 100644 --- a/lib/cyberarm_engine/vector.rb +++ b/lib/cyberarm_engine/vector.rb @@ -60,22 +60,15 @@ module CyberarmEngine Vector.new(0, 0, -1) end + attr_accessor :x, :y, :z, :weight + def initialize(x = 0, y = 0, z = 0, weight = 0) - @x, @y, @z, @weight = x, y, z, weight + @x = x + @y = y + @z = z + @weight = weight end - def x; @x; end - def x=(n); @x = n; end - - def y; @y; end - def y=(n); @y = n; end - - def z; @z; end - def z=(n); @z = n; end - - def weight; @weight; end - def weight=(n); @weight = n; end - alias w weight alias w= weight= @@ -83,14 +76,14 @@ module CyberarmEngine def ==(other) if other.is_a?(Numeric) @x == other && - @y == other && - @z == other && - @weight == other + @y == other && + @z == other && + @weight == other elsif other.is_a?(Vector) @x == other.x && - @y == other.y && - @z == other.z && - @weight == other.weight + @y == other.y && + @z == other.z && + @weight == other.weight else other == self end @@ -172,20 +165,20 @@ module CyberarmEngine def dot(other) product = 0 - a = self.to_a + a = to_a b = other.to_a 3.times do |i| - product = product + (a[i] * b[i]) + product += (a[i] * b[i]) end - return product + product end # cross product of {Vector} # @return [CyberarmEngine::Vector] def cross(other) - a = self.to_a + a = to_a b = other.to_a Vector.new( @@ -198,7 +191,7 @@ module CyberarmEngine # returns degrees # @return [Float] def angle(other) - Math.acos( self.normalized.dot(other.normalized) ) * 180 / Math::PI + Math.acos(normalized.dot(other.normalized)) * 180 / Math::PI end # returns magnitude of Vector, ignoring #weight @@ -220,7 +213,6 @@ module CyberarmEngine self / Vector.new(mag, mag, mag) end - # returns a direction {Vector} # # z is pitch @@ -265,19 +257,19 @@ module CyberarmEngine # 2D distance using X and Y # @return [Float] def distance(other) - Math.sqrt((@x-other.x)**2 + (@y-other.y)**2) + Math.sqrt((@x - other.x)**2 + (@y - other.y)**2) end # 2D distance using X and Z # @return [Float] def gl_distance2d(other) - Math.sqrt((@x-other.x)**2 + (@z-other.z)**2) + Math.sqrt((@x - other.x)**2 + (@z - other.z)**2) end # 3D distance using X, Y, and Z # @return [Float] def distance3d(other) - Math.sqrt((@x-other.x)**2 + (@y-other.y)**2 + (@z-other.z)**2) + Math.sqrt((@x - other.x)**2 + (@y - other.y)**2 + (@z - other.z)**2) end # Converts {Vector} to Array @@ -295,7 +287,7 @@ module CyberarmEngine # Converts {Vector} to Hash # @return [Hash] def to_h - {x: @x, y: @y, z: @z, weight: @weight} + { x: @x, y: @y, z: @z, weight: @weight } end end -end \ No newline at end of file +end diff --git a/lib/cyberarm_engine/version.rb b/lib/cyberarm_engine/version.rb index fb13475..d6dd8a4 100644 --- a/lib/cyberarm_engine/version.rb +++ b/lib/cyberarm_engine/version.rb @@ -1,4 +1,4 @@ module CyberarmEngine - NAME = "InDev" - VERSION = "0.14.0" + NAME = "InDev".freeze + VERSION = "0.14.0".freeze end diff --git a/lib/cyberarm_engine/window.rb b/lib/cyberarm_engine/window.rb index 4512317..510bfb5 100644 --- a/lib/cyberarm_engine/window.rb +++ b/lib/cyberarm_engine/window.rb @@ -1,8 +1,8 @@ module CyberarmEngine class Window < Gosu::Window IMAGES = {} - SAMPLES= {} - SONGS = {} + SAMPLES = {} + SONGS = {} attr_accessor :show_cursor attr_writer :exit_on_opengl_error @@ -13,15 +13,15 @@ module CyberarmEngine end def self.dt - $window.last_frame_time/1000.0 + $window.last_frame_time / 1000.0 end - def initialize(width: 800, height: 600, fullscreen: false, update_interval: 1000.0/60, resizable: false, borderless: false) + def initialize(width: 800, height: 600, fullscreen: false, update_interval: 1000.0 / 60, resizable: false, borderless: false) @show_cursor = false super(width, height, fullscreen: fullscreen, update_interval: update_interval, resizable: resizable, borderless: borderless) $window = self - @last_frame_time = Gosu.milliseconds-1 + @last_frame_time = Gosu.milliseconds - 1 @current_frame_time = Gosu.milliseconds self.caption = "CyberarmEngine #{CyberarmEngine::VERSION} #{Gosu.language}" @@ -39,7 +39,7 @@ module CyberarmEngine Stats.clear current_state.update if current_state - @last_frame_time = Gosu.milliseconds-@current_frame_time + @last_frame_time = Gosu.milliseconds - @current_frame_time @current_frame_time = Gosu.milliseconds end @@ -48,7 +48,7 @@ module CyberarmEngine end def dt - @last_frame_time/1000.0 + @last_frame_time / 1000.0 end def aspect_ratio @@ -69,8 +69,8 @@ module CyberarmEngine current_state.button_up(id) if current_state end - def push_state(klass, options={}) - options = {setup: true}.merge(options) + def push_state(klass, options = {}) + options = { setup: true }.merge(options) if klass.instance_of?(klass.class) && defined?(klass.options) @states << klass @@ -78,12 +78,12 @@ module CyberarmEngine else @states << klass.new(options) if child_of?(klass, GameState) @states << klass.new if child_of?(klass, Element::Container) - current_state.setup if current_state.class == klass && options[:setup] + current_state.setup if current_state.instance_of?(klass) && options[:setup] end end private def child_of?(input, klass) - input.ancestors.detect {|c| c == klass} + input.ancestors.detect { |c| c == klass } end def current_state @@ -91,10 +91,8 @@ module CyberarmEngine end def previous_state - if @states.size > 1 && state = @states[@states.size-2] - return state - else - return nil + if @states.size > 1 && state = @states[@states.size - 2] + state end end @@ -103,10 +101,11 @@ module CyberarmEngine end # Sourced from https://gist.github.com/ippa/662583 - def draw_circle(cx,cy,r, z = 9999,color = Gosu::Color::GREEN, step = 10) + def draw_circle(cx, cy, r, z = 9999, color = Gosu::Color::GREEN, step = 10) 0.step(360, step) do |a1| a2 = a1 + step - draw_line(cx + Gosu.offset_x(a1, r), cy + Gosu.offset_y(a1, r), color, cx + Gosu.offset_x(a2, r), cy + Gosu.offset_y(a2, r), color, z) + draw_line(cx + Gosu.offset_x(a1, r), cy + Gosu.offset_y(a1, r), color, cx + Gosu.offset_x(a2, r), + cy + Gosu.offset_y(a2, r), color, z) end end end diff --git a/test/test_helper.rb b/test/test_helper.rb index e94a2eb..636d829 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,4 +1,4 @@ -$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) +$LOAD_PATH.unshift File.expand_path("../lib", __dir__) require "cyberarm_engine" require "minitest/autorun"