repo
string | commit
string | message
string | diff
string |
---|---|---|---|
galaxycats/haz_enum
|
c209ec88c2b0e940525d9f91f10eeeb9b8ea828c
|
initialize an enum with its name as string
|
diff --git a/lib/haz_enum/enum.rb b/lib/haz_enum/enum.rb
index 87d88cc..ebafc7e 100644
--- a/lib/haz_enum/enum.rb
+++ b/lib/haz_enum/enum.rb
@@ -1,43 +1,47 @@
module HazEnum
module Enum
def has_enum(enum_name, options={})
enum_name = enum_name.to_s
enum_column = options.has_key?(:column_name) ? options[:column_name].to_s : enum_name
enum_class = options.has_key?(:class_name) ? Object.const_get(options[:class_name].to_s.classify) : Object.const_get(enum_name.pluralize.camelize)
self.attr_protected("#{enum_column}") if enum_name != enum_column
self.validate "#{enum_column}_check_for_valid_enum_value"
define_method "#{enum_name}" do
begin
return enum_class.const_get(self["#{enum_column}"]) if self["#{enum_column}"]
return nil
rescue NameError => e
return nil
end
end
define_method "#{enum_name}=" do |enum_to_set|
- self["#{enum_column}"] = enum_to_set.name
+ if enum_to_set.respond_to?(:name)
+ self["#{enum_column}"] = enum_to_set.name
+ else
+ self["#{enum_column}"] = enum_class.const_get(enum_to_set).name
+ end
end
define_method "#{enum_name}_changed?" do
send("#{enum_column}_changed?")
end if enum_name != enum_column
define_method "#{enum_column}_check_for_valid_enum_value" do
return true if self["#{enum_column}"].nil?
begin
enum_class.const_get(self["#{enum_column}"])
rescue NameError => e
message = I18n.translate("activerecord.errors.models.#{self.class.name.underscore}.attributes.#{enum_name}.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name) ||
I18n.translate("activerecord.errors.models.#{self.class.name.underscore}.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name) ||
I18n.translate(:'activerecord.errors.messages.enum_value_invalid', :value => self["#{enum_column}"], :name => enum_name)
self.errors.add(enum_name.to_sym, message)
end
end
end
end
end
\ No newline at end of file
diff --git a/spec/enum_spec.rb b/spec/enum_spec.rb
index 8064a61..e432e87 100644
--- a/spec/enum_spec.rb
+++ b/spec/enum_spec.rb
@@ -1,63 +1,67 @@
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "HazEnum" do
describe "Enum" do
before(:all) do
setup_db
end
it "should have class method has_enum" do
ClassWithEnum.should respond_to(:has_enum)
end
it "should be able to set enum-attribute via hash in initializer" do
ClassWithEnum.new(:product => Products::Silver).product.should be(Products::Silver)
ClassWithCustomNameEnum.new(:product => Products::Silver).product.should be(Products::Silver)
end
+ it "should be able to set enum-value as string in initializer" do
+ ClassWithEnum.new(:product => "Silver").product.should be(Products::Silver)
+ end
+
it "should not be able to set enum-attribute by colum-name via hash in initializer" do
ClassWithCustomNameEnum.new(:custom_name => Products::Silver).product.should_not be(Products::Silver)
ClassWithCustomNameEnum.new(:custom_name => Products::Silver.name).product.should_not be(Products::Silver)
end
it "should have a enum_value attribute" do
ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name)
end
it "colum_name should be configurable" do
- ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name)
+ ClassWithCustomNameEnum.new(:product => Products::Gold).product.should be(Products::Gold)
end
it "should know if enum-attribute has changed" do
product_enum = ClassWithEnum.new(:product => Products::Silver)
product_enum.product_changed?.should be(true)
product_enum.save
product_enum.product_changed?.should be(false)
product_enum.product = Products::Gold
product_enum.product_changed?.should be(true)
end
it "should know if enum-attribute has not really changed" do
product_enum = ClassWithEnum.new(:product => Products::Silver)
product_enum.save
product_enum.product = Products::Silver
product_enum.product_changed?.should be(false)
end
it "should validate enum-value" do
enum_mixin = ClassWithEnum.new
platin = "Platin"
class <<platin; def name;"Platin";end;end
enum_mixin.product = platin
enum_mixin.valid?.should_not be(true)
enum_mixin.errors[:product].size.should > 0
end
after(:all) do
teardown_db
end
end
end
\ No newline at end of file
|
galaxycats/haz_enum
|
fdefead424fb5c9813b505d7e21c8fb4919d7aa6
|
added specialized i18n translation for error
|
diff --git a/lib/haz_enum/enum.rb b/lib/haz_enum/enum.rb
index f43a345..87d88cc 100644
--- a/lib/haz_enum/enum.rb
+++ b/lib/haz_enum/enum.rb
@@ -1,38 +1,43 @@
module HazEnum
module Enum
def has_enum(enum_name, options={})
enum_name = enum_name.to_s
enum_column = options.has_key?(:column_name) ? options[:column_name].to_s : enum_name
enum_class = options.has_key?(:class_name) ? Object.const_get(options[:class_name].to_s.classify) : Object.const_get(enum_name.pluralize.camelize)
self.attr_protected("#{enum_column}") if enum_name != enum_column
self.validate "#{enum_column}_check_for_valid_enum_value"
define_method "#{enum_name}" do
begin
return enum_class.const_get(self["#{enum_column}"]) if self["#{enum_column}"]
return nil
rescue NameError => e
return nil
end
end
define_method "#{enum_name}=" do |enum_to_set|
self["#{enum_column}"] = enum_to_set.name
end
define_method "#{enum_name}_changed?" do
send("#{enum_column}_changed?")
end if enum_name != enum_column
define_method "#{enum_column}_check_for_valid_enum_value" do
return true if self["#{enum_column}"].nil?
begin
enum_class.const_get(self["#{enum_column}"])
rescue NameError => e
- self.errors.add("#{enum_name}".to_sym, I18n.t("activerecord.errors.messages.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name))
+
+ message = I18n.translate("activerecord.errors.models.#{self.class.name.underscore}.attributes.#{enum_name}.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name) ||
+ I18n.translate("activerecord.errors.models.#{self.class.name.underscore}.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name) ||
+ I18n.translate(:'activerecord.errors.messages.enum_value_invalid', :value => self["#{enum_column}"], :name => enum_name)
+
+ self.errors.add(enum_name.to_sym, message)
end
end
end
end
end
\ No newline at end of file
diff --git a/spec/enum_spec.rb b/spec/enum_spec.rb
index 14d4d6e..8064a61 100644
--- a/spec/enum_spec.rb
+++ b/spec/enum_spec.rb
@@ -1,63 +1,63 @@
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "HazEnum" do
describe "Enum" do
before(:all) do
setup_db
end
-
+
it "should have class method has_enum" do
ClassWithEnum.should respond_to(:has_enum)
end
-
+
it "should be able to set enum-attribute via hash in initializer" do
ClassWithEnum.new(:product => Products::Silver).product.should be(Products::Silver)
ClassWithCustomNameEnum.new(:product => Products::Silver).product.should be(Products::Silver)
end
-
+
it "should not be able to set enum-attribute by colum-name via hash in initializer" do
ClassWithCustomNameEnum.new(:custom_name => Products::Silver).product.should_not be(Products::Silver)
ClassWithCustomNameEnum.new(:custom_name => Products::Silver.name).product.should_not be(Products::Silver)
end
-
+
it "should have a enum_value attribute" do
ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name)
end
-
+
it "colum_name should be configurable" do
ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name)
end
-
+
it "should know if enum-attribute has changed" do
product_enum = ClassWithEnum.new(:product => Products::Silver)
product_enum.product_changed?.should be(true)
product_enum.save
product_enum.product_changed?.should be(false)
product_enum.product = Products::Gold
product_enum.product_changed?.should be(true)
end
-
+
it "should know if enum-attribute has not really changed" do
product_enum = ClassWithEnum.new(:product => Products::Silver)
product_enum.save
product_enum.product = Products::Silver
product_enum.product_changed?.should be(false)
end
-
+
it "should validate enum-value" do
enum_mixin = ClassWithEnum.new
platin = "Platin"
class <<platin; def name;"Platin";end;end
enum_mixin.product = platin
enum_mixin.valid?.should_not be(true)
enum_mixin.errors[:product].size.should > 0
end
-
+
after(:all) do
teardown_db
end
end
end
\ No newline at end of file
|
galaxycats/haz_enum
|
d2f3a7a2012d93708893da29474052f438d7869e
|
gemspec version bump to 0.2.0
|
diff --git a/haz_enum.gemspec b/haz_enum.gemspec
index df1e09d..c5a69a0 100644
--- a/haz_enum.gemspec
+++ b/haz_enum.gemspec
@@ -1,62 +1,62 @@
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{haz_enum}
- s.version = "0.1.0"
+ s.version = "0.2.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["thyphoon"]
s.date = %q{2010-06-15}
s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))}
s.email = %q{[email protected]}
s.extra_rdoc_files = [
"LICENSE",
"README.rdoc"
]
s.files = [
".document",
".gitignore",
"LICENSE",
"README.rdoc",
"Rakefile",
"VERSION",
"haz_enum.gemspec",
"lib/haz_enum.rb",
"lib/haz_enum/enum.rb",
"lib/haz_enum/set.rb",
"spec/enum_spec.rb",
"spec/set_spec.rb",
"spec/spec.opts",
"spec/spec_helper.rb"
]
s.homepage = %q{http://github.com/galaxycats/haz_enum}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.6}
s.summary = %q{has_set and has_enum for ActiveRecord}
s.test_files = [
"spec/enum_spec.rb",
"spec/set_spec.rb",
"spec/spec_helper.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<activerecord>, [">= 3.0.0.beta3"])
s.add_development_dependency(%q<rspec>, [">= 1.2.9"])
else
s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"])
s.add_dependency(%q<rspec>, [">= 1.2.9"])
end
else
s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"])
s.add_dependency(%q<rspec>, [">= 1.2.9"])
end
end
|
galaxycats/haz_enum
|
d6c66f1fec6e3108b00264bd45700355903aa6bd
|
Version bump to 0.2.0
|
diff --git a/VERSION b/VERSION
index 6e8bf73..0ea3a94 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.1.0
+0.2.0
|
galaxycats/haz_enum
|
080433b3ce28f42a87c816eda3fec7abf581e544
|
rewrite of enum with define_method
|
diff --git a/haz_enum.gemspec b/haz_enum.gemspec
index d50987c..df1e09d 100644
--- a/haz_enum.gemspec
+++ b/haz_enum.gemspec
@@ -1,62 +1,62 @@
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{haz_enum}
- s.version = "0.0.0"
+ s.version = "0.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["thyphoon"]
s.date = %q{2010-06-15}
s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))}
s.email = %q{[email protected]}
s.extra_rdoc_files = [
"LICENSE",
"README.rdoc"
]
s.files = [
".document",
".gitignore",
"LICENSE",
"README.rdoc",
"Rakefile",
"VERSION",
"haz_enum.gemspec",
"lib/haz_enum.rb",
"lib/haz_enum/enum.rb",
"lib/haz_enum/set.rb",
"spec/enum_spec.rb",
"spec/set_spec.rb",
"spec/spec.opts",
"spec/spec_helper.rb"
]
s.homepage = %q{http://github.com/galaxycats/haz_enum}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.6}
s.summary = %q{has_set and has_enum for ActiveRecord}
s.test_files = [
"spec/enum_spec.rb",
"spec/set_spec.rb",
"spec/spec_helper.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<activerecord>, [">= 3.0.0.beta3"])
s.add_development_dependency(%q<rspec>, [">= 1.2.9"])
else
s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"])
s.add_dependency(%q<rspec>, [">= 1.2.9"])
end
else
s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"])
s.add_dependency(%q<rspec>, [">= 1.2.9"])
end
end
diff --git a/lib/haz_enum/enum.rb b/lib/haz_enum/enum.rb
index 5a19d52..f43a345 100644
--- a/lib/haz_enum/enum.rb
+++ b/lib/haz_enum/enum.rb
@@ -1,40 +1,38 @@
module HazEnum
module Enum
def has_enum(enum_name, options={})
- enum_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{enum_name}_enum_value"
- # throws a NameError if Enum Class doesn't exists
- enum_class = options.has_key?(:class_name) ? Object.const_get(options[:class_name].to_s.classify) : Object.const_get(enum_name.to_s.pluralize.camelize)
- class_eval <<-RUBY, __FILE__, __LINE__ + 1
- attr_protected :#{enum_column}
- validate :#{enum_column}_check_for_valid_enum_value
- def #{enum_name}
- begin
- return #{enum_class}.const_get(self["#{enum_column}"]) if self["#{enum_column}"]
- return nil
- rescue NameError => e
- return nil
- end
- end
+ enum_name = enum_name.to_s
+ enum_column = options.has_key?(:column_name) ? options[:column_name].to_s : enum_name
+ enum_class = options.has_key?(:class_name) ? Object.const_get(options[:class_name].to_s.classify) : Object.const_get(enum_name.pluralize.camelize)
- def #{enum_name}=(enum_to_set)
- self["#{enum_column}"] = enum_to_set.name
- end
-
- def #{enum_name}_changed?
- send("#{enum_column}_changed?")
+ self.attr_protected("#{enum_column}") if enum_name != enum_column
+ self.validate "#{enum_column}_check_for_valid_enum_value"
+
+ define_method "#{enum_name}" do
+ begin
+ return enum_class.const_get(self["#{enum_column}"]) if self["#{enum_column}"]
+ return nil
+ rescue NameError => e
+ return nil
end
-
- def #{enum_column}_check_for_valid_enum_value
- return true if self["#{enum_column}"].nil?
- begin
- #{enum_class}.const_get(self["#{enum_column}"])
- rescue NameError => e
- self.errors.add("#{enum_name}".to_sym, I18n.t("activerecord.errors.messages.enum_value_invalid", :value => self["#{enum_column}"], :name => "#{enum_name}"))
- end
+ end
+
+ define_method "#{enum_name}=" do |enum_to_set|
+ self["#{enum_column}"] = enum_to_set.name
+ end
+
+ define_method "#{enum_name}_changed?" do
+ send("#{enum_column}_changed?")
+ end if enum_name != enum_column
+
+ define_method "#{enum_column}_check_for_valid_enum_value" do
+ return true if self["#{enum_column}"].nil?
+ begin
+ enum_class.const_get(self["#{enum_column}"])
+ rescue NameError => e
+ self.errors.add("#{enum_name}".to_sym, I18n.t("activerecord.errors.messages.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name))
end
-
- RUBY
+ end
end
-
end
end
\ No newline at end of file
diff --git a/spec/enum_spec.rb b/spec/enum_spec.rb
index 164bc4e..14d4d6e 100644
--- a/spec/enum_spec.rb
+++ b/spec/enum_spec.rb
@@ -1,61 +1,63 @@
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "HazEnum" do
describe "Enum" do
before(:all) do
setup_db
end
it "should have class method has_enum" do
ClassWithEnum.should respond_to(:has_enum)
end
it "should be able to set enum-attribute via hash in initializer" do
ClassWithEnum.new(:product => Products::Silver).product.should be(Products::Silver)
+ ClassWithCustomNameEnum.new(:product => Products::Silver).product.should be(Products::Silver)
end
it "should not be able to set enum-attribute by colum-name via hash in initializer" do
- ClassWithEnum.new(:product_enum_value => Products::Silver.name).product.should_not be(Products::Silver)
+ ClassWithCustomNameEnum.new(:custom_name => Products::Silver).product.should_not be(Products::Silver)
+ ClassWithCustomNameEnum.new(:custom_name => Products::Silver.name).product.should_not be(Products::Silver)
end
it "should have a enum_value attribute" do
- ClassWithEnum.new(:product => Products::Gold).product_enum_value.should be(Products::Gold.name)
+ ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name)
end
it "colum_name should be configurable" do
ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name)
end
it "should know if enum-attribute has changed" do
product_enum = ClassWithEnum.new(:product => Products::Silver)
product_enum.product_changed?.should be(true)
product_enum.save
product_enum.product_changed?.should be(false)
product_enum.product = Products::Gold
product_enum.product_changed?.should be(true)
end
it "should know if enum-attribute has not really changed" do
product_enum = ClassWithEnum.new(:product => Products::Silver)
product_enum.save
product_enum.product = Products::Silver
product_enum.product_changed?.should be(false)
end
it "should validate enum-value" do
enum_mixin = ClassWithEnum.new
platin = "Platin"
class <<platin; def name;"Platin";end;end
enum_mixin.product = platin
enum_mixin.valid?.should_not be(true)
enum_mixin.errors[:product].size.should > 0
end
after(:all) do
teardown_db
end
end
end
\ No newline at end of file
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 3c2d809..7b352e7 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,86 +1,86 @@
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require "rubygems"
require "active_record"
require 'renum'
require 'haz_enum'
require 'spec'
require 'spec/autorun'
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Migration.verbose = false
def setup_db
ActiveRecord::Base.silence do
ActiveRecord::Schema.define(:version => 1) do
create_table :class_with_enums do |t|
t.column :title, :string
- t.column :product_enum_value, :string
+ t.column :product, :string
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
create_table :class_with_custom_name_enums do |t|
t.column :title, :string
t.column :custom_name, :string
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
create_table :class_with_sets do |t|
t.column :title, :string
t.column :roles_bitfield, :integer
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
create_table :class_with_custom_name_sets do |t|
t.column :title, :string
t.column :custom_name, :string
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
end
end
end
def teardown_db
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.drop_table(table)
end
end
enum :Fakes, [:NOT_DEFINIED]
enum :Products, [:Silver, :Gold, :Titanium]
enum :Roles, [:Admin, :Supervisor, :User]
setup_db # Init the database for class creation
class ClassWithEnum < ActiveRecord::Base
has_enum :product
end
class ClassWithCustomNameEnum < ActiveRecord::Base
has_enum :product, :column_name => :custom_name
end
class ClassWithSet < ActiveRecord::Base
has_set :roles
has_set :extended_roles, :class_name => :roles do
def to_s
extended_roles.collect(&:name).join(", ")
end
end
end
class ClassWithCustomNameSet < ActiveRecord::Base
has_set :roles, :column_name => :custom_name
end
teardown_db # And drop them right afterwards
Spec::Runner.configure do |config|
end
|
galaxycats/haz_enum
|
3eb0ae08e2ee059b14ad5dc4d163b39f25211809
|
bumped version to 0.1.0
|
diff --git a/haz_enum.gemspec b/haz_enum.gemspec
index bb5f143..d50987c 100644
--- a/haz_enum.gemspec
+++ b/haz_enum.gemspec
@@ -1,56 +1,62 @@
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{haz_enum}
s.version = "0.0.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["thyphoon"]
- s.date = %q{2010-06-10}
+ s.date = %q{2010-06-15}
s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))}
s.email = %q{[email protected]}
s.extra_rdoc_files = [
"LICENSE",
"README.rdoc"
]
s.files = [
".document",
".gitignore",
"LICENSE",
"README.rdoc",
"Rakefile",
"VERSION",
+ "haz_enum.gemspec",
"lib/haz_enum.rb",
"lib/haz_enum/enum.rb",
"lib/haz_enum/set.rb",
- "spec/haz_enum_spec.rb",
+ "spec/enum_spec.rb",
+ "spec/set_spec.rb",
"spec/spec.opts",
"spec/spec_helper.rb"
]
s.homepage = %q{http://github.com/galaxycats/haz_enum}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.6}
s.summary = %q{has_set and has_enum for ActiveRecord}
s.test_files = [
- "spec/haz_enum_spec.rb",
+ "spec/enum_spec.rb",
+ "spec/set_spec.rb",
"spec/spec_helper.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
+ s.add_runtime_dependency(%q<activerecord>, [">= 3.0.0.beta3"])
s.add_development_dependency(%q<rspec>, [">= 1.2.9"])
else
+ s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"])
s.add_dependency(%q<rspec>, [">= 1.2.9"])
end
else
+ s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"])
s.add_dependency(%q<rspec>, [">= 1.2.9"])
end
end
|
galaxycats/haz_enum
|
ecaa29c7a3cee1afe0ecf4405ba1d451259a457c
|
Version bump to 0.1.0
|
diff --git a/VERSION b/VERSION
index 77d6f4c..6e8bf73 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.0.0
+0.1.0
|
galaxycats/haz_enum
|
f5ce0183644ac6d43031f3fe080ec65e5f338944
|
has_set can handle association extensions
|
diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb
index 1c56686..30f456f 100644
--- a/lib/haz_enum/set.rb
+++ b/lib/haz_enum/set.rb
@@ -1,36 +1,59 @@
module HazEnum
module Set
def has_set(set_name, options={})
field_type = options.has_key?(:field_type) ? options[:field_type].to_s : "bitfield"
set_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{set_name}_#{field_type}"
- enum_class = options.has_key?(:class_name) ? Object.const_get(options[:class_name].to_s.classify) : Object.const_get(set_name.to_s.camelize)
+ enum_class = options.has_key?(:class_name) ? Object.const_get(options[:class_name].to_s.camelize) : Object.const_get(set_name.to_s.camelize)
- self.before_save "convert_#{set_name}_to_bitfield"
+ after_find "initialize_#{set_name}_from_bitfield"
+ before_save "convert_#{set_name}_to_bitfield"
+
+ enum_class.class_eval do
+ def bitfield_index
+ index + 1
+ end
+ end unless enum_class.method_defined?(:bitfield_index)
define_method("#{set_name}") do
instance_variable_get("@#{set_name}")
end
- define_method("#{set_name}=") do |new_elements|
- instance_variable_set("@#{set_name}", new_elements)
+ define_method("#{set_name}=") do |value|
+ class <<value
+ yield if block_given?
+ end
+ instance_variable_set("@#{set_name}", value)
end
define_method("has_#{set_name.to_s.singularize}?") do |set_value|
send(set_name).include?(set_value)
end
define_method("#{set_name}_changed?") do
send("convert_#{set_name}_to_bitfield")
send("#{set_column}_changed?")
end
define_method("convert_#{set_name}_to_bitfield") do
self[set_column] = 0
- self[set_column] = send(set_name).each do |element|
- 2**element.index & self[set_column] == 2**element.index ? next : self[set_column] += 2**element.index
+ if send(set_name)
+ send(set_name).each do |element|
+ 2**element.bitfield_index & self[set_column] == 2**element.bitfield_index ? next : self[set_column] += 2**element.bitfield_index
+ end
+ end
+ end
+
+ define_method("initialize_#{set_name}_from_bitfield") do
+ if self[set_column]
+ set_elements = enum_class.values.collect do |enum_element|
+ enum_element if ((2**enum_element.bitfield_index & self[set_column]) == 2**enum_element.bitfield_index)
+ end.compact
+ send("#{set_name}=", set_elements)
+ else
+ self[set_column] = 0
end
end
end
end
end
\ No newline at end of file
diff --git a/spec/set_spec.rb b/spec/set_spec.rb
index 2891e0f..5fe79e7 100644
--- a/spec/set_spec.rb
+++ b/spec/set_spec.rb
@@ -1,59 +1,64 @@
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "HazEnum" do
describe "Set" do
before(:all) do
setup_db
end
it "should have class method has_enum" do
ClassWithSet.should respond_to(:has_set)
end
it "should be able to set set-values via hash in initializer" do
ClassWithSet.new(:roles => [Roles::User, Roles::Admin]).roles[0].should be(Roles::User)
ClassWithSet.new(:roles => [Roles::User, Roles::Admin]).roles[1].should be(Roles::Admin)
end
it "should not be able to set set-values by colum-name via hash in initializer" do
lambda { ClassWithEnum.new(:roles_bitfield => 3) }.should raise_error
end
it "colum_name should be configurable" do
ClassWithCustomNameSet.new(:roles => [Roles::Admin]).roles.first.should be(Roles::Admin)
end
it "should know if set-attribute has changed" do
roles_set = ClassWithSet.new(:roles => [Roles::Admin])
roles_set.roles_changed?.should be(true)
roles_set.save
roles_set.roles_changed?.should be(false)
roles_set.roles = [Roles::Supervisor]
roles_set.roles_changed?.should be(true)
end
it "should know if enum-attribute has not really changed" do
roles_set = ClassWithSet.new(:roles => [Roles::Admin])
roles_set.save
roles_set.roles = [Roles::Admin]
roles_set.roles_changed?.should be(false)
end
- it "should bea able to add set-value" do
+ it "should be able to add set-value" do
roles_set = ClassWithSet.new(:roles => [Roles::Admin])
roles_set.save
roles_set.roles << Roles::Supervisor
roles_set.save
roles_set.reload
roles_set.has_role?(Roles::Admin).should == true
roles_set.has_role?(Roles::Supervisor).should == true
end
+ it "should be able to define association methods" do
+ extended = ClassWithSet.new(:extended_roles => [Roles::Admin, Roles::Supervisor, Roles::User])
+ extended.to_s.should == "Admin, Supervisor, User"
+ end
+
after(:all) do
teardown_db
end
end
end
\ No newline at end of file
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 6f3129b..3c2d809 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,81 +1,86 @@
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require "rubygems"
require "active_record"
require 'renum'
require 'haz_enum'
require 'spec'
require 'spec/autorun'
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Migration.verbose = false
def setup_db
ActiveRecord::Base.silence do
ActiveRecord::Schema.define(:version => 1) do
create_table :class_with_enums do |t|
t.column :title, :string
t.column :product_enum_value, :string
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
create_table :class_with_custom_name_enums do |t|
t.column :title, :string
t.column :custom_name, :string
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
create_table :class_with_sets do |t|
t.column :title, :string
- t.column :roles_bitfield, :string
+ t.column :roles_bitfield, :integer
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
create_table :class_with_custom_name_sets do |t|
t.column :title, :string
t.column :custom_name, :string
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
end
end
end
def teardown_db
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.drop_table(table)
end
end
enum :Fakes, [:NOT_DEFINIED]
enum :Products, [:Silver, :Gold, :Titanium]
enum :Roles, [:Admin, :Supervisor, :User]
setup_db # Init the database for class creation
class ClassWithEnum < ActiveRecord::Base
has_enum :product
end
class ClassWithCustomNameEnum < ActiveRecord::Base
has_enum :product, :column_name => :custom_name
end
class ClassWithSet < ActiveRecord::Base
has_set :roles
+ has_set :extended_roles, :class_name => :roles do
+ def to_s
+ extended_roles.collect(&:name).join(", ")
+ end
+ end
end
class ClassWithCustomNameSet < ActiveRecord::Base
has_set :roles, :column_name => :custom_name
end
teardown_db # And drop them right afterwards
Spec::Runner.configure do |config|
end
|
galaxycats/haz_enum
|
c4f7bdbd5da9cf9c74b458d336e8e8ec2aa18e09
|
implemented has_set
|
diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb
index ae1b5b4..1c56686 100644
--- a/lib/haz_enum/set.rb
+++ b/lib/haz_enum/set.rb
@@ -1,6 +1,36 @@
module HazEnum
module Set
- def has_set(enum_name, options={})
+ def has_set(set_name, options={})
+
+ field_type = options.has_key?(:field_type) ? options[:field_type].to_s : "bitfield"
+ set_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{set_name}_#{field_type}"
+ enum_class = options.has_key?(:class_name) ? Object.const_get(options[:class_name].to_s.classify) : Object.const_get(set_name.to_s.camelize)
+
+ self.before_save "convert_#{set_name}_to_bitfield"
+
+ define_method("#{set_name}") do
+ instance_variable_get("@#{set_name}")
+ end
+
+ define_method("#{set_name}=") do |new_elements|
+ instance_variable_set("@#{set_name}", new_elements)
+ end
+
+ define_method("has_#{set_name.to_s.singularize}?") do |set_value|
+ send(set_name).include?(set_value)
+ end
+
+ define_method("#{set_name}_changed?") do
+ send("convert_#{set_name}_to_bitfield")
+ send("#{set_column}_changed?")
+ end
+
+ define_method("convert_#{set_name}_to_bitfield") do
+ self[set_column] = 0
+ self[set_column] = send(set_name).each do |element|
+ 2**element.index & self[set_column] == 2**element.index ? next : self[set_column] += 2**element.index
+ end
+ end
end
end
end
\ No newline at end of file
diff --git a/spec/enum_spec.rb b/spec/enum_spec.rb
new file mode 100644
index 0000000..164bc4e
--- /dev/null
+++ b/spec/enum_spec.rb
@@ -0,0 +1,61 @@
+require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
+
+describe "HazEnum" do
+
+ describe "Enum" do
+
+ before(:all) do
+ setup_db
+ end
+
+ it "should have class method has_enum" do
+ ClassWithEnum.should respond_to(:has_enum)
+ end
+
+ it "should be able to set enum-attribute via hash in initializer" do
+ ClassWithEnum.new(:product => Products::Silver).product.should be(Products::Silver)
+ end
+
+ it "should not be able to set enum-attribute by colum-name via hash in initializer" do
+ ClassWithEnum.new(:product_enum_value => Products::Silver.name).product.should_not be(Products::Silver)
+ end
+
+ it "should have a enum_value attribute" do
+ ClassWithEnum.new(:product => Products::Gold).product_enum_value.should be(Products::Gold.name)
+ end
+
+ it "colum_name should be configurable" do
+ ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name)
+ end
+
+ it "should know if enum-attribute has changed" do
+ product_enum = ClassWithEnum.new(:product => Products::Silver)
+ product_enum.product_changed?.should be(true)
+ product_enum.save
+ product_enum.product_changed?.should be(false)
+ product_enum.product = Products::Gold
+ product_enum.product_changed?.should be(true)
+ end
+
+ it "should know if enum-attribute has not really changed" do
+ product_enum = ClassWithEnum.new(:product => Products::Silver)
+ product_enum.save
+ product_enum.product = Products::Silver
+ product_enum.product_changed?.should be(false)
+ end
+
+ it "should validate enum-value" do
+ enum_mixin = ClassWithEnum.new
+ platin = "Platin"
+ class <<platin; def name;"Platin";end;end
+ enum_mixin.product = platin
+ enum_mixin.valid?.should_not be(true)
+ enum_mixin.errors[:product].size.should > 0
+ end
+
+ after(:all) do
+ teardown_db
+ end
+
+ end
+end
\ No newline at end of file
diff --git a/spec/haz_enum_spec.rb b/spec/haz_enum_spec.rb
deleted file mode 100644
index fd41cb3..0000000
--- a/spec/haz_enum_spec.rb
+++ /dev/null
@@ -1,56 +0,0 @@
-require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
-
-describe "HazEnum" do
- before(:all) do
- setup_db
- end
-
- it "should have class method has_enum" do
- ClassWithEnum.should respond_to(:has_enum)
- end
-
- it "should be able to set enum-attribute via hash in initializer" do
- ClassWithEnum.new(:product => Products::Silver).product.should be(Products::Silver)
- end
-
- it "should not be able to set enum-attribute by colum-name via hash in initializer" do
- ClassWithEnum.new(:product_enum_value => Products::Silver.name).product.should_not be(Products::Silver)
- end
-
- it "should have a enum_value attribute" do
- ClassWithEnum.new(:product => Products::Gold).product_enum_value.should be(Products::Gold.name)
- end
-
- it "colum_name should be configurable" do
- ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name)
- end
-
- it "should know if enum-attribute has changed" do
- product_enum = ClassWithEnum.new(:product => Products::Silver)
- product_enum.product_changed?.should be(true)
- product_enum.save
- product_enum.product_changed?.should be(false)
- product_enum.product = Products::Gold
- product_enum.product_changed?.should be(true)
- end
-
- it "should know if enum-attribute has not really changed" do
- product_enum = ClassWithEnum.new(:product => Products::Silver)
- product_enum.save
- product_enum.product = Products::Silver
- product_enum.product_changed?.should be(false)
- end
-
- it "should validate enum-value" do
- enum_mixin = ClassWithEnum.new
- platin = "Platin"
- class <<platin; def name;"Platin";end;end
- enum_mixin.product = platin
- enum_mixin.valid?.should_not be(true)
- enum_mixin.errors[:product].size.should > 0
- end
-
- after(:all) do
- teardown_db
- end
-end
\ No newline at end of file
diff --git a/spec/set_spec.rb b/spec/set_spec.rb
new file mode 100644
index 0000000..2891e0f
--- /dev/null
+++ b/spec/set_spec.rb
@@ -0,0 +1,59 @@
+require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
+
+describe "HazEnum" do
+
+ describe "Set" do
+
+ before(:all) do
+ setup_db
+ end
+
+ it "should have class method has_enum" do
+ ClassWithSet.should respond_to(:has_set)
+ end
+
+ it "should be able to set set-values via hash in initializer" do
+ ClassWithSet.new(:roles => [Roles::User, Roles::Admin]).roles[0].should be(Roles::User)
+ ClassWithSet.new(:roles => [Roles::User, Roles::Admin]).roles[1].should be(Roles::Admin)
+ end
+
+ it "should not be able to set set-values by colum-name via hash in initializer" do
+ lambda { ClassWithEnum.new(:roles_bitfield => 3) }.should raise_error
+ end
+
+ it "colum_name should be configurable" do
+ ClassWithCustomNameSet.new(:roles => [Roles::Admin]).roles.first.should be(Roles::Admin)
+ end
+
+ it "should know if set-attribute has changed" do
+ roles_set = ClassWithSet.new(:roles => [Roles::Admin])
+ roles_set.roles_changed?.should be(true)
+ roles_set.save
+ roles_set.roles_changed?.should be(false)
+ roles_set.roles = [Roles::Supervisor]
+ roles_set.roles_changed?.should be(true)
+ end
+
+ it "should know if enum-attribute has not really changed" do
+ roles_set = ClassWithSet.new(:roles => [Roles::Admin])
+ roles_set.save
+ roles_set.roles = [Roles::Admin]
+ roles_set.roles_changed?.should be(false)
+ end
+
+ it "should bea able to add set-value" do
+ roles_set = ClassWithSet.new(:roles => [Roles::Admin])
+ roles_set.save
+ roles_set.roles << Roles::Supervisor
+ roles_set.save
+ roles_set.reload
+ roles_set.has_role?(Roles::Admin).should == true
+ roles_set.has_role?(Roles::Supervisor).should == true
+ end
+
+ after(:all) do
+ teardown_db
+ end
+
+ end
+end
\ No newline at end of file
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 1e67cc7..6f3129b 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,64 +1,81 @@
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require "rubygems"
require "active_record"
require 'renum'
require 'haz_enum'
require 'spec'
require 'spec/autorun'
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Migration.verbose = false
def setup_db
ActiveRecord::Base.silence do
ActiveRecord::Schema.define(:version => 1) do
create_table :class_with_enums do |t|
t.column :title, :string
t.column :product_enum_value, :string
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
- create_table :class_without_enums do |t|
+ create_table :class_with_custom_name_enums do |t|
t.column :title, :string
+ t.column :custom_name, :string
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
- create_table :class_with_custom_name_enums do |t|
+ create_table :class_with_sets do |t|
+ t.column :title, :string
+ t.column :roles_bitfield, :string
+ t.column :created_at, :datetime
+ t.column :updated_at, :datetime
+ end
+
+ create_table :class_with_custom_name_sets do |t|
t.column :title, :string
t.column :custom_name, :string
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
+
end
end
end
def teardown_db
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.drop_table(table)
end
end
enum :Fakes, [:NOT_DEFINIED]
enum :Products, [:Silver, :Gold, :Titanium]
+enum :Roles, [:Admin, :Supervisor, :User]
+
setup_db # Init the database for class creation
class ClassWithEnum < ActiveRecord::Base
has_enum :product
end
-class ClassWithoutEnum < ActiveRecord::Base; end
-
class ClassWithCustomNameEnum < ActiveRecord::Base
has_enum :product, :column_name => :custom_name
end
+class ClassWithSet < ActiveRecord::Base
+ has_set :roles
+end
+
+class ClassWithCustomNameSet < ActiveRecord::Base
+ has_set :roles, :column_name => :custom_name
+end
+
teardown_db # And drop them right afterwards
Spec::Runner.configure do |config|
end
|
galaxycats/haz_enum
|
85ccfa56f69a1746cb72b870dfeb2105400c5958
|
added activerecord dependency
|
diff --git a/Rakefile b/Rakefile
index 0fbf07d..e4f0c47 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,45 +1,46 @@
require 'rubygems'
require 'rake'
begin
require 'jeweler'
Jeweler::Tasks.new do |gem|
gem.name = "haz_enum"
gem.summary = %Q{has_set and has_enum for ActiveRecord}
gem.description = %Q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))}
gem.email = "[email protected]"
gem.homepage = "http://github.com/galaxycats/haz_enum"
gem.authors = ["thyphoon"]
+ gem.add_dependency "activerecord", ">= 3.0.0.beta3"
gem.add_development_dependency "rspec", ">= 1.2.9"
# gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
end
Jeweler::GemcutterTasks.new
rescue LoadError
puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
end
require 'spec/rake/spectask'
Spec::Rake::SpecTask.new(:spec) do |spec|
spec.libs << 'lib' << 'spec'
spec.spec_files = FileList['spec/**/*_spec.rb']
end
Spec::Rake::SpecTask.new(:rcov) do |spec|
spec.libs << 'lib' << 'spec'
spec.pattern = 'spec/**/*_spec.rb'
spec.rcov = true
end
task :spec => :check_dependencies
task :default => :spec
require 'rake/rdoctask'
Rake::RDocTask.new do |rdoc|
version = File.exist?('VERSION') ? File.read('VERSION') : ""
rdoc.rdoc_dir = 'rdoc'
rdoc.title = "haz_enum #{version}"
rdoc.rdoc_files.include('README*')
rdoc.rdoc_files.include('lib/**/*.rb')
end
diff --git a/lib/haz_enum.rb b/lib/haz_enum.rb
index 351919b..7fbe94d 100644
--- a/lib/haz_enum.rb
+++ b/lib/haz_enum.rb
@@ -1,9 +1,8 @@
-require "active_record"
require "haz_enum/enum"
require "haz_enum/set"
module HazEnum
end
ActiveRecord::Base.extend HazEnum::Enum
ActiveRecord::Base.extend HazEnum::Set
\ No newline at end of file
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 0e7683d..1e67cc7 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,64 +1,64 @@
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
+require "rubygems"
+require "active_record"
+require 'renum'
require 'haz_enum'
require 'spec'
require 'spec/autorun'
-require 'rubygems'
-require 'active_record'
-require 'renum'
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Migration.verbose = false
def setup_db
ActiveRecord::Base.silence do
ActiveRecord::Schema.define(:version => 1) do
create_table :class_with_enums do |t|
t.column :title, :string
t.column :product_enum_value, :string
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
create_table :class_without_enums do |t|
t.column :title, :string
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
create_table :class_with_custom_name_enums do |t|
t.column :title, :string
t.column :custom_name, :string
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
end
end
end
def teardown_db
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.drop_table(table)
end
end
enum :Fakes, [:NOT_DEFINIED]
enum :Products, [:Silver, :Gold, :Titanium]
setup_db # Init the database for class creation
class ClassWithEnum < ActiveRecord::Base
has_enum :product
end
class ClassWithoutEnum < ActiveRecord::Base; end
class ClassWithCustomNameEnum < ActiveRecord::Base
has_enum :product, :column_name => :custom_name
end
teardown_db # And drop them right afterwards
Spec::Runner.configure do |config|
end
|
galaxycats/haz_enum
|
4ff5c09b8ab06be9368026dd52c3de8e536ed86b
|
added some tests for has_enum
|
diff --git a/lib/haz_enum/enum.rb b/lib/haz_enum/enum.rb
index c0ae62f..5a19d52 100644
--- a/lib/haz_enum/enum.rb
+++ b/lib/haz_enum/enum.rb
@@ -1,40 +1,40 @@
module HazEnum
module Enum
def has_enum(enum_name, options={})
enum_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{enum_name}_enum_value"
# throws a NameError if Enum Class doesn't exists
enum_class = options.has_key?(:class_name) ? Object.const_get(options[:class_name].to_s.classify) : Object.const_get(enum_name.to_s.pluralize.camelize)
class_eval <<-RUBY, __FILE__, __LINE__ + 1
attr_protected :#{enum_column}
validate :#{enum_column}_check_for_valid_enum_value
def #{enum_name}
begin
- return #{enum_class}.const_get(self[\"#{enum_column}\"]) if self[\"#{enum_column}\"]
+ return #{enum_class}.const_get(self["#{enum_column}"]) if self["#{enum_column}"]
return nil
rescue NameError => e
return nil
end
end
def #{enum_name}=(enum_to_set)
- self[\"#{enum_column}\"] = enum_to_set.name
+ self["#{enum_column}"] = enum_to_set.name
end
def #{enum_name}_changed?
- send(\"#{enum_column}_changed?\")
+ send("#{enum_column}_changed?")
end
def #{enum_column}_check_for_valid_enum_value
- return true if self[\"#{enum_column}\"].nil?
+ return true if self["#{enum_column}"].nil?
begin
- enum_class.const_get(self[\"#{enum_column}\"])
+ #{enum_class}.const_get(self["#{enum_column}"])
rescue NameError => e
- self.errors.add(enum_column.to_sym, I18n.t("activerecord.errors.messages.enum_value_invalid", :value => self["#{enum_column}"], :name => "#{enum_name}"))
+ self.errors.add("#{enum_name}".to_sym, I18n.t("activerecord.errors.messages.enum_value_invalid", :value => self["#{enum_column}"], :name => "#{enum_name}"))
end
end
RUBY
end
end
end
\ No newline at end of file
diff --git a/spec/haz_enum_spec.rb b/spec/haz_enum_spec.rb
index 2f18bf4..fd41cb3 100644
--- a/spec/haz_enum_spec.rb
+++ b/spec/haz_enum_spec.rb
@@ -1,23 +1,56 @@
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "HazEnum" do
before(:all) do
setup_db
end
it "should have class method has_enum" do
ClassWithEnum.should respond_to(:has_enum)
end
it "should be able to set enum-attribute via hash in initializer" do
ClassWithEnum.new(:product => Products::Silver).product.should be(Products::Silver)
end
it "should not be able to set enum-attribute by colum-name via hash in initializer" do
ClassWithEnum.new(:product_enum_value => Products::Silver.name).product.should_not be(Products::Silver)
end
+ it "should have a enum_value attribute" do
+ ClassWithEnum.new(:product => Products::Gold).product_enum_value.should be(Products::Gold.name)
+ end
+
+ it "colum_name should be configurable" do
+ ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name)
+ end
+
+ it "should know if enum-attribute has changed" do
+ product_enum = ClassWithEnum.new(:product => Products::Silver)
+ product_enum.product_changed?.should be(true)
+ product_enum.save
+ product_enum.product_changed?.should be(false)
+ product_enum.product = Products::Gold
+ product_enum.product_changed?.should be(true)
+ end
+
+ it "should know if enum-attribute has not really changed" do
+ product_enum = ClassWithEnum.new(:product => Products::Silver)
+ product_enum.save
+ product_enum.product = Products::Silver
+ product_enum.product_changed?.should be(false)
+ end
+
+ it "should validate enum-value" do
+ enum_mixin = ClassWithEnum.new
+ platin = "Platin"
+ class <<platin; def name;"Platin";end;end
+ enum_mixin.product = platin
+ enum_mixin.valid?.should_not be(true)
+ enum_mixin.errors[:product].size.should > 0
+ end
+
after(:all) do
teardown_db
end
end
\ No newline at end of file
|
galaxycats/haz_enum
|
a94f7a007f76d97ebc89909934abf4e73d05d2ad
|
first basic tests
|
diff --git a/.gitignore b/.gitignore
index c1e0daf..dcb41bd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,21 +1,22 @@
## MAC OS
.DS_Store
## TEXTMATE
*.tmproj
tmtags
## EMACS
*~
\#*
.\#*
## VIM
*.swp
## PROJECT::GENERAL
coverage
rdoc
pkg
## PROJECT::SPECIFIC
+.rake_tasks
\ No newline at end of file
diff --git a/haz_enum.gemspec b/haz_enum.gemspec
new file mode 100644
index 0000000..bb5f143
--- /dev/null
+++ b/haz_enum.gemspec
@@ -0,0 +1,56 @@
+# Generated by jeweler
+# DO NOT EDIT THIS FILE DIRECTLY
+# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
+# -*- encoding: utf-8 -*-
+
+Gem::Specification.new do |s|
+ s.name = %q{haz_enum}
+ s.version = "0.0.0"
+
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
+ s.authors = ["thyphoon"]
+ s.date = %q{2010-06-10}
+ s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))}
+ s.email = %q{[email protected]}
+ s.extra_rdoc_files = [
+ "LICENSE",
+ "README.rdoc"
+ ]
+ s.files = [
+ ".document",
+ ".gitignore",
+ "LICENSE",
+ "README.rdoc",
+ "Rakefile",
+ "VERSION",
+ "lib/haz_enum.rb",
+ "lib/haz_enum/enum.rb",
+ "lib/haz_enum/set.rb",
+ "spec/haz_enum_spec.rb",
+ "spec/spec.opts",
+ "spec/spec_helper.rb"
+ ]
+ s.homepage = %q{http://github.com/galaxycats/haz_enum}
+ s.rdoc_options = ["--charset=UTF-8"]
+ s.require_paths = ["lib"]
+ s.rubygems_version = %q{1.3.6}
+ s.summary = %q{has_set and has_enum for ActiveRecord}
+ s.test_files = [
+ "spec/haz_enum_spec.rb",
+ "spec/spec_helper.rb"
+ ]
+
+ if s.respond_to? :specification_version then
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
+ s.specification_version = 3
+
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
+ s.add_development_dependency(%q<rspec>, [">= 1.2.9"])
+ else
+ s.add_dependency(%q<rspec>, [">= 1.2.9"])
+ end
+ else
+ s.add_dependency(%q<rspec>, [">= 1.2.9"])
+ end
+end
+
diff --git a/lib/haz_enum.rb b/lib/haz_enum.rb
index 1b7a075..351919b 100644
--- a/lib/haz_enum.rb
+++ b/lib/haz_enum.rb
@@ -1,3 +1,9 @@
+require "active_record"
+require "haz_enum/enum"
+require "haz_enum/set"
+
module HazEnum
-
-end
\ No newline at end of file
+end
+
+ActiveRecord::Base.extend HazEnum::Enum
+ActiveRecord::Base.extend HazEnum::Set
\ No newline at end of file
diff --git a/lib/haz_enum/enum.rb b/lib/haz_enum/enum.rb
index 2a9ec10..c0ae62f 100644
--- a/lib/haz_enum/enum.rb
+++ b/lib/haz_enum/enum.rb
@@ -1,41 +1,40 @@
module HazEnum
module Enum
def has_enum(enum_name, options={})
- enum_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{enum_name}_enum"
+ enum_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{enum_name}_enum_value"
# throws a NameError if Enum Class doesn't exists
- enum_class = options.has_key?(:class_name) ? Object.const_get(options[:class_name].to_s.classify) : Object.const_get(enum_name.to_s.classify)
- add_validation(enum_name, enum_column)
-
-
- class_eval <<-RUBY
- validate #{enum_column}_check_for_valid_enum_value
+ enum_class = options.has_key?(:class_name) ? Object.const_get(options[:class_name].to_s.classify) : Object.const_get(enum_name.to_s.pluralize.camelize)
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ attr_protected :#{enum_column}
+ validate :#{enum_column}_check_for_valid_enum_value
def #{enum_name}
begin
- return self[enum_column] ? enum_class.const_get(self[enum_column]) : nil
+ return #{enum_class}.const_get(self[\"#{enum_column}\"]) if self[\"#{enum_column}\"]
+ return nil
rescue NameError => e
return nil
end
end
def #{enum_name}=(enum_to_set)
- self[enum_column] = enum_to_set.name
+ self[\"#{enum_column}\"] = enum_to_set.name
end
def #{enum_name}_changed?
send(\"#{enum_column}_changed?\")
end
def #{enum_column}_check_for_valid_enum_value
- return true if self[enum_column].nil?
+ return true if self[\"#{enum_column}\"].nil?
begin
- enum_class.const_get(self[enum_column])
+ enum_class.const_get(self[\"#{enum_column}\"])
rescue NameError => e
self.errors.add(enum_column.to_sym, I18n.t("activerecord.errors.messages.enum_value_invalid", :value => self["#{enum_column}"], :name => "#{enum_name}"))
end
end
RUBY
end
end
end
\ No newline at end of file
diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb
index 2109927..ae1b5b4 100644
--- a/lib/haz_enum/set.rb
+++ b/lib/haz_enum/set.rb
@@ -1,6 +1,6 @@
module HazEnum
- module Enum
+ module Set
def has_set(enum_name, options={})
end
end
end
\ No newline at end of file
diff --git a/spec/haz_enum_spec.rb b/spec/haz_enum_spec.rb
index 39baffe..2f18bf4 100644
--- a/spec/haz_enum_spec.rb
+++ b/spec/haz_enum_spec.rb
@@ -1,7 +1,23 @@
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "HazEnum" do
- it "fails" do
- fail "hey buddy, you should probably rename this file and start specing for real"
+ before(:all) do
+ setup_db
end
-end
+
+ it "should have class method has_enum" do
+ ClassWithEnum.should respond_to(:has_enum)
+ end
+
+ it "should be able to set enum-attribute via hash in initializer" do
+ ClassWithEnum.new(:product => Products::Silver).product.should be(Products::Silver)
+ end
+
+ it "should not be able to set enum-attribute by colum-name via hash in initializer" do
+ ClassWithEnum.new(:product_enum_value => Products::Silver.name).product.should_not be(Products::Silver)
+ end
+
+ after(:all) do
+ teardown_db
+ end
+end
\ No newline at end of file
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 2d13d32..0e7683d 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,9 +1,64 @@
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'haz_enum'
require 'spec'
require 'spec/autorun'
+require 'rubygems'
+require 'active_record'
+require 'renum'
+
+ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
+ActiveRecord::Migration.verbose = false
+
+def setup_db
+ ActiveRecord::Base.silence do
+ ActiveRecord::Schema.define(:version => 1) do
+ create_table :class_with_enums do |t|
+ t.column :title, :string
+ t.column :product_enum_value, :string
+ t.column :created_at, :datetime
+ t.column :updated_at, :datetime
+ end
+
+ create_table :class_without_enums do |t|
+ t.column :title, :string
+ t.column :created_at, :datetime
+ t.column :updated_at, :datetime
+ end
+
+ create_table :class_with_custom_name_enums do |t|
+ t.column :title, :string
+ t.column :custom_name, :string
+ t.column :created_at, :datetime
+ t.column :updated_at, :datetime
+ end
+ end
+ end
+end
+
+def teardown_db
+ ActiveRecord::Base.connection.tables.each do |table|
+ ActiveRecord::Base.connection.drop_table(table)
+ end
+end
+
+enum :Fakes, [:NOT_DEFINIED]
+enum :Products, [:Silver, :Gold, :Titanium]
+
+setup_db # Init the database for class creation
+
+class ClassWithEnum < ActiveRecord::Base
+ has_enum :product
+end
+
+class ClassWithoutEnum < ActiveRecord::Base; end
+
+class ClassWithCustomNameEnum < ActiveRecord::Base
+ has_enum :product, :column_name => :custom_name
+end
+
+teardown_db # And drop them right afterwards
Spec::Runner.configure do |config|
end
|
galaxycats/haz_enum
|
79ca91f22899222df62875caf95e57befcac8b45
|
Version bump to 0.0.0
|
diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000..77d6f4c
--- /dev/null
+++ b/VERSION
@@ -0,0 +1 @@
+0.0.0
|
galaxycats/haz_enum
|
f5dabf7c2cd532d8422303848ff72a5bd837b89c
|
implemented has_enum
|
diff --git a/LICENSE b/LICENSE
index 5916d26..ca31f48 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,20 +1,20 @@
-Copyright (c) 2009 thyphoon
+Copyright (c) 2009 Galaxy Cats IT Consulting GmbH
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.rdoc b/README.rdoc
index c8ab54b..82a2384 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -1,17 +1,17 @@
= haz_enum
Description goes here.
== Note on Patches/Pull Requests
* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a
future version unintentionally.
* Commit, do not mess with rakefile, version, or history.
(if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
* Send me a pull request. Bonus points for topic branches.
== Copyright
-Copyright (c) 2010 thyphoon. See LICENSE for details.
+Copyright (c) 2010 Galaxy Cats IT Consulting GmbH. See LICENSE for details.
diff --git a/lib/haz_enum.rb b/lib/haz_enum.rb
index e69de29..1b7a075 100644
--- a/lib/haz_enum.rb
+++ b/lib/haz_enum.rb
@@ -0,0 +1,3 @@
+module HazEnum
+
+end
\ No newline at end of file
diff --git a/lib/haz_enum/enum.rb b/lib/haz_enum/enum.rb
new file mode 100644
index 0000000..2a9ec10
--- /dev/null
+++ b/lib/haz_enum/enum.rb
@@ -0,0 +1,41 @@
+module HazEnum
+ module Enum
+ def has_enum(enum_name, options={})
+ enum_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{enum_name}_enum"
+ # throws a NameError if Enum Class doesn't exists
+ enum_class = options.has_key?(:class_name) ? Object.const_get(options[:class_name].to_s.classify) : Object.const_get(enum_name.to_s.classify)
+ add_validation(enum_name, enum_column)
+
+
+ class_eval <<-RUBY
+ validate #{enum_column}_check_for_valid_enum_value
+ def #{enum_name}
+ begin
+ return self[enum_column] ? enum_class.const_get(self[enum_column]) : nil
+ rescue NameError => e
+ return nil
+ end
+ end
+
+ def #{enum_name}=(enum_to_set)
+ self[enum_column] = enum_to_set.name
+ end
+
+ def #{enum_name}_changed?
+ send(\"#{enum_column}_changed?\")
+ end
+
+ def #{enum_column}_check_for_valid_enum_value
+ return true if self[enum_column].nil?
+ begin
+ enum_class.const_get(self[enum_column])
+ rescue NameError => e
+ self.errors.add(enum_column.to_sym, I18n.t("activerecord.errors.messages.enum_value_invalid", :value => self["#{enum_column}"], :name => "#{enum_name}"))
+ end
+ end
+
+ RUBY
+ end
+
+ end
+end
\ No newline at end of file
diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb
new file mode 100644
index 0000000..2109927
--- /dev/null
+++ b/lib/haz_enum/set.rb
@@ -0,0 +1,6 @@
+module HazEnum
+ module Enum
+ def has_set(enum_name, options={})
+ end
+ end
+end
\ No newline at end of file
|
jcblitz/maven-selenium-demo
|
a3a59f08de43f1dd43a1bee4a0555466f2732bd3
|
Added more robust Selenium test case
|
diff --git a/pom.xml b/pom.xml
index c55a982..922bd00 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,110 +1,112 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.blitzstein.demo</groupId>
<artifactId>testing-demo</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>testing-demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.openqa.selenium.client-drivers</groupId>
<artifactId>selenium-java-client-driver</artifactId>
<version>1.0-beta-2</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>openqa-releases</id>
<name>Openqa Release Repository</name>
<url>http://nexus.openqa.org/content/repositories/releases</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
<repository>
<id>openqa-snapshots</id>
<name>Openqa Snapshot Repository</name>
<url>http://nexus.openqa.org/content/repositories/snapshots</url>
<layout>default</layout>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<build>
<finalName>testing-demo</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<additionalClasspathElements>
<additionalClasspathElement>
src/main/webapp/WEB-INF/
</additionalClasspathElement>
</additionalClasspathElements>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>selenium-maven-plugin</artifactId>
<executions>
<execution>
<phase>pre-integration-test</phase>
<goals>
<goal>start-server</goal>
</goals>
<configuration>
<background>true</background>
+ <logOutput>true</logOutput>
+ <multiWindow>true</multiWindow>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
diff --git a/src/main/java/net/blitzstein/demo/testing/service/ProductService.java b/src/main/java/net/blitzstein/demo/testing/service/ProductService.java
new file mode 100644
index 0000000..da40e68
--- /dev/null
+++ b/src/main/java/net/blitzstein/demo/testing/service/ProductService.java
@@ -0,0 +1,21 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package net.blitzstein.demo.testing.service;
+
+import java.util.List;
+import net.blitzstein.demo.testing.domain.Product;
+
+/**
+ *
+ * @author jared
+ */
+public interface ProductService {
+ public Product getProduct(Integer id);
+ public List<Product> getProducts();
+ public void save(Product product);
+ public void delete(Integer id);
+
+}
diff --git a/src/main/java/net/blitzstein/demo/testing/service/ProductServiceImpl.java b/src/main/java/net/blitzstein/demo/testing/service/ProductServiceImpl.java
new file mode 100644
index 0000000..d282078
--- /dev/null
+++ b/src/main/java/net/blitzstein/demo/testing/service/ProductServiceImpl.java
@@ -0,0 +1,84 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package net.blitzstein.demo.testing.service;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import net.blitzstein.demo.testing.domain.Product;
+import net.blitzstein.demo.testing.domain.ProductComparable;
+import org.springframework.beans.BeansException;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.stereotype.Service;
+
+/**
+ *
+ * @author jared
+ */
+@Service
+public class ProductServiceImpl implements ProductService, ApplicationContextAware {
+
+ private ApplicationContext context;
+ private List<Product> products;
+
+ public Product getProduct(Integer id) {
+ for (Product product : products) {
+
+ if (product.getId().equals(id)) {
+ return product;
+ }
+
+ }
+
+ return null;
+ }
+
+ private int getNextProductId() {
+ Product product = this.getProducts().get(this.getProducts().size() - 1);
+ return product.getId() + 1;
+ }
+
+ public List<Product> getProducts() {
+ if (this.products == null || this.products.isEmpty()) {
+ Map productMap = context.getBeansOfType(net.blitzstein.demo.testing.domain.Product.class);
+ this.products = new ArrayList(productMap.values());
+ }
+
+ Collections.sort(products, new ProductComparable());
+ return this.products;
+ }
+
+ public void save(Product product) {
+ if (product.getId() == null) {
+ product.setId(getNextProductId());
+ this.products.add(product);
+ } else {
+ swapProduct(product);
+ }
+
+
+ }
+
+ public void delete(Integer id) {
+ Product product = getProduct(id);
+ this.products.remove(product);
+ }
+
+ public void setApplicationContext(ApplicationContext context) throws BeansException {
+ this.context = context;
+ }
+
+ private void swapProduct(Product product) {
+ for (int i = 0; i < products.size(); i++) {
+ Product currentProduct = products.get(i);
+ if (currentProduct.getId().intValue() == product.getId().intValue()) {
+ this.products.set(i, product);
+ return;
+ }
+ }
+ }
+}
diff --git a/src/main/java/net/blitzstein/demo/testing/web/ProductController.java b/src/main/java/net/blitzstein/demo/testing/web/ProductController.java
index dd98b2b..8f84d39 100644
--- a/src/main/java/net/blitzstein/demo/testing/web/ProductController.java
+++ b/src/main/java/net/blitzstein/demo/testing/web/ProductController.java
@@ -1,125 +1,70 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
-
package net.blitzstein.demo.testing.web;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
import net.blitzstein.demo.testing.domain.Product;
-import net.blitzstein.demo.testing.domain.ProductComparable;
-import org.springframework.beans.BeansException;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
+import net.blitzstein.demo.testing.service.ProductService;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
/**
*
* @author jared
*/
@Controller
-public class ProductController implements ApplicationContextAware {
- private List<Product> products = new ArrayList();
- private ApplicationContext context;
+public class ProductController {
+
+ @Autowired
+ private ProductService productService;
@RequestMapping(value = "/product/index.htm", method = RequestMethod.GET)
public void index(Model model) {
- model.addAttribute("products", getProducts());
- }
-
- public void setProducts(List<Product> products) {
- this.products = products;
+ model.addAttribute("products", productService.getProducts());
}
@RequestMapping(value = "/product/view.htm", method = RequestMethod.GET)
public void view(Model model, @RequestParam("id") int id) {
- Product product = getProduct(id);
+ Product product = productService.getProduct(new Integer(id));
model.addAttribute(product);
}
@RequestMapping(value = "/product/edit.htm", method = RequestMethod.GET)
public void edit(Model model, @RequestParam("id") int id) {
- Product product = getProduct(id);
+ Product product = productService.getProduct(new Integer(id));
model.addAttribute(product);
}
@RequestMapping(value = "/product/create.htm", method = RequestMethod.GET)
public String create(Model model) {
model.addAttribute(new Product());
return "product/edit";
}
@RequestMapping(value = "/product/save.htm", method = RequestMethod.POST)
public String save(
@ModelAttribute("Product") Product product, Model model, WebRequest webRequest) {
- if (product.getId() == null) {
- Integer id = getNextProductId();
- product.setId(id);
- } else {
- Product old = getProduct(product.getId());
- this.products.remove(old);
- }
- this.products.add(product);
+ productService.save(product);
- registerMessage(webRequest, "Product was saved!");
- return "redirect:view.htm?id="+product.getId();
+ registerMessage(webRequest, "Product was saved!");
+ return "redirect:view.htm?id=" + product.getId();
}
-
@RequestMapping(value = "/product/delete.htm", method = RequestMethod.GET)
public String delete(@RequestParam("id") int id) {
- deleteProduct(id);
+ productService.delete(new Integer(id));
return "redirect:index.htm";
}
- private void deleteProduct(int id) {
- Product product = getProduct(id);
- this.products.remove(product);
- }
-
- private List<Product> getProducts() {
- //return products;
- if (this.products == null || this.products.isEmpty()) {
- Map productMap = context.getBeansOfType(net.blitzstein.demo.testing.domain.Product.class);
- this.products = new ArrayList(productMap.values());
- }
-
- Collections.sort(products, new ProductComparable());
- return this.products;
- }
-
- private Product getProduct(Integer id) {
- for (Product product : products) {
-
- if (product.getId().equals(id)) {
- return product;
- }
-
- }
-
- return null;
- }
-
- private int getNextProductId() {
- Product product = this.getProducts().get(this.getProducts().size()-1);
- return product.getId() + 1;
- }
-
- public void setApplicationContext(ApplicationContext context) throws BeansException {
- this.context = context;
- }
-
private void registerMessage(WebRequest webRequest, String message) {
webRequest.setAttribute("message", message, WebRequest.SCOPE_SESSION);
}
}
diff --git a/src/main/webapp/WEB-INF/testingdemo-servlet.xml b/src/main/webapp/WEB-INF/testingdemo-servlet.xml
index 37b710d..e9059ca 100644
--- a/src/main/webapp/WEB-INF/testingdemo-servlet.xml
+++ b/src/main/webapp/WEB-INF/testingdemo-servlet.xml
@@ -1,231 +1,231 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
- <context:component-scan base-package="net.blitzstein.demo.testing.web"/>
+ <context:component-scan base-package="net.blitzstein.demo.testing"/>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>display</value>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/product/*=productController
</value>
</property>
</bean>
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
<property name="order" value="2" />
</bean>
-
+
<bean id="productController" class="net.blitzstein.demo.testing.web.ProductController">
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="1" />
<property name="name" value="eu" />
<property name="manufacturer" value="ullamcorper," />
<property name="price" value="254" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="2" />
<property name="name" value="eget" />
<property name="manufacturer" value="rutrum" />
<property name="price" value="605" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="3" />
<property name="name" value="vulputate dui," />
<property name="manufacturer" value="eu" />
<property name="price" value="325" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="4" />
<property name="name" value="diam. Pellentesque habitant" />
<property name="manufacturer" value="tellus." />
<property name="price" value="559" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="5" />
<property name="name" value="eros" />
<property name="manufacturer" value="sagittis. Nullam" />
<property name="price" value="435" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="6" />
<property name="name" value="nibh vulputate" />
<property name="manufacturer" value="suscipit," />
<property name="price" value="667" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="7" />
<property name="name" value="dignissim magna a" />
<property name="manufacturer" value="nunc." />
<property name="price" value="413" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="8" />
<property name="name" value="massa. Integer" />
<property name="manufacturer" value="ultrices sit" />
<property name="price" value="728" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="9" />
<property name="name" value="convallis in," />
<property name="manufacturer" value="vel," />
<property name="price" value="530" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="10" />
<property name="name" value="magnis dis parturient" />
<property name="manufacturer" value="vitae, orci." />
<property name="price" value="954" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="11" />
<property name="name" value="quis," />
<property name="manufacturer" value="fringilla" />
<property name="price" value="167" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="12" />
<property name="name" value="non dui" />
<property name="manufacturer" value="dui, in" />
<property name="price" value="824" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="13" />
<property name="name" value="dignissim" />
<property name="manufacturer" value="luctus. Curabitur" />
<property name="price" value="409" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="14" />
<property name="name" value="amet, consectetuer adipiscing" />
<property name="manufacturer" value="mi eleifend" />
<property name="price" value="532" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="15" />
<property name="name" value="vitae," />
<property name="manufacturer" value="lobortis" />
<property name="price" value="973" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="16" />
<property name="name" value="ut, nulla. Cras" />
<property name="manufacturer" value="orci," />
<property name="price" value="530" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="17" />
<property name="name" value="Curabitur" />
<property name="manufacturer" value="urna. Nullam" />
<property name="price" value="430" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="18" />
<property name="name" value="eros. Proin ultrices." />
<property name="manufacturer" value="eget magna." />
<property name="price" value="676" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="19" />
<property name="name" value="fermentum vel," />
<property name="manufacturer" value="porttitor" />
<property name="price" value="528" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="20" />
<property name="name" value="sem. Pellentesque" />
<property name="manufacturer" value="eu eros." />
<property name="price" value="658" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="21" />
<property name="name" value="sodales" />
<property name="manufacturer" value="Quisque varius." />
<property name="price" value="87" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="22" />
<property name="name" value="torquent per conubia" />
<property name="manufacturer" value="diam" />
<property name="price" value="722" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="23" />
<property name="name" value="risus. Donec nibh" />
<property name="manufacturer" value="Proin" />
<property name="price" value="872" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="24" />
<property name="name" value="malesuada vel," />
<property name="manufacturer" value="Morbi vehicula." />
<property name="price" value="538" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="25" />
<property name="name" value="Ut semper" />
<property name="manufacturer" value="pretium" />
<property name="price" value="661" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="26" />
<property name="name" value="urna suscipit nonummy." />
<property name="manufacturer" value="Ut" />
<property name="price" value="370" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="27" />
<property name="name" value="mattis" />
<property name="manufacturer" value="eget metus." />
<property name="price" value="883" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="28" />
<property name="name" value="arcu et pede." />
<property name="manufacturer" value="mauris" />
<property name="price" value="337" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="29" />
<property name="name" value="ut, molestie in," />
<property name="manufacturer" value="erat. Sed" />
<property name="price" value="119" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="30" />
<property name="name" value="sagittis. Nullam vitae" />
<property name="manufacturer" value="eget massa." />
<property name="price" value="80" />
</bean>
</beans>
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/views/product/edit.jsp b/src/main/webapp/WEB-INF/views/product/edit.jsp
index c05e513..b2d83ea 100644
--- a/src/main/webapp/WEB-INF/views/product/edit.jsp
+++ b/src/main/webapp/WEB-INF/views/product/edit.jsp
@@ -1,38 +1,39 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>
Edit
</title>
+ <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/stylesheets/styles.css" />
</head>
<body>
<h1>Edit</h1>
<form:form commandName="product" action="${pageContext.request.contextPath}/product/save.htm">
<form:hidden path="id" />
<table>
<tr>
<td>Name:</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Manufacturer:</td>
<td><form:input path="manufacturer" /></td>
</tr>
<tr>
<td>Price:</td>
<td><form:input path="price" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save Changes" />
- <a href="${pageContext.request.contextPath}/product/view.htm?id=${product.id}">Cancel</a>
+ <a class="button" title="Cancel" href="${pageContext.request.contextPath}/product/index.htm">Cancel</a>
</td>
</tr>
</table>
</form:form>
</body>
</html>
diff --git a/src/main/webapp/WEB-INF/views/product/index.jsp b/src/main/webapp/WEB-INF/views/product/index.jsp
index f676002..8827b32 100644
--- a/src/main/webapp/WEB-INF/views/product/index.jsp
+++ b/src/main/webapp/WEB-INF/views/product/index.jsp
@@ -1,47 +1,49 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>
Index
</title>
+ <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/stylesheets/styles.css" />
</head>
<body>
- <h1>Index</h1>
+ <h1 id="title">Index</h1>
<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Manufacturer</th>
<th>Price</th>
<th>Action</th>
</tr>
<c:forEach var="product" items="${products}">
- <tr>
+ <tr id="product_row_${product.id}">
<td><c:out value="${product.id}" /></td>
<td><c:out value="${product.name}" /></td>
<td><c:out value="${product.manufacturer}" /></td>
<td><fmt:formatNumber value="${product.price}" type="currency"/></td>
<td>
- <a href="${pageContext.request.contextPath}/product/view.htm?id=${product.id}">View</a>
- <a href="${pageContext.request.contextPath}/product/edit.htm?id=${product.id}">Edit</a>
- <a href="${pageContext.request.contextPath}/product/delete.htm?id=${product.id}">Delete</a>
+ <a href="${pageContext.request.contextPath}/product/view.htm?id=${product.id}" title="View" id="view_${product.id}">View</a>
+ <a href="${pageContext.request.contextPath}/product/edit.htm?id=${product.id}" title="Edit" id="edit_${product.id}"> Edit</a>
+ <a href="${pageContext.request.contextPath}/product/delete.htm?id=${product.id}" title="Delete" id="delete_${product.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
-
- <a title="Create a new product" href="${pageContext.request.contextPath}/product/create.htm">Create</a>
- </body>
+ <div class="buttons">
+ <a class="button" title="Create a new product" href="${pageContext.request.contextPath}/product/create.htm">Create</a>
+ </div>
+ </body>
</html>
diff --git a/src/main/webapp/WEB-INF/views/product/view.jsp b/src/main/webapp/WEB-INF/views/product/view.jsp
index ad6cac3..3a4533c 100644
--- a/src/main/webapp/WEB-INF/views/product/view.jsp
+++ b/src/main/webapp/WEB-INF/views/product/view.jsp
@@ -1,38 +1,41 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>
View
</title>
+ <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/stylesheets/styles.css" />
</head>
<body>
<h1>View</h1>
- ${sessionScope.message}
- <c:remove var="message" scope="session"/>
+ <div id="message" class="success">
+ ${sessionScope.message}
+ <c:remove var="message" scope="session"/>
+ </div>
<div>
<span>id: </span> ${product.id}
</div>
<div>
<span>name: </span> ${product.name}
</div>
<div>
<span>manufactuerer: </span> ${product.manufacturer}
</div>
<div>
<span>price: </span> ${product.price}
</div>
<div>
<a href="${pageContext.request.contextPath}/product/index.htm">Index</a>
<a href="${pageContext.request.contextPath}/product/edit.htm?id=${product.id}">Edit</a>
<a href="${pageContext.request.contextPath}/product/delete.htm?id=${product.id}">Delete</a>
</div>
</body>
</html>
diff --git a/src/main/webapp/includes.jspf b/src/main/webapp/includes.jspf
new file mode 100644
index 0000000..6b912f6
--- /dev/null
+++ b/src/main/webapp/includes.jspf
@@ -0,0 +1,4 @@
+<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
+<%@ page pageEncoding="MacRoman" %>
+<link href="${pageContext.request.contextPath}/stylesheets/styles.css" />
diff --git a/src/main/webapp/stylesheets/styles.css b/src/main/webapp/stylesheets/styles.css
new file mode 100644
index 0000000..cec70c5
--- /dev/null
+++ b/src/main/webapp/stylesheets/styles.css
@@ -0,0 +1,26 @@
+body {
+ font-family: Verdana;
+}
+
+td {
+ padding-right: 5px;
+}
+
+th {
+ padding: 0 10px;
+}
+
+a.button {
+ background: #333;
+ border: 2px solid #666;
+ color: #fff;
+ text-decoration: none;
+}
+
+div.buttons {
+ padding: 10px;
+}
+
+.success {
+ background: green;
+}
\ No newline at end of file
diff --git a/src/test/java/net/blitzstein/demo/testing/integration/web/ProductIndexSeleniumTest.java b/src/test/java/net/blitzstein/demo/testing/integration/web/ProductIndexSeleniumTest.java
new file mode 100644
index 0000000..2d147b7
--- /dev/null
+++ b/src/test/java/net/blitzstein/demo/testing/integration/web/ProductIndexSeleniumTest.java
@@ -0,0 +1,48 @@
+package net.blitzstein.demo.testing.integration.web;
+
+import com.thoughtworks.selenium.*;
+import java.util.regex.Pattern;
+
+public class ProductIndexSeleniumTest extends SeleneseTestCase {
+
+ public void setUp() throws Exception {
+ setUp("http://localhost:8080/", "*chrome");
+ }
+
+ public void testNew() throws Exception {
+ selenium.open("/testing-demo/product/index.htm");
+
+ //Verify page title
+ verifyEquals("Index", selenium.getTitle());
+
+ //Verify page headings
+ verifyEquals("Index", selenium.getText("css=h1"));
+
+ //Veify page elements
+ verifyEquals("Id", selenium.getText("//th[1]"));
+ verifyEquals("Name", selenium.getText("//th[2]"));
+ verifyEquals("Manufacturer", selenium.getText("//th[3]"));
+ verifyEquals("Price", selenium.getText("//th[4]"));
+ verifyEquals("Action", selenium.getText("//th[5]"));
+
+ //Verify page buttons
+ verifyEquals("Create", selenium.getText("link=Create"));
+
+ //TODO - Add some type of function to find a valid product that should be there
+ //or have DbUnit ensure expected values are present
+ //or pass in a mock / dummy
+ validateProductValues(1);
+
+
+ }
+
+ private void validateProductValues(int productIdToVerify) {
+ verifyEquals("View", selenium.getAttribute(String.format("view_%s@title", productIdToVerify)));
+ verifyEquals("Edit", selenium.getAttribute(String.format("edit_%s@title", productIdToVerify)));
+ verifyEquals("Delete", selenium.getAttribute(String.format("delete_%s@title", productIdToVerify)));
+
+ verifyEquals("eu", selenium.getText(String.format("xpath=//tr[@id='product_row_%s']/td[%s]", productIdToVerify, 2)));
+ verifyEquals("ullamcorper,", selenium.getText(String.format("xpath=//tr[@id='product_row_%s']/td[%s]", productIdToVerify, 3)));
+ verifyEquals("$254.00", selenium.getText(String.format("xpath=//tr[@id='product_row_%s']/td[%s]", productIdToVerify, 4)));
+ }
+}
diff --git a/src/test/java/net/blitzstein/demo/testing/integration/web/ProductSeleniumTest.java b/src/test/java/net/blitzstein/demo/testing/integration/web/ProductSeleniumTest.java
deleted file mode 100644
index 75995ab..0000000
--- a/src/test/java/net/blitzstein/demo/testing/integration/web/ProductSeleniumTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
-package net.blitzstein.demo.testing.integration.web;
-
-import org.junit.Test;
-import static org.junit.Assert.*;
-import com.thoughtworks.selenium.*;
-
-import com.thoughtworks.selenium.DefaultSelenium;
-import org.junit.Before;
-
-/**
- *
- * @author jared
- */
-public class ProductSeleniumTest extends SeleneseTestCase {
-
- @Test
- public void thisIsTrue() {
- assertTrue(true);
- }
-
- @Before
- public void before() throws Exception {
- setUp("http://www.google.com/", "*chrome");
- }
-
- @Test
- public void testSomethingSimple() throws Exception {
- //DefaultSelenium selenium = createSeleniumClient("http://localhost:8080/");
- //selenium.start();
-
- //
- // This is an exmaple of testing the Apache Geroniom Welcome page for specific text
- //
-
- selenium.open("/");
- selenium.type("//input[@name='q']", "test");
- selenium.click("btnG");
- verifyTrue(selenium.isElementPresent("//a[@id='logo']/img"));
-
-
-// selenium.click("link=JVM");
-// selenium.waitForPageToLoad("30000");
-// selenium.click("link=Welcome");
-// selenium.waitForPageToLoad("30000");
-// assertEquals("Geronimo Console", selenium.getTitle());
-// assertEquals("Welcome", selenium.getText(
-// "xpath=/html/body/table[@id='rootfragment']/tbody/tr[2]/td/table/tbody/tr[2]/td[4]/table/tbody/tr[1]/td/table/tbody/tr[1]/td/div/table/tbody/tr/td[2]/table/tbody/tr/td[1]/strong"));
-//
-// // Test help link
-// selenium.click("link=help");
-// selenium.waitForPageToLoad("30000");
-// selenium.isTextPresent("This is the help for the Geronimo Administration Console Welcome.");
-
- //selenium.stop();
- }
-}
diff --git a/src/test/selenium/product/index b/src/test/selenium/product/index
new file mode 100644
index 0000000..797d97a
--- /dev/null
+++ b/src/test/selenium/product/index
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head profile="http://selenium-ide.openqa.org/profiles/test-case">
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<link rel="selenium.base" href="http://localhost:8080/" />
+<title>index</title>
+</head>
+<body>
+<table cellpadding="1" cellspacing="1" border="1">
+<thead>
+<tr><td rowspan="1" colspan="3">index</td></tr>
+</thead><tbody>
+<tr>
+ <td>open</td>
+ <td>/testing-demo/product/index.htm</td>
+ <td></td>
+</tr>
+<tr>
+ <td>verifyText</td>
+ <td>title</td>
+ <td>Index</td>
+</tr>
+<tr>
+ <td>verifyText</td>
+ <td>//th[1]</td>
+ <td>Id</td>
+</tr>
+<tr>
+ <td>verifyText</td>
+ <td>//th[2]</td>
+ <td>Name</td>
+</tr>
+<tr>
+ <td>verifyText</td>
+ <td>//th[3]</td>
+ <td>Manufacturer</td>
+</tr>
+<tr>
+ <td>verifyText</td>
+ <td>//th[4]</td>
+ <td>Price</td>
+</tr>
+<tr>
+ <td>verifyText</td>
+ <td>//th[5]</td>
+ <td>Action</td>
+</tr>
+<tr>
+ <td>verifyText</td>
+ <td>link=Create</td>
+ <td>Create</td>
+</tr>
+
+</tbody></table>
+</body>
+</html>
diff --git a/target/classes/net/blitzstein/demo/testing/service/ProductService.class b/target/classes/net/blitzstein/demo/testing/service/ProductService.class
new file mode 100644
index 0000000..2913b4c
Binary files /dev/null and b/target/classes/net/blitzstein/demo/testing/service/ProductService.class differ
diff --git a/target/classes/net/blitzstein/demo/testing/service/ProductServiceImpl.class b/target/classes/net/blitzstein/demo/testing/service/ProductServiceImpl.class
new file mode 100644
index 0000000..c21851f
Binary files /dev/null and b/target/classes/net/blitzstein/demo/testing/service/ProductServiceImpl.class differ
diff --git a/target/classes/net/blitzstein/demo/testing/web/ProductController.class b/target/classes/net/blitzstein/demo/testing/web/ProductController.class
index f7c1b88..55137f2 100644
Binary files a/target/classes/net/blitzstein/demo/testing/web/ProductController.class and b/target/classes/net/blitzstein/demo/testing/web/ProductController.class differ
diff --git a/target/maven-archiver/pom.properties b/target/maven-archiver/pom.properties
deleted file mode 100644
index ec84b71..0000000
--- a/target/maven-archiver/pom.properties
+++ /dev/null
@@ -1,5 +0,0 @@
-#Generated by Maven
-#Thu May 14 23:02:01 EDT 2009
-version=1.0-SNAPSHOT
-groupId=net.blitzstein.demo
-artifactId=testing-demo
diff --git a/target/surefire-reports/TEST-net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.xml b/target/surefire-reports/TEST-net.blitzstein.demo.testing.integration.web.ProductIndexSeleniumTest.xml
similarity index 71%
rename from target/surefire-reports/TEST-net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.xml
rename to target/surefire-reports/TEST-net.blitzstein.demo.testing.integration.web.ProductIndexSeleniumTest.xml
index 3a18b42..4725dc6 100644
--- a/target/surefire-reports/TEST-net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.xml
+++ b/target/surefire-reports/TEST-net.blitzstein.demo.testing.integration.web.ProductIndexSeleniumTest.xml
@@ -1,98 +1,67 @@
<?xml version="1.0" encoding="UTF-8" ?>
-<testsuite errors="1" skipped="0" tests="1" time="7.271" failures="0" name="net.blitzstein.demo.testing.integration.web.ProductSeleniumTest">
+<testsuite errors="0" skipped="0" tests="1" time="7.441" failures="0" name="net.blitzstein.demo.testing.integration.web.ProductIndexSeleniumTest">
<properties>
<property value="Java(TM) 2 Runtime Environment, Standard Edition" name="java.runtime.name"/>
<property value="/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Libraries" name="sun.boot.library.path"/>
<property value="1.5.0_16-133" name="java.vm.version"/>
<property value="true" name="awt.nativeDoubleBuffering"/>
<property value="false" name="gopherProxySet"/>
<property value="Apple Inc." name="java.vm.vendor"/>
<property value="http://www.apple.com/" name="java.vendor.url"/>
<property value=":" name="path.separator"/>
<property value="Java HotSpot(TM) Client VM" name="java.vm.name"/>
<property value="sun.io" name="file.encoding.pkg"/>
<property value="US" name="user.country"/>
<property value="SUN_STANDARD" name="sun.java.launcher"/>
<property value="unknown" name="sun.os.patch.level"/>
<property value="Java Virtual Machine Specification" name="java.vm.specification.name"/>
<property value="/Users/jared/Documents/programming/java/netbeans-workspace/testing-demo" name="user.dir"/>
<property value="1.5.0_16-b06-284" name="java.runtime.version"/>
<property value="apple.awt.CGraphicsEnvironment" name="java.awt.graphicsenv"/>
<property value="/Users/jared/Documents/programming/java/netbeans-workspace/testing-demo" name="basedir"/>
<property value="/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/endorsed" name="java.endorsed.dirs"/>
<property value="i386" name="os.arch"/>
- <property value="/tmp/surefirebooter16574.jar" name="surefire.real.class.path"/>
+ <property value="/tmp/surefirebooter659.jar" name="surefire.real.class.path"/>
<property value="/tmp" name="java.io.tmpdir"/>
<property value="
" name="line.separator"/>
<property value="Sun Microsystems Inc." name="java.vm.specification.vendor"/>
<property value="Mac OS X" name="os.name"/>
<property value="MacRoman" name="sun.jnu.encoding"/>
<property value=".:/Users/jared/Library/Java/Extensions:/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java" name="java.library.path"/>
<property value="/Users/jared/Documents/programming/java/netbeans-workspace/testing-demo/target/test-classes:/Users/jared/Documents/programming/java/netbeans-workspace/testing-demo/target/classes:/Users/jared/.m2/junit/junit/4.4/junit-4.4.jar:/Users/jared/.m2/org/springframework/spring-webmvc/2.5.6/spring-webmvc-2.5.6.jar:/Users/jared/.m2/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar:/Users/jared/.m2/org/springframework/spring-beans/2.5.6/spring-beans-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-core/2.5.6/spring-core-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-context/2.5.6/spring-context-2.5.6.jar:/Users/jared/.m2/aopalliance/aopalliance/1.0/aopalliance-1.0.jar:/Users/jared/.m2/org/springframework/spring-context-support/2.5.6/spring-context-support-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-web/2.5.6/spring-web-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-test/2.5.6/spring-test-2.5.6.jar:/Users/jared/.m2/org/openqa/selenium/client-drivers/selenium-java-client-driver/1.0-beta-2/selenium-java-client-driver-1.0-beta-2.jar:src/main/webapp/WEB-INF/:" name="surefire.test.class.path"/>
<property value="Java Platform API Specification" name="java.specification.name"/>
<property value="49.0" name="java.class.version"/>
<property value="HotSpot Client Compiler" name="sun.management.compiler"/>
- <property value="10.5.6" name="os.version"/>
+ <property value="10.5.7" name="os.version"/>
<property value="local|*.local|169.254/16|*.169.254/16" name="http.nonProxyHosts"/>
<property value="/Users/jared" name="user.home"/>
<property value="" name="user.timezone"/>
<property value="apple.awt.CPrinterJob" name="java.awt.printerjob"/>
<property value="1.5" name="java.specification.version"/>
<property value="MacRoman" name="file.encoding"/>
<property value="jared" name="user.name"/>
<property value="/Users/jared/Documents/programming/java/netbeans-workspace/testing-demo/target/test-classes:/Users/jared/Documents/programming/java/netbeans-workspace/testing-demo/target/classes:/Users/jared/.m2/junit/junit/4.4/junit-4.4.jar:/Users/jared/.m2/org/springframework/spring-webmvc/2.5.6/spring-webmvc-2.5.6.jar:/Users/jared/.m2/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar:/Users/jared/.m2/org/springframework/spring-beans/2.5.6/spring-beans-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-core/2.5.6/spring-core-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-context/2.5.6/spring-context-2.5.6.jar:/Users/jared/.m2/aopalliance/aopalliance/1.0/aopalliance-1.0.jar:/Users/jared/.m2/org/springframework/spring-context-support/2.5.6/spring-context-support-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-web/2.5.6/spring-web-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-test/2.5.6/spring-test-2.5.6.jar:/Users/jared/.m2/org/openqa/selenium/client-drivers/selenium-java-client-driver/1.0-beta-2/selenium-java-client-driver-1.0-beta-2.jar:src/main/webapp/WEB-INF/:" name="java.class.path"/>
<property value="1.0" name="java.vm.specification.version"/>
<property value="32" name="sun.arch.data.model"/>
<property value="/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home" name="java.home"/>
<property value="Sun Microsystems Inc." name="java.specification.vendor"/>
<property value="en" name="user.language"/>
<property value="apple.awt.CToolkit" name="awt.toolkit"/>
<property value="mixed mode, sharing" name="java.vm.info"/>
<property value="1.5.0_16" name="java.version"/>
<property value="/Users/jared/Library/Java/Extensions:/Library/Java/Extensions:/System/Library/Java/Extensions:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/ext" name="java.ext.dirs"/>
<property value="/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/classes.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/ui.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/laf.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/sunrsasign.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/jsse.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/jce.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/charsets.jar" name="sun.boot.class.path"/>
<property value="Apple Inc." name="java.vendor"/>
<property value="/Users/jared/.m2" name="localRepository"/>
<property value="/" name="file.separator"/>
<property value="http://bugreport.apple.com/" name="java.vendor.url.bug"/>
<property value="little" name="sun.cpu.endian"/>
<property value="UnicodeLittle" name="sun.io.unicode.encoding"/>
<property value="1050.1.5.0_16-284" name="mrj.version"/>
<property value="local|*.local|169.254/16|*.169.254/16" name="socksNonProxyHosts"/>
<property value="local|*.local|169.254/16|*.169.254/16" name="ftp.nonProxyHosts"/>
<property value="" name="sun.cpu.isalist"/>
</properties>
- <testcase classname="net.blitzstein.demo.testing.integration.web.ProductSeleniumTest" time="7.244" name="testSomethingSimple">
- <error type="com.thoughtworks.selenium.SeleniumException" message="ERROR: Element //input[@name='q'] not found">com.thoughtworks.selenium.SeleniumException: ERROR: Element //input[@name='q'] not found
- at com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(HttpCommandProcessor.java:97)
- at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:91)
- at com.thoughtworks.selenium.DefaultSelenium.type(DefaultSelenium.java:291)
- at net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.testSomethingSimple(ProductSeleniumTest.java:40)
- at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
- at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
- at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
- at java.lang.reflect.Method.invoke(Method.java:585)
- at junit.framework.TestCase.runTest(TestCase.java:168)
- at junit.framework.TestCase.runBare(TestCase.java:134)
- at com.thoughtworks.selenium.SeleneseTestCase.runBare(SeleneseTestCase.java:212)
- at junit.framework.TestResult$1.protect(TestResult.java:110)
- at junit.framework.TestResult.runProtected(TestResult.java:128)
- at junit.framework.TestResult.run(TestResult.java:113)
- at junit.framework.TestCase.run(TestCase.java:124)
- at junit.framework.TestSuite.runTest(TestSuite.java:232)
- at junit.framework.TestSuite.run(TestSuite.java:227)
- at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:81)
- at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:62)
- at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140)
- at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127)
- at org.apache.maven.surefire.Surefire.run(Surefire.java:177)
- at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
- at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
- at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
- at java.lang.reflect.Method.invoke(Method.java:585)
- at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345)
- at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009)
-</error>
- </testcase>
+ <testcase classname="net.blitzstein.demo.testing.integration.web.ProductIndexSeleniumTest" time="7.424" name="testNew"/>
</testsuite>
\ No newline at end of file
diff --git a/target/surefire-reports/net.blitzstein.demo.testing.integration.web.ProductIndexSeleniumTest.txt b/target/surefire-reports/net.blitzstein.demo.testing.integration.web.ProductIndexSeleniumTest.txt
new file mode 100644
index 0000000..d143dc3
--- /dev/null
+++ b/target/surefire-reports/net.blitzstein.demo.testing.integration.web.ProductIndexSeleniumTest.txt
@@ -0,0 +1,4 @@
+-------------------------------------------------------------------------------
+Test set: net.blitzstein.demo.testing.integration.web.ProductIndexSeleniumTest
+-------------------------------------------------------------------------------
+Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 7.453 sec
diff --git a/target/surefire-reports/net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.txt b/target/surefire-reports/net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.txt
deleted file mode 100644
index fce6599..0000000
--- a/target/surefire-reports/net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.txt
+++ /dev/null
@@ -1,35 +0,0 @@
--------------------------------------------------------------------------------
-Test set: net.blitzstein.demo.testing.integration.web.ProductSeleniumTest
--------------------------------------------------------------------------------
-Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 7.284 sec <<< FAILURE!
-testSomethingSimple(net.blitzstein.demo.testing.integration.web.ProductSeleniumTest) Time elapsed: 7.251 sec <<< ERROR!
-com.thoughtworks.selenium.SeleniumException: ERROR: Element //input[@name='q'] not found
- at com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(HttpCommandProcessor.java:97)
- at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:91)
- at com.thoughtworks.selenium.DefaultSelenium.type(DefaultSelenium.java:291)
- at net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.testSomethingSimple(ProductSeleniumTest.java:40)
- at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
- at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
- at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
- at java.lang.reflect.Method.invoke(Method.java:585)
- at junit.framework.TestCase.runTest(TestCase.java:168)
- at junit.framework.TestCase.runBare(TestCase.java:134)
- at com.thoughtworks.selenium.SeleneseTestCase.runBare(SeleneseTestCase.java:212)
- at junit.framework.TestResult$1.protect(TestResult.java:110)
- at junit.framework.TestResult.runProtected(TestResult.java:128)
- at junit.framework.TestResult.run(TestResult.java:113)
- at junit.framework.TestCase.run(TestCase.java:124)
- at junit.framework.TestSuite.runTest(TestSuite.java:232)
- at junit.framework.TestSuite.run(TestSuite.java:227)
- at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:81)
- at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:62)
- at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140)
- at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127)
- at org.apache.maven.surefire.Surefire.run(Surefire.java:177)
- at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
- at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
- at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
- at java.lang.reflect.Method.invoke(Method.java:585)
- at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345)
- at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009)
-
diff --git a/target/test-classes/net/blitzstein/demo/testing/integration/web/ProductIndexSeleniumTest.class b/target/test-classes/net/blitzstein/demo/testing/integration/web/ProductIndexSeleniumTest.class
new file mode 100644
index 0000000..b9d49f0
Binary files /dev/null and b/target/test-classes/net/blitzstein/demo/testing/integration/web/ProductIndexSeleniumTest.class differ
diff --git a/target/test-classes/net/blitzstein/demo/testing/integration/web/ProductSeleniumTest.class b/target/test-classes/net/blitzstein/demo/testing/integration/web/ProductSeleniumTest.class
deleted file mode 100644
index f5917b8..0000000
Binary files a/target/test-classes/net/blitzstein/demo/testing/integration/web/ProductSeleniumTest.class and /dev/null differ
diff --git a/target/testing-demo.war b/target/testing-demo.war
deleted file mode 100644
index 4bcd442..0000000
Binary files a/target/testing-demo.war and /dev/null differ
diff --git a/target/testing-demo/WEB-INF/classes/display.properties b/target/testing-demo/WEB-INF/classes/display.properties
deleted file mode 100644
index 57ed665..0000000
--- a/target/testing-demo/WEB-INF/classes/display.properties
+++ /dev/null
@@ -1,3 +0,0 @@
-# To change this template, choose Tools | Templates
-# and open the template in the editor.
-
diff --git a/target/testing-demo/WEB-INF/classes/net/blitzstein/demo/testing/domain/Product.class b/target/testing-demo/WEB-INF/classes/net/blitzstein/demo/testing/domain/Product.class
deleted file mode 100644
index fe2818b..0000000
Binary files a/target/testing-demo/WEB-INF/classes/net/blitzstein/demo/testing/domain/Product.class and /dev/null differ
diff --git a/target/testing-demo/WEB-INF/classes/net/blitzstein/demo/testing/web/ProductController.class b/target/testing-demo/WEB-INF/classes/net/blitzstein/demo/testing/web/ProductController.class
deleted file mode 100644
index 533eec0..0000000
Binary files a/target/testing-demo/WEB-INF/classes/net/blitzstein/demo/testing/web/ProductController.class and /dev/null differ
diff --git a/target/testing-demo/WEB-INF/lib/aopalliance-1.0.jar b/target/testing-demo/WEB-INF/lib/aopalliance-1.0.jar
deleted file mode 100644
index 578b1a0..0000000
Binary files a/target/testing-demo/WEB-INF/lib/aopalliance-1.0.jar and /dev/null differ
diff --git a/target/testing-demo/WEB-INF/lib/commons-logging-1.1.1.jar b/target/testing-demo/WEB-INF/lib/commons-logging-1.1.1.jar
deleted file mode 100644
index 1deef14..0000000
Binary files a/target/testing-demo/WEB-INF/lib/commons-logging-1.1.1.jar and /dev/null differ
diff --git a/target/testing-demo/WEB-INF/lib/spring-beans-2.5.6.jar b/target/testing-demo/WEB-INF/lib/spring-beans-2.5.6.jar
deleted file mode 100644
index 3f306b6..0000000
Binary files a/target/testing-demo/WEB-INF/lib/spring-beans-2.5.6.jar and /dev/null differ
diff --git a/target/testing-demo/WEB-INF/lib/spring-context-2.5.6.jar b/target/testing-demo/WEB-INF/lib/spring-context-2.5.6.jar
deleted file mode 100644
index 29fabcc..0000000
Binary files a/target/testing-demo/WEB-INF/lib/spring-context-2.5.6.jar and /dev/null differ
diff --git a/target/testing-demo/WEB-INF/lib/spring-context-support-2.5.6.jar b/target/testing-demo/WEB-INF/lib/spring-context-support-2.5.6.jar
deleted file mode 100644
index 2927c6e..0000000
Binary files a/target/testing-demo/WEB-INF/lib/spring-context-support-2.5.6.jar and /dev/null differ
diff --git a/target/testing-demo/WEB-INF/lib/spring-core-2.5.6.jar b/target/testing-demo/WEB-INF/lib/spring-core-2.5.6.jar
deleted file mode 100644
index aafa336..0000000
Binary files a/target/testing-demo/WEB-INF/lib/spring-core-2.5.6.jar and /dev/null differ
diff --git a/target/testing-demo/WEB-INF/lib/spring-test-2.5.6.jar b/target/testing-demo/WEB-INF/lib/spring-test-2.5.6.jar
deleted file mode 100644
index 2589840..0000000
Binary files a/target/testing-demo/WEB-INF/lib/spring-test-2.5.6.jar and /dev/null differ
diff --git a/target/testing-demo/WEB-INF/lib/spring-web-2.5.6.jar b/target/testing-demo/WEB-INF/lib/spring-web-2.5.6.jar
deleted file mode 100644
index 432e8f0..0000000
Binary files a/target/testing-demo/WEB-INF/lib/spring-web-2.5.6.jar and /dev/null differ
diff --git a/target/testing-demo/WEB-INF/lib/spring-webmvc-2.5.6.jar b/target/testing-demo/WEB-INF/lib/spring-webmvc-2.5.6.jar
deleted file mode 100644
index 613f595..0000000
Binary files a/target/testing-demo/WEB-INF/lib/spring-webmvc-2.5.6.jar and /dev/null differ
diff --git a/target/testing-demo/WEB-INF/testingdemo-servlet.xml b/target/testing-demo/WEB-INF/testingdemo-servlet.xml
deleted file mode 100644
index 37b710d..0000000
--- a/target/testing-demo/WEB-INF/testingdemo-servlet.xml
+++ /dev/null
@@ -1,231 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:util="http://www.springframework.org/schema/util"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
-
- <context:component-scan base-package="net.blitzstein.demo.testing.web"/>
- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
-
-
- <bean id="messageSource"
- class="org.springframework.context.support.ResourceBundleMessageSource">
- <property name="basenames">
- <list>
- <value>display</value>
- </list>
- </property>
- </bean>
-
- <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
- <property name="mappings">
- <value>
- /product/*=productController
- </value>
- </property>
- </bean>
-
- <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
- <property name="prefix" value="/WEB-INF/views/"/>
- <property name="suffix" value=".jsp"/>
- <property name="order" value="2" />
- </bean>
-
- <bean id="productController" class="net.blitzstein.demo.testing.web.ProductController">
-
- </bean>
-
-
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="1" />
- <property name="name" value="eu" />
- <property name="manufacturer" value="ullamcorper," />
- <property name="price" value="254" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="2" />
- <property name="name" value="eget" />
- <property name="manufacturer" value="rutrum" />
- <property name="price" value="605" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="3" />
- <property name="name" value="vulputate dui," />
- <property name="manufacturer" value="eu" />
- <property name="price" value="325" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="4" />
- <property name="name" value="diam. Pellentesque habitant" />
- <property name="manufacturer" value="tellus." />
- <property name="price" value="559" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="5" />
- <property name="name" value="eros" />
- <property name="manufacturer" value="sagittis. Nullam" />
- <property name="price" value="435" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="6" />
- <property name="name" value="nibh vulputate" />
- <property name="manufacturer" value="suscipit," />
- <property name="price" value="667" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="7" />
- <property name="name" value="dignissim magna a" />
- <property name="manufacturer" value="nunc." />
- <property name="price" value="413" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="8" />
- <property name="name" value="massa. Integer" />
- <property name="manufacturer" value="ultrices sit" />
- <property name="price" value="728" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="9" />
- <property name="name" value="convallis in," />
- <property name="manufacturer" value="vel," />
- <property name="price" value="530" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="10" />
- <property name="name" value="magnis dis parturient" />
- <property name="manufacturer" value="vitae, orci." />
- <property name="price" value="954" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="11" />
- <property name="name" value="quis," />
- <property name="manufacturer" value="fringilla" />
- <property name="price" value="167" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="12" />
- <property name="name" value="non dui" />
- <property name="manufacturer" value="dui, in" />
- <property name="price" value="824" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="13" />
- <property name="name" value="dignissim" />
- <property name="manufacturer" value="luctus. Curabitur" />
- <property name="price" value="409" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="14" />
- <property name="name" value="amet, consectetuer adipiscing" />
- <property name="manufacturer" value="mi eleifend" />
- <property name="price" value="532" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="15" />
- <property name="name" value="vitae," />
- <property name="manufacturer" value="lobortis" />
- <property name="price" value="973" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="16" />
- <property name="name" value="ut, nulla. Cras" />
- <property name="manufacturer" value="orci," />
- <property name="price" value="530" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="17" />
- <property name="name" value="Curabitur" />
- <property name="manufacturer" value="urna. Nullam" />
- <property name="price" value="430" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="18" />
- <property name="name" value="eros. Proin ultrices." />
- <property name="manufacturer" value="eget magna." />
- <property name="price" value="676" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="19" />
- <property name="name" value="fermentum vel," />
- <property name="manufacturer" value="porttitor" />
- <property name="price" value="528" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="20" />
- <property name="name" value="sem. Pellentesque" />
- <property name="manufacturer" value="eu eros." />
- <property name="price" value="658" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="21" />
- <property name="name" value="sodales" />
- <property name="manufacturer" value="Quisque varius." />
- <property name="price" value="87" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="22" />
- <property name="name" value="torquent per conubia" />
- <property name="manufacturer" value="diam" />
- <property name="price" value="722" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="23" />
- <property name="name" value="risus. Donec nibh" />
- <property name="manufacturer" value="Proin" />
- <property name="price" value="872" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="24" />
- <property name="name" value="malesuada vel," />
- <property name="manufacturer" value="Morbi vehicula." />
- <property name="price" value="538" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="25" />
- <property name="name" value="Ut semper" />
- <property name="manufacturer" value="pretium" />
- <property name="price" value="661" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="26" />
- <property name="name" value="urna suscipit nonummy." />
- <property name="manufacturer" value="Ut" />
- <property name="price" value="370" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="27" />
- <property name="name" value="mattis" />
- <property name="manufacturer" value="eget metus." />
- <property name="price" value="883" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="28" />
- <property name="name" value="arcu et pede." />
- <property name="manufacturer" value="mauris" />
- <property name="price" value="337" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="29" />
- <property name="name" value="ut, molestie in," />
- <property name="manufacturer" value="erat. Sed" />
- <property name="price" value="119" />
- </bean>
- <bean class="net.blitzstein.demo.testing.domain.Product">
- <property name="id" value="30" />
- <property name="name" value="sagittis. Nullam vitae" />
- <property name="manufacturer" value="eget massa." />
- <property name="price" value="80" />
- </bean>
-
-
-</beans>
\ No newline at end of file
diff --git a/target/testing-demo/WEB-INF/views/product/create.jsp b/target/testing-demo/WEB-INF/views/product/create.jsp
deleted file mode 100644
index 5c81a19..0000000
--- a/target/testing-demo/WEB-INF/views/product/create.jsp
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
- <title>
- Edit
- </title>
- </head>
- <body>
- <h1>Edit</h1>
- </body>
-</html>
diff --git a/target/testing-demo/WEB-INF/views/product/edit.jsp b/target/testing-demo/WEB-INF/views/product/edit.jsp
deleted file mode 100644
index c05e513..0000000
--- a/target/testing-demo/WEB-INF/views/product/edit.jsp
+++ /dev/null
@@ -1,38 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
-<html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
- <title>
- Edit
- </title>
- </head>
- <body>
- <h1>Edit</h1>
-
- <form:form commandName="product" action="${pageContext.request.contextPath}/product/save.htm">
- <form:hidden path="id" />
- <table>
- <tr>
- <td>Name:</td>
- <td><form:input path="name" /></td>
- </tr>
- <tr>
- <td>Manufacturer:</td>
- <td><form:input path="manufacturer" /></td>
- </tr>
- <tr>
- <td>Price:</td>
- <td><form:input path="price" /></td>
- </tr>
- <tr>
- <td colspan="2">
- <input type="submit" value="Save Changes" />
- <a href="${pageContext.request.contextPath}/product/view.htm?id=${product.id}">Cancel</a>
- </td>
- </tr>
- </table>
- </form:form>
- </body>
-</html>
diff --git a/target/testing-demo/WEB-INF/views/product/index.jsp b/target/testing-demo/WEB-INF/views/product/index.jsp
deleted file mode 100644
index f676002..0000000
--- a/target/testing-demo/WEB-INF/views/product/index.jsp
+++ /dev/null
@@ -1,47 +0,0 @@
-<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
-<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
-<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
-
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
- <title>
- Index
- </title>
- </head>
- <body>
- <h1>Index</h1>
-
- <table>
- <tr>
- <th>Id</th>
- <th>Name</th>
- <th>Manufacturer</th>
- <th>Price</th>
- <th>Action</th>
- </tr>
- <c:forEach var="product" items="${products}">
- <tr>
- <td><c:out value="${product.id}" /></td>
- <td><c:out value="${product.name}" /></td>
- <td><c:out value="${product.manufacturer}" /></td>
- <td><fmt:formatNumber value="${product.price}" type="currency"/></td>
- <td>
- <a href="${pageContext.request.contextPath}/product/view.htm?id=${product.id}">View</a>
- <a href="${pageContext.request.contextPath}/product/edit.htm?id=${product.id}">Edit</a>
- <a href="${pageContext.request.contextPath}/product/delete.htm?id=${product.id}">Delete</a>
- </td>
-
-
-
- </tr>
- </c:forEach>
- </table>
-
-
- <a title="Create a new product" href="${pageContext.request.contextPath}/product/create.htm">Create</a>
- </body>
-</html>
diff --git a/target/testing-demo/WEB-INF/views/product/view.jsp b/target/testing-demo/WEB-INF/views/product/view.jsp
deleted file mode 100644
index ad6cac3..0000000
--- a/target/testing-demo/WEB-INF/views/product/view.jsp
+++ /dev/null
@@ -1,38 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
-<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
-
-<html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
- <title>
- View
- </title>
- </head>
- <body>
- <h1>View</h1>
-
- ${sessionScope.message}
- <c:remove var="message" scope="session"/>
-
- <div>
- <span>id: </span> ${product.id}
- </div>
- <div>
- <span>name: </span> ${product.name}
- </div>
- <div>
- <span>manufactuerer: </span> ${product.manufacturer}
- </div>
- <div>
- <span>price: </span> ${product.price}
- </div>
-
- <div>
- <a href="${pageContext.request.contextPath}/product/index.htm">Index</a>
- <a href="${pageContext.request.contextPath}/product/edit.htm?id=${product.id}">Edit</a>
- <a href="${pageContext.request.contextPath}/product/delete.htm?id=${product.id}">Delete</a>
- </div>
- </body>
-</html>
diff --git a/target/testing-demo/WEB-INF/web.xml b/target/testing-demo/WEB-INF/web.xml
deleted file mode 100644
index 629d65d..0000000
--- a/target/testing-demo/WEB-INF/web.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<web-app id="MessengerWebApp" version="2.4"
- xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
- <display-name>Archetype Created Web Application</display-name>
-
-<context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/testingdemo-servlet.xml</param-value>
- </context-param>
-
- <servlet>
- <servlet-name>testingdemo</servlet-name>
- <servlet-class>
- org.springframework.web.servlet.DispatcherServlet
- </servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>testingdemo</servlet-name>
- <url-pattern>*.htm</url-pattern>
- </servlet-mapping>
-
- <listener>
- <listener-class>
- org.springframework.web.context.ContextLoaderListener
- </listener-class>
- </listener>
-</web-app>
diff --git a/target/testing-demo/index.jsp b/target/testing-demo/index.jsp
deleted file mode 100644
index 9e9d551..0000000
--- a/target/testing-demo/index.jsp
+++ /dev/null
@@ -1,2 +0,0 @@
-<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
-<c:redirect url="/product/index.htm"/>
diff --git a/target/war/work/webapp-cache.xml b/target/war/work/webapp-cache.xml
deleted file mode 100644
index d4a2a6c..0000000
--- a/target/war/work/webapp-cache.xml
+++ /dev/null
@@ -1,82 +0,0 @@
-<webapp-structure>
- <registeredFiles>
- <entry>
- <string>currentBuild</string>
- <path-set>
- <pathsSet class="linked-hash-set">
- <string>index.jsp</string>
- <string>WEB-INF/testingdemo-servlet.xml</string>
- <string>WEB-INF/views/product/create.jsp</string>
- <string>WEB-INF/views/product/edit.jsp</string>
- <string>WEB-INF/views/product/index.jsp</string>
- <string>WEB-INF/views/product/view.jsp</string>
- <string>WEB-INF/web.xml</string>
- <string>WEB-INF/classes/display.properties</string>
- <string>WEB-INF/classes/net/blitzstein/demo/testing/domain/Product.class</string>
- <string>WEB-INF/classes/net/blitzstein/demo/testing/web/ProductController.class</string>
- <string>WEB-INF/lib/spring-webmvc-2.5.6.jar</string>
- <string>WEB-INF/lib/commons-logging-1.1.1.jar</string>
- <string>WEB-INF/lib/spring-beans-2.5.6.jar</string>
- <string>WEB-INF/lib/spring-core-2.5.6.jar</string>
- <string>WEB-INF/lib/spring-context-2.5.6.jar</string>
- <string>WEB-INF/lib/aopalliance-1.0.jar</string>
- <string>WEB-INF/lib/spring-context-support-2.5.6.jar</string>
- <string>WEB-INF/lib/spring-web-2.5.6.jar</string>
- <string>WEB-INF/lib/spring-test-2.5.6.jar</string>
- </pathsSet>
- </path-set>
- </entry>
- </registeredFiles>
- <dependenciesInfo>
- <org.apache.maven.plugin.war.util.DependencyInfo>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.4</version>
- <type>jar</type>
- <scope>test</scope>
- <exclusions/>
- <optional>false</optional>
- <modelEncoding>UTF-8</modelEncoding>
- </dependency>
- </org.apache.maven.plugin.war.util.DependencyInfo>
- <org.apache.maven.plugin.war.util.DependencyInfo>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>2.5.6</version>
- <type>jar</type>
- <scope>compile</scope>
- <exclusions/>
- <optional>false</optional>
- <modelEncoding>UTF-8</modelEncoding>
- </dependency>
- <targetFileName>spring-webmvc-2.5.6.jar</targetFileName>
- </org.apache.maven.plugin.war.util.DependencyInfo>
- <org.apache.maven.plugin.war.util.DependencyInfo>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>2.5.6</version>
- <type>jar</type>
- <scope>compile</scope>
- <exclusions/>
- <optional>false</optional>
- <modelEncoding>UTF-8</modelEncoding>
- </dependency>
- <targetFileName>spring-test-2.5.6.jar</targetFileName>
- </org.apache.maven.plugin.war.util.DependencyInfo>
- <org.apache.maven.plugin.war.util.DependencyInfo>
- <dependency>
- <groupId>org.openqa.selenium.client-drivers</groupId>
- <artifactId>selenium-java-client-driver</artifactId>
- <version>1.0-beta-2</version>
- <type>jar</type>
- <scope>test</scope>
- <exclusions/>
- <optional>false</optional>
- <modelEncoding>UTF-8</modelEncoding>
- </dependency>
- </org.apache.maven.plugin.war.util.DependencyInfo>
- </dependenciesInfo>
-</webapp-structure>
\ No newline at end of file
diff --git a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/edit_jsp.class b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/edit_jsp.class
index abe9071..e39697e 100644
Binary files a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/edit_jsp.class and b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/edit_jsp.class differ
diff --git a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/edit_jsp.java b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/edit_jsp.java
index f8cbcf7..be847f5 100644
--- a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/edit_jsp.java
+++ b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/edit_jsp.java
@@ -1,267 +1,268 @@
package org.apache.jsp.WEB_002dINF.views.product;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class edit_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.Vector _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_form_form_commandName_action;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_form_hidden_path_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_form_input_path_nobody;
private org.apache.jasper.runtime.ResourceInjector _jspx_resourceInjector;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_jspx_tagPool_form_form_commandName_action = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_form_hidden_path_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_form_input_path_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
}
public void _jspDestroy() {
_jspx_tagPool_form_form_commandName_action.release();
_jspx_tagPool_form_hidden_path_nobody.release();
_jspx_tagPool_form_input_path_nobody.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n");
out.write("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
out.write("\n");
out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
out.write("\t<head>\n");
out.write("\t\t<meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />\n");
out.write("\t\t<title>\n");
out.write("\t\t\tEdit\n");
out.write("\t\t</title>\n");
+ out.write(" <link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("/stylesheets/styles.css\" />\n");
out.write("\t</head>\n");
out.write("\t<body>\n");
out.write(" <h1>Edit</h1>\n");
out.write("\n");
out.write(" ");
if (_jspx_meth_form_form_0(_jspx_page_context))
return;
out.write("\n");
out.write("\t</body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_form_form_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// form:form
org.springframework.web.servlet.tags.form.FormTag _jspx_th_form_form_0 = (org.springframework.web.servlet.tags.form.FormTag) _jspx_tagPool_form_form_commandName_action.get(org.springframework.web.servlet.tags.form.FormTag.class);
_jspx_th_form_form_0.setPageContext(_jspx_page_context);
_jspx_th_form_form_0.setParent(null);
_jspx_th_form_form_0.setCommandName("product");
_jspx_th_form_form_0.setAction((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}/product/save.htm", java.lang.String.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_form_form_0 = new int[] { 0 };
try {
int _jspx_eval_form_form_0 = _jspx_th_form_form_0.doStartTag();
if (_jspx_eval_form_form_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_form_hidden_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_form_form_0, _jspx_page_context, _jspx_push_body_count_form_form_0))
return true;
out.write("\n");
out.write(" <table>\n");
out.write(" <tr>\n");
out.write(" <td>Name:</td>\n");
out.write(" <td>");
if (_jspx_meth_form_input_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_form_form_0, _jspx_page_context, _jspx_push_body_count_form_form_0))
return true;
out.write("</td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <td>Manufacturer:</td>\n");
out.write(" <td>");
if (_jspx_meth_form_input_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_form_form_0, _jspx_page_context, _jspx_push_body_count_form_form_0))
return true;
out.write("</td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <td>Price:</td>\n");
out.write(" <td>");
if (_jspx_meth_form_input_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_form_form_0, _jspx_page_context, _jspx_push_body_count_form_form_0))
return true;
out.write("</td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <td colspan=\"2\">\n");
out.write(" <input type=\"submit\" value=\"Save Changes\" />\n");
- out.write(" <a href=\"");
+ out.write(" <a class=\"button\" title=\"Cancel\" href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
- out.write("/product/view.htm?id=");
- out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
- out.write("\">Cancel</a>\n");
+ out.write("/product/index.htm\">Cancel</a>\n");
out.write(" </td>\n");
out.write(" </tr>\n");
out.write(" </table>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_form_form_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_form_form_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_form_form_0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_form_0.doCatch(_jspx_exception);
} finally {
_jspx_th_form_form_0.doFinally();
_jspx_tagPool_form_form_commandName_action.reuse(_jspx_th_form_form_0);
}
return false;
}
private boolean _jspx_meth_form_hidden_0(javax.servlet.jsp.tagext.JspTag _jspx_th_form_form_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_form_form_0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// form:hidden
org.springframework.web.servlet.tags.form.HiddenInputTag _jspx_th_form_hidden_0 = (org.springframework.web.servlet.tags.form.HiddenInputTag) _jspx_tagPool_form_hidden_path_nobody.get(org.springframework.web.servlet.tags.form.HiddenInputTag.class);
_jspx_th_form_hidden_0.setPageContext(_jspx_page_context);
_jspx_th_form_hidden_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_form_0);
_jspx_th_form_hidden_0.setPath("id");
int[] _jspx_push_body_count_form_hidden_0 = new int[] { 0 };
try {
int _jspx_eval_form_hidden_0 = _jspx_th_form_hidden_0.doStartTag();
if (_jspx_th_form_hidden_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_form_hidden_0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_hidden_0.doCatch(_jspx_exception);
} finally {
_jspx_th_form_hidden_0.doFinally();
_jspx_tagPool_form_hidden_path_nobody.reuse(_jspx_th_form_hidden_0);
}
return false;
}
private boolean _jspx_meth_form_input_0(javax.servlet.jsp.tagext.JspTag _jspx_th_form_form_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_form_form_0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// form:input
org.springframework.web.servlet.tags.form.InputTag _jspx_th_form_input_0 = (org.springframework.web.servlet.tags.form.InputTag) _jspx_tagPool_form_input_path_nobody.get(org.springframework.web.servlet.tags.form.InputTag.class);
_jspx_th_form_input_0.setPageContext(_jspx_page_context);
_jspx_th_form_input_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_form_0);
_jspx_th_form_input_0.setPath("name");
int[] _jspx_push_body_count_form_input_0 = new int[] { 0 };
try {
int _jspx_eval_form_input_0 = _jspx_th_form_input_0.doStartTag();
if (_jspx_th_form_input_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_form_input_0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_input_0.doCatch(_jspx_exception);
} finally {
_jspx_th_form_input_0.doFinally();
_jspx_tagPool_form_input_path_nobody.reuse(_jspx_th_form_input_0);
}
return false;
}
private boolean _jspx_meth_form_input_1(javax.servlet.jsp.tagext.JspTag _jspx_th_form_form_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_form_form_0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// form:input
org.springframework.web.servlet.tags.form.InputTag _jspx_th_form_input_1 = (org.springframework.web.servlet.tags.form.InputTag) _jspx_tagPool_form_input_path_nobody.get(org.springframework.web.servlet.tags.form.InputTag.class);
_jspx_th_form_input_1.setPageContext(_jspx_page_context);
_jspx_th_form_input_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_form_0);
_jspx_th_form_input_1.setPath("manufacturer");
int[] _jspx_push_body_count_form_input_1 = new int[] { 0 };
try {
int _jspx_eval_form_input_1 = _jspx_th_form_input_1.doStartTag();
if (_jspx_th_form_input_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_form_input_1[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_input_1.doCatch(_jspx_exception);
} finally {
_jspx_th_form_input_1.doFinally();
_jspx_tagPool_form_input_path_nobody.reuse(_jspx_th_form_input_1);
}
return false;
}
private boolean _jspx_meth_form_input_2(javax.servlet.jsp.tagext.JspTag _jspx_th_form_form_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_form_form_0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// form:input
org.springframework.web.servlet.tags.form.InputTag _jspx_th_form_input_2 = (org.springframework.web.servlet.tags.form.InputTag) _jspx_tagPool_form_input_path_nobody.get(org.springframework.web.servlet.tags.form.InputTag.class);
_jspx_th_form_input_2.setPageContext(_jspx_page_context);
_jspx_th_form_input_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_form_0);
_jspx_th_form_input_2.setPath("price");
int[] _jspx_push_body_count_form_input_2 = new int[] { 0 };
try {
int _jspx_eval_form_input_2 = _jspx_th_form_input_2.doStartTag();
if (_jspx_th_form_input_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_form_input_2[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_input_2.doCatch(_jspx_exception);
} finally {
_jspx_th_form_input_2.doFinally();
_jspx_tagPool_form_input_path_nobody.reuse(_jspx_th_form_input_2);
}
return false;
}
}
diff --git a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/index_jsp.class b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/index_jsp.class
index 23e8cf5..20bbd1a 100644
Binary files a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/index_jsp.class and b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/index_jsp.class differ
diff --git a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/index_jsp.java b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/index_jsp.java
index e0b3a0d..9419dc1 100644
--- a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/index_jsp.java
+++ b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/index_jsp.java
@@ -1,255 +1,267 @@
package org.apache.jsp.WEB_002dINF.views.product;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.Vector _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_forEach_var_items;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_out_value_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_fmt_formatNumber_value_type_nobody;
private org.apache.jasper.runtime.ResourceInjector _jspx_resourceInjector;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_jspx_tagPool_c_forEach_var_items = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_out_value_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_fmt_formatNumber_value_type_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
}
public void _jspDestroy() {
_jspx_tagPool_c_forEach_var_items.release();
_jspx_tagPool_c_out_value_nobody.release();
_jspx_tagPool_fmt_formatNumber_value_type_nobody.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n");
out.write("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
out.write("\n");
out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
out.write("\t<head>\n");
out.write("\t\t<meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />\n");
out.write("\t\t<title>\n");
out.write("\t\t\tIndex\n");
out.write("\t\t</title>\n");
+ out.write(" <link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("/stylesheets/styles.css\" />\n");
out.write("\t</head>\n");
out.write("\t<body>\n");
- out.write(" <h1>Index</h1>\n");
+ out.write(" <h1 id=\"title\">Index</h1>\n");
out.write("\n");
out.write(" <table>\n");
out.write(" <tr>\n");
out.write(" <th>Id</th>\n");
out.write(" <th>Name</th>\n");
out.write(" <th>Manufacturer</th>\n");
out.write(" <th>Price</th>\n");
out.write(" <th>Action</th>\n");
out.write(" </tr>\n");
out.write(" ");
if (_jspx_meth_c_forEach_0(_jspx_page_context))
return;
out.write("\n");
out.write(" </table>\n");
out.write("\n");
- out.write("\n");
- out.write(" <a title=\"Create a new product\" href=\"");
+ out.write(" <div class=\"buttons\">\n");
+ out.write(" <a class=\"button\" title=\"Create a new product\" href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/product/create.htm\">Create</a>\n");
- out.write("\t</body>\n");
+ out.write(" </div>\n");
+ out.write(" </body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_c_forEach_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_0 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_0.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_0.setParent(null);
_jspx_th_c_forEach_0.setVar("product");
_jspx_th_c_forEach_0.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${products}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_0 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_0 = _jspx_th_c_forEach_0.doStartTag();
if (_jspx_eval_c_forEach_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
- out.write(" <tr>\n");
+ out.write(" <tr id=\"product_row_");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\">\n");
out.write(" <td>");
if (_jspx_meth_c_out_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_0, _jspx_page_context, _jspx_push_body_count_c_forEach_0))
return true;
out.write("</td>\n");
out.write(" <td>");
if (_jspx_meth_c_out_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_0, _jspx_page_context, _jspx_push_body_count_c_forEach_0))
return true;
out.write("</td>\n");
out.write(" <td>");
if (_jspx_meth_c_out_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_0, _jspx_page_context, _jspx_push_body_count_c_forEach_0))
return true;
out.write("</td>\n");
out.write(" <td>");
if (_jspx_meth_fmt_formatNumber_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_0, _jspx_page_context, _jspx_push_body_count_c_forEach_0))
return true;
out.write("</td>\n");
out.write(" <td>\n");
out.write(" <a href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/product/view.htm?id=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\" title=\"View\" id=\"view_");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\">View</a>\n");
out.write(" <a href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/product/edit.htm?id=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
- out.write("\">Edit</a>\n");
+ out.write("\" title=\"Edit\" id=\"edit_");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\"> Edit</a>\n");
out.write(" <a href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/product/delete.htm?id=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\" title=\"Delete\" id=\"delete_");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\">Delete</a>\n");
out.write(" </td>\n");
out.write("\n");
out.write("\n");
out.write(" \n");
out.write(" </tr>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_0.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_0.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_0);
}
return false;
}
private boolean _jspx_meth_c_out_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_0 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_0.setPageContext(_jspx_page_context);
_jspx_th_c_out_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_0);
_jspx_th_c_out_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_0 = _jspx_th_c_out_0.doStartTag();
if (_jspx_th_c_out_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_0);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_0);
return false;
}
private boolean _jspx_meth_c_out_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_1 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_1.setPageContext(_jspx_page_context);
_jspx_th_c_out_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_0);
_jspx_th_c_out_1.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.name}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_1 = _jspx_th_c_out_1.doStartTag();
if (_jspx_th_c_out_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_1);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_1);
return false;
}
private boolean _jspx_meth_c_out_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_2 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_2.setPageContext(_jspx_page_context);
_jspx_th_c_out_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_0);
_jspx_th_c_out_2.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.manufacturer}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_2 = _jspx_th_c_out_2.doStartTag();
if (_jspx_th_c_out_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_2);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_2);
return false;
}
private boolean _jspx_meth_fmt_formatNumber_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// fmt:formatNumber
org.apache.taglibs.standard.tag.rt.fmt.FormatNumberTag _jspx_th_fmt_formatNumber_0 = (org.apache.taglibs.standard.tag.rt.fmt.FormatNumberTag) _jspx_tagPool_fmt_formatNumber_value_type_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.FormatNumberTag.class);
_jspx_th_fmt_formatNumber_0.setPageContext(_jspx_page_context);
_jspx_th_fmt_formatNumber_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_0);
_jspx_th_fmt_formatNumber_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.price}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
_jspx_th_fmt_formatNumber_0.setType("currency");
int _jspx_eval_fmt_formatNumber_0 = _jspx_th_fmt_formatNumber_0.doStartTag();
if (_jspx_th_fmt_formatNumber_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_fmt_formatNumber_value_type_nobody.reuse(_jspx_th_fmt_formatNumber_0);
return true;
}
_jspx_tagPool_fmt_formatNumber_value_type_nobody.reuse(_jspx_th_fmt_formatNumber_0);
return false;
}
}
diff --git a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/view_jsp.class b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/view_jsp.class
index d6f1562..4906fda 100644
Binary files a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/view_jsp.class and b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/view_jsp.class differ
diff --git a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/view_jsp.java b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/view_jsp.java
index 73b9cfc..21e7759 100644
--- a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/view_jsp.java
+++ b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/view_jsp.java
@@ -1,145 +1,150 @@
package org.apache.jsp.WEB_002dINF.views.product;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class view_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.Vector _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_remove_var_scope_nobody;
private org.apache.jasper.runtime.ResourceInjector _jspx_resourceInjector;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_jspx_tagPool_c_remove_var_scope_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
}
public void _jspDestroy() {
_jspx_tagPool_c_remove_var_scope_nobody.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n");
out.write("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
out.write("\t<head>\n");
out.write("\t\t<meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />\n");
out.write("\t\t<title>\n");
out.write("\t\t\tView\n");
out.write("\t\t</title>\n");
+ out.write(" <link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("/stylesheets/styles.css\" />\n");
out.write("\t</head>\n");
out.write("\t<body>\n");
out.write(" <h1>View</h1>\n");
out.write("\n");
- out.write(" ");
+ out.write(" <div id=\"message\" class=\"success\">\n");
+ out.write(" ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionScope.message}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\n");
- out.write(" ");
+ out.write(" ");
if (_jspx_meth_c_remove_0(_jspx_page_context))
return;
out.write("\n");
+ out.write(" </div>\n");
out.write("\n");
out.write(" <div>\n");
out.write(" <span>id: </span> ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\n");
out.write(" </div>\n");
out.write(" <div>\n");
out.write(" <span>name: </span> ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.name}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\n");
out.write(" </div>\n");
out.write(" <div>\n");
out.write(" <span>manufactuerer: </span> ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.manufacturer}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\n");
out.write(" </div>\n");
out.write(" <div>\n");
out.write(" <span>price: </span> ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.price}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div>\n");
out.write(" <a href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/product/index.htm\">Index</a>\n");
out.write(" <a href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/product/edit.htm?id=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\">Edit</a>\n");
out.write(" <a href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/product/delete.htm?id=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\">Delete</a>\n");
out.write(" </div>\n");
out.write("\t</body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_c_remove_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:remove
org.apache.taglibs.standard.tag.common.core.RemoveTag _jspx_th_c_remove_0 = (org.apache.taglibs.standard.tag.common.core.RemoveTag) _jspx_tagPool_c_remove_var_scope_nobody.get(org.apache.taglibs.standard.tag.common.core.RemoveTag.class);
_jspx_th_c_remove_0.setPageContext(_jspx_page_context);
_jspx_th_c_remove_0.setParent(null);
_jspx_th_c_remove_0.setVar("message");
_jspx_th_c_remove_0.setScope("session");
int _jspx_eval_c_remove_0 = _jspx_th_c_remove_0.doStartTag();
if (_jspx_th_c_remove_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_remove_var_scope_nobody.reuse(_jspx_th_c_remove_0);
return true;
}
_jspx_tagPool_c_remove_var_scope_nobody.reuse(_jspx_th_c_remove_0);
return false;
}
}
|
jcblitz/maven-selenium-demo
|
79c041c72cd0b79bad43202ac70005534cbf6823
|
Added more sample data. Added more CRUD functionality
|
diff --git a/pom.xml b/pom.xml
index bd05c5b..c55a982 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,61 +1,110 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.blitzstein.demo</groupId>
<artifactId>testing-demo</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>testing-demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>2.5.6</version>
</dependency>
-
+ <dependency>
+ <groupId>org.openqa.selenium.client-drivers</groupId>
+ <artifactId>selenium-java-client-driver</artifactId>
+ <version>1.0-beta-2</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
+ <repositories>
+ <repository>
+ <id>openqa-releases</id>
+ <name>Openqa Release Repository</name>
+ <url>http://nexus.openqa.org/content/repositories/releases</url>
+ <layout>default</layout>
+ <snapshots>
+ <enabled>false</enabled>
+ </snapshots>
+ <releases>
+ <enabled>true</enabled>
+ </releases>
+ </repository>
+ <repository>
+ <id>openqa-snapshots</id>
+ <name>Openqa Snapshot Repository</name>
+ <url>http://nexus.openqa.org/content/repositories/snapshots</url>
+ <layout>default</layout>
+ <snapshots>
+ <enabled>true</enabled>
+ <updatePolicy>daily</updatePolicy>
+ <checksumPolicy>ignore</checksumPolicy>
+ </snapshots>
+ <releases>
+ <enabled>false</enabled>
+ </releases>
+ </repository>
+ </repositories>
+
<build>
<finalName>testing-demo</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<additionalClasspathElements>
<additionalClasspathElement>
src/main/webapp/WEB-INF/
</additionalClasspathElement>
</additionalClasspathElements>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>selenium-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <phase>pre-integration-test</phase>
+ <goals>
+ <goal>start-server</goal>
+ </goals>
+ <configuration>
+ <background>true</background>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
diff --git a/src/main/java/net/blitzstein/demo/testing/domain/Product.java b/src/main/java/net/blitzstein/demo/testing/domain/Product.java
index 22a2831..45de49d 100644
--- a/src/main/java/net/blitzstein/demo/testing/domain/Product.java
+++ b/src/main/java/net/blitzstein/demo/testing/domain/Product.java
@@ -1,71 +1,102 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
-
package net.blitzstein.demo.testing.domain;
/**
*
* @author jared
*/
public class Product {
+
private Integer id;
private String name, description;
private float price;
private String manufacturer;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Product() {
}
public Product(Integer id, String name, String description, String manufacturer, float price) {
this.id = id;
this.name = name;
this.description = description;
this.price = price;
this.manufacturer = manufacturer;
}
-
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ final Product other = (Product) obj;
+ if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 7;
+ return hash;
+ }
+
+ public int compareTo(Object prod) {
+
+ if (this.id < ((Product)prod).getId()) {
+ return -1;
+ } else if (this.id > ((Product)prod).getId()) {
+ return 1;
+ } else {
+ return 0;
+ }
+ }
+
}
diff --git a/src/main/java/net/blitzstein/demo/testing/domain/ProductComparable.java b/src/main/java/net/blitzstein/demo/testing/domain/ProductComparable.java
new file mode 100644
index 0000000..6247a27
--- /dev/null
+++ b/src/main/java/net/blitzstein/demo/testing/domain/ProductComparable.java
@@ -0,0 +1,30 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package net.blitzstein.demo.testing.domain;
+
+import java.util.Comparator;
+
+/**
+ *
+ * @author jared
+ */
+public class ProductComparable implements Comparator {
+
+ public int compare(Object o1, Object o2) {
+
+ Product prod1 = (Product)o1;
+ Product prod2 = (Product)o2;
+
+ if (prod1.getId() < prod2.getId()) {
+ return -1;
+ } else if (prod1.getId() > prod2.getId()) {
+ return 1;
+ } else {
+ return 0;
+ }
+ }
+
+}
diff --git a/src/main/java/net/blitzstein/demo/testing/web/ProductController.java b/src/main/java/net/blitzstein/demo/testing/web/ProductController.java
index 528fba8..dd98b2b 100644
--- a/src/main/java/net/blitzstein/demo/testing/web/ProductController.java
+++ b/src/main/java/net/blitzstein/demo/testing/web/ProductController.java
@@ -1,101 +1,125 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.blitzstein.demo.testing.web;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
import net.blitzstein.demo.testing.domain.Product;
+import net.blitzstein.demo.testing.domain.ProductComparable;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.context.request.WebRequest;
/**
*
* @author jared
*/
@Controller
public class ProductController implements ApplicationContextAware {
private List<Product> products = new ArrayList();
private ApplicationContext context;
@RequestMapping(value = "/product/index.htm", method = RequestMethod.GET)
public void index(Model model) {
model.addAttribute("products", getProducts());
}
public void setProducts(List<Product> products) {
this.products = products;
}
@RequestMapping(value = "/product/view.htm", method = RequestMethod.GET)
public void view(Model model, @RequestParam("id") int id) {
Product product = getProduct(id);
model.addAttribute(product);
}
@RequestMapping(value = "/product/edit.htm", method = RequestMethod.GET)
public void edit(Model model, @RequestParam("id") int id) {
Product product = getProduct(id);
model.addAttribute(product);
}
@RequestMapping(value = "/product/create.htm", method = RequestMethod.GET)
public String create(Model model) {
model.addAttribute(new Product());
return "product/edit";
}
@RequestMapping(value = "/product/save.htm", method = RequestMethod.POST)
- public void save(
- @ModelAttribute("Product") Product product) {
+ public String save(
+ @ModelAttribute("Product") Product product, Model model, WebRequest webRequest) {
+
+ if (product.getId() == null) {
+ Integer id = getNextProductId();
+ product.setId(id);
+ } else {
+ Product old = getProduct(product.getId());
+ this.products.remove(old);
+ }
+ this.products.add(product);
+ registerMessage(webRequest, "Product was saved!");
+ return "redirect:view.htm?id="+product.getId();
}
@RequestMapping(value = "/product/delete.htm", method = RequestMethod.GET)
public String delete(@RequestParam("id") int id) {
deleteProduct(id);
return "redirect:index.htm";
}
private void deleteProduct(int id) {
Product product = getProduct(id);
this.products.remove(product);
}
private List<Product> getProducts() {
//return products;
if (this.products == null || this.products.isEmpty()) {
Map productMap = context.getBeansOfType(net.blitzstein.demo.testing.domain.Product.class);
this.products = new ArrayList(productMap.values());
}
+ Collections.sort(products, new ProductComparable());
return this.products;
}
private Product getProduct(Integer id) {
for (Product product : products) {
if (product.getId().equals(id)) {
return product;
}
}
return null;
}
+ private int getNextProductId() {
+ Product product = this.getProducts().get(this.getProducts().size()-1);
+ return product.getId() + 1;
+ }
+
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.context = context;
}
+
+ private void registerMessage(WebRequest webRequest, String message) {
+ webRequest.setAttribute("message", message, WebRequest.SCOPE_SESSION);
+ }
}
diff --git a/src/main/webapp/WEB-INF/testingdemo-servlet.xml b/src/main/webapp/WEB-INF/testingdemo-servlet.xml
index c92fe68..37b710d 100644
--- a/src/main/webapp/WEB-INF/testingdemo-servlet.xml
+++ b/src/main/webapp/WEB-INF/testingdemo-servlet.xml
@@ -1,65 +1,231 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<context:component-scan base-package="net.blitzstein.demo.testing.web"/>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>display</value>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/product/*=productController
</value>
</property>
</bean>
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
<property name="order" value="2" />
</bean>
<bean id="productController" class="net.blitzstein.demo.testing.web.ProductController">
</bean>
-
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="1" />
- <property name="name" value="Product One" />
- <property name="manufacturer" value="Apple" />
- <property name="price" value="3000.50" />
-
+ <property name="name" value="eu" />
+ <property name="manufacturer" value="ullamcorper," />
+ <property name="price" value="254" />
</bean>
<bean class="net.blitzstein.demo.testing.domain.Product">
<property name="id" value="2" />
- <property name="name" value="Product Two" />
- <property name="manufacturer" value="IBM" />
- <property name="price" value="1500.00" />
+ <property name="name" value="eget" />
+ <property name="manufacturer" value="rutrum" />
+ <property name="price" value="605" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="3" />
+ <property name="name" value="vulputate dui," />
+ <property name="manufacturer" value="eu" />
+ <property name="price" value="325" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="4" />
+ <property name="name" value="diam. Pellentesque habitant" />
+ <property name="manufacturer" value="tellus." />
+ <property name="price" value="559" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="5" />
+ <property name="name" value="eros" />
+ <property name="manufacturer" value="sagittis. Nullam" />
+ <property name="price" value="435" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="6" />
+ <property name="name" value="nibh vulputate" />
+ <property name="manufacturer" value="suscipit," />
+ <property name="price" value="667" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="7" />
+ <property name="name" value="dignissim magna a" />
+ <property name="manufacturer" value="nunc." />
+ <property name="price" value="413" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="8" />
+ <property name="name" value="massa. Integer" />
+ <property name="manufacturer" value="ultrices sit" />
+ <property name="price" value="728" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="9" />
+ <property name="name" value="convallis in," />
+ <property name="manufacturer" value="vel," />
+ <property name="price" value="530" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="10" />
+ <property name="name" value="magnis dis parturient" />
+ <property name="manufacturer" value="vitae, orci." />
+ <property name="price" value="954" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="11" />
+ <property name="name" value="quis," />
+ <property name="manufacturer" value="fringilla" />
+ <property name="price" value="167" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="12" />
+ <property name="name" value="non dui" />
+ <property name="manufacturer" value="dui, in" />
+ <property name="price" value="824" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="13" />
+ <property name="name" value="dignissim" />
+ <property name="manufacturer" value="luctus. Curabitur" />
+ <property name="price" value="409" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="14" />
+ <property name="name" value="amet, consectetuer adipiscing" />
+ <property name="manufacturer" value="mi eleifend" />
+ <property name="price" value="532" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="15" />
+ <property name="name" value="vitae," />
+ <property name="manufacturer" value="lobortis" />
+ <property name="price" value="973" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="16" />
+ <property name="name" value="ut, nulla. Cras" />
+ <property name="manufacturer" value="orci," />
+ <property name="price" value="530" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="17" />
+ <property name="name" value="Curabitur" />
+ <property name="manufacturer" value="urna. Nullam" />
+ <property name="price" value="430" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="18" />
+ <property name="name" value="eros. Proin ultrices." />
+ <property name="manufacturer" value="eget magna." />
+ <property name="price" value="676" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="19" />
+ <property name="name" value="fermentum vel," />
+ <property name="manufacturer" value="porttitor" />
+ <property name="price" value="528" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="20" />
+ <property name="name" value="sem. Pellentesque" />
+ <property name="manufacturer" value="eu eros." />
+ <property name="price" value="658" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="21" />
+ <property name="name" value="sodales" />
+ <property name="manufacturer" value="Quisque varius." />
+ <property name="price" value="87" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="22" />
+ <property name="name" value="torquent per conubia" />
+ <property name="manufacturer" value="diam" />
+ <property name="price" value="722" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="23" />
+ <property name="name" value="risus. Donec nibh" />
+ <property name="manufacturer" value="Proin" />
+ <property name="price" value="872" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="24" />
+ <property name="name" value="malesuada vel," />
+ <property name="manufacturer" value="Morbi vehicula." />
+ <property name="price" value="538" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="25" />
+ <property name="name" value="Ut semper" />
+ <property name="manufacturer" value="pretium" />
+ <property name="price" value="661" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="26" />
+ <property name="name" value="urna suscipit nonummy." />
+ <property name="manufacturer" value="Ut" />
+ <property name="price" value="370" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="27" />
+ <property name="name" value="mattis" />
+ <property name="manufacturer" value="eget metus." />
+ <property name="price" value="883" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="28" />
+ <property name="name" value="arcu et pede." />
+ <property name="manufacturer" value="mauris" />
+ <property name="price" value="337" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="29" />
+ <property name="name" value="ut, molestie in," />
+ <property name="manufacturer" value="erat. Sed" />
+ <property name="price" value="119" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="30" />
+ <property name="name" value="sagittis. Nullam vitae" />
+ <property name="manufacturer" value="eget massa." />
+ <property name="price" value="80" />
</bean>
</beans>
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/views/product/edit.jsp b/src/main/webapp/WEB-INF/views/product/edit.jsp
index 5c81a19..c05e513 100644
--- a/src/main/webapp/WEB-INF/views/product/edit.jsp
+++ b/src/main/webapp/WEB-INF/views/product/edit.jsp
@@ -1,13 +1,38 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>
Edit
</title>
</head>
<body>
<h1>Edit</h1>
+
+ <form:form commandName="product" action="${pageContext.request.contextPath}/product/save.htm">
+ <form:hidden path="id" />
+ <table>
+ <tr>
+ <td>Name:</td>
+ <td><form:input path="name" /></td>
+ </tr>
+ <tr>
+ <td>Manufacturer:</td>
+ <td><form:input path="manufacturer" /></td>
+ </tr>
+ <tr>
+ <td>Price:</td>
+ <td><form:input path="price" /></td>
+ </tr>
+ <tr>
+ <td colspan="2">
+ <input type="submit" value="Save Changes" />
+ <a href="${pageContext.request.contextPath}/product/view.htm?id=${product.id}">Cancel</a>
+ </td>
+ </tr>
+ </table>
+ </form:form>
</body>
</html>
diff --git a/src/main/webapp/WEB-INF/views/product/view.jsp b/src/main/webapp/WEB-INF/views/product/view.jsp
index aab2b7e..ad6cac3 100644
--- a/src/main/webapp/WEB-INF/views/product/view.jsp
+++ b/src/main/webapp/WEB-INF/views/product/view.jsp
@@ -1,13 +1,38 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
+
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>
View
</title>
</head>
<body>
<h1>View</h1>
+
+ ${sessionScope.message}
+ <c:remove var="message" scope="session"/>
+
+ <div>
+ <span>id: </span> ${product.id}
+ </div>
+ <div>
+ <span>name: </span> ${product.name}
+ </div>
+ <div>
+ <span>manufactuerer: </span> ${product.manufacturer}
+ </div>
+ <div>
+ <span>price: </span> ${product.price}
+ </div>
+
+ <div>
+ <a href="${pageContext.request.contextPath}/product/index.htm">Index</a>
+ <a href="${pageContext.request.contextPath}/product/edit.htm?id=${product.id}">Edit</a>
+ <a href="${pageContext.request.contextPath}/product/delete.htm?id=${product.id}">Delete</a>
+ </div>
</body>
</html>
diff --git a/src/main/webapp/index.jsp b/src/main/webapp/index.jsp
index c38169b..9e9d551 100644
--- a/src/main/webapp/index.jsp
+++ b/src/main/webapp/index.jsp
@@ -1,5 +1,2 @@
-<html>
-<body>
-<h2>Hello World!</h2>
-</body>
-</html>
+<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
+<c:redirect url="/product/index.htm"/>
diff --git a/src/test/java/net/blitzstein/demo/testing/integration/web/ProductSeleniumTest.java b/src/test/java/net/blitzstein/demo/testing/integration/web/ProductSeleniumTest.java
new file mode 100644
index 0000000..75995ab
--- /dev/null
+++ b/src/test/java/net/blitzstein/demo/testing/integration/web/ProductSeleniumTest.java
@@ -0,0 +1,60 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package net.blitzstein.demo.testing.integration.web;
+
+import org.junit.Test;
+import static org.junit.Assert.*;
+import com.thoughtworks.selenium.*;
+
+import com.thoughtworks.selenium.DefaultSelenium;
+import org.junit.Before;
+
+/**
+ *
+ * @author jared
+ */
+public class ProductSeleniumTest extends SeleneseTestCase {
+
+ @Test
+ public void thisIsTrue() {
+ assertTrue(true);
+ }
+
+ @Before
+ public void before() throws Exception {
+ setUp("http://www.google.com/", "*chrome");
+ }
+
+ @Test
+ public void testSomethingSimple() throws Exception {
+ //DefaultSelenium selenium = createSeleniumClient("http://localhost:8080/");
+ //selenium.start();
+
+ //
+ // This is an exmaple of testing the Apache Geroniom Welcome page for specific text
+ //
+
+ selenium.open("/");
+ selenium.type("//input[@name='q']", "test");
+ selenium.click("btnG");
+ verifyTrue(selenium.isElementPresent("//a[@id='logo']/img"));
+
+
+// selenium.click("link=JVM");
+// selenium.waitForPageToLoad("30000");
+// selenium.click("link=Welcome");
+// selenium.waitForPageToLoad("30000");
+// assertEquals("Geronimo Console", selenium.getTitle());
+// assertEquals("Welcome", selenium.getText(
+// "xpath=/html/body/table[@id='rootfragment']/tbody/tr[2]/td/table/tbody/tr[2]/td[4]/table/tbody/tr[1]/td/table/tbody/tr[1]/td/div/table/tbody/tr/td[2]/table/tbody/tr/td[1]/strong"));
+//
+// // Test help link
+// selenium.click("link=help");
+// selenium.waitForPageToLoad("30000");
+// selenium.isTextPresent("This is the help for the Geronimo Administration Console Welcome.");
+
+ //selenium.stop();
+ }
+}
diff --git a/target/classes/display.properties b/target/classes/display.properties
new file mode 100644
index 0000000..57ed665
--- /dev/null
+++ b/target/classes/display.properties
@@ -0,0 +1,3 @@
+# To change this template, choose Tools | Templates
+# and open the template in the editor.
+
diff --git a/target/classes/net/blitzstein/demo/testing/domain/Product.class b/target/classes/net/blitzstein/demo/testing/domain/Product.class
new file mode 100644
index 0000000..5ec91fc
Binary files /dev/null and b/target/classes/net/blitzstein/demo/testing/domain/Product.class differ
diff --git a/target/classes/net/blitzstein/demo/testing/domain/ProductComparable.class b/target/classes/net/blitzstein/demo/testing/domain/ProductComparable.class
new file mode 100644
index 0000000..7113feb
Binary files /dev/null and b/target/classes/net/blitzstein/demo/testing/domain/ProductComparable.class differ
diff --git a/target/classes/net/blitzstein/demo/testing/web/ProductController.class b/target/classes/net/blitzstein/demo/testing/web/ProductController.class
new file mode 100644
index 0000000..f7c1b88
Binary files /dev/null and b/target/classes/net/blitzstein/demo/testing/web/ProductController.class differ
diff --git a/target/maven-archiver/pom.properties b/target/maven-archiver/pom.properties
new file mode 100644
index 0000000..ec84b71
--- /dev/null
+++ b/target/maven-archiver/pom.properties
@@ -0,0 +1,5 @@
+#Generated by Maven
+#Thu May 14 23:02:01 EDT 2009
+version=1.0-SNAPSHOT
+groupId=net.blitzstein.demo
+artifactId=testing-demo
diff --git a/target/selenium/user-extensions.js b/target/selenium/user-extensions.js
new file mode 100644
index 0000000..7469018
--- /dev/null
+++ b/target/selenium/user-extensions.js
@@ -0,0 +1,129 @@
+//
+// Default user extensions from: jar:file:/Users/jared/.m2/org/codehaus/mojo/selenium-maven-plugin/1.0-rc-1/selenium-maven-plugin-1.0-rc-1.jar!/org/codehaus/mojo/selenium/default-user-extensions.js
+//
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//
+// $Id: default-user-extensions.js 4489 2007-07-01 23:49:34Z user57 $
+//
+
+//
+// Incorporated from: http://wiki.openqa.org/display/SEL/removeCookie
+//
+
+function createCookie(doc, name, value, path, days) {
+ if (!path) {
+ path = "/";
+ }
+
+ if (days) {
+ var date = new Date();
+ date.setTime(date.getTime()+(days*24*60*60*1000));
+ var expires = "; expires=" + date.toGMTString();
+ }
+ else {
+ var expires = "";
+ }
+
+ doc.cookie = name + "=" + value + expires + "; path=" + path;
+}
+
+/**
+ * Removes the cookie with the given name.
+ * text - the cookie name
+ * path - the cookie path
+ */
+Selenium.prototype.removeCookie = function(text, path) {
+ createCookie(this.page().currentDocument, text, "", path, -1);
+};
+
+//
+// Incorporated from user-extensions.js.sample from Selenium RC 0.8.1
+//
+
+// The following examples try to give an indication of how Selenium can be extended with javascript.
+
+/**
+ * All do* methods on the Selenium prototype are added as actions.
+ * Eg add a typeRepeated action to Selenium, which types the text twice into a text box.
+ * The typeTwiceAndWait command will be available automatically
+ */
+Selenium.prototype.doTypeRepeated = function(locator, text) {
+ // All locator-strategies are automatically handled by "findElement"
+ var element = this.page().findElement(locator);
+
+ // Create the text to type
+ var valueToType = text + text;
+
+ // Replace the element text with the new text
+ this.page().replaceText(element, valueToType);
+};
+
+/**
+ * All assert* methods on the Selenium prototype are added as checks.
+ * Eg add a assertValueRepeated check, that makes sure that the element value
+ * consists of the supplied text repeated.
+ * The verify version will be available automatically.
+ */
+Selenium.prototype.assertValueRepeated = function(locator, text) {
+ // All locator-strategies are automatically handled by "findElement"
+ var element = this.page().findElement(locator);
+
+ // Create the text to verify
+ var expectedValue = text + text;
+
+ // Get the actual element value
+ var actualValue = element.value;
+
+ // Make sure the actual value matches the expected
+ Assert.matches(expectedValue, actualValue);
+};
+
+/**
+ * All get* methods on the Selenium prototype result in
+ * store, assert, assertNot, verify, verifyNot, waitFor, and waitForNot commands.
+ * E.g. add a getTextLength method that returns the length of the text
+ * of a specified element.
+ * Will result in support for storeTextLength, assertTextLength, etc.
+ */
+Selenium.prototype.getTextLength = function(locator) {
+ return this.getText(locator).length;
+};
+
+/**
+ * All locateElementBy* methods are added as locator-strategies.
+ * Eg add a "valuerepeated=" locator, that finds the first element with the supplied value, repeated.
+ * The "inDocument" is a the document you are searching.
+ */
+PageBot.prototype.locateElementByValueRepeated = function(text, inDocument) {
+ // Create the text to search for
+ var expectedValue = text + text;
+
+ // Loop through all elements, looking for ones that have a value === our expected value
+ var allElements = inDocument.getElementsByTagName("*");
+ for (var i = 0; i < allElements.length; i++) {
+ var testElement = allElements[i];
+ if (testElement.value && testElement.value === expectedValue) {
+ return testElement;
+ }
+ }
+ return null;
+};
+
diff --git a/target/surefire-reports/TEST-net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.xml b/target/surefire-reports/TEST-net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.xml
new file mode 100644
index 0000000..3a18b42
--- /dev/null
+++ b/target/surefire-reports/TEST-net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.xml
@@ -0,0 +1,98 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<testsuite errors="1" skipped="0" tests="1" time="7.271" failures="0" name="net.blitzstein.demo.testing.integration.web.ProductSeleniumTest">
+ <properties>
+ <property value="Java(TM) 2 Runtime Environment, Standard Edition" name="java.runtime.name"/>
+ <property value="/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Libraries" name="sun.boot.library.path"/>
+ <property value="1.5.0_16-133" name="java.vm.version"/>
+ <property value="true" name="awt.nativeDoubleBuffering"/>
+ <property value="false" name="gopherProxySet"/>
+ <property value="Apple Inc." name="java.vm.vendor"/>
+ <property value="http://www.apple.com/" name="java.vendor.url"/>
+ <property value=":" name="path.separator"/>
+ <property value="Java HotSpot(TM) Client VM" name="java.vm.name"/>
+ <property value="sun.io" name="file.encoding.pkg"/>
+ <property value="US" name="user.country"/>
+ <property value="SUN_STANDARD" name="sun.java.launcher"/>
+ <property value="unknown" name="sun.os.patch.level"/>
+ <property value="Java Virtual Machine Specification" name="java.vm.specification.name"/>
+ <property value="/Users/jared/Documents/programming/java/netbeans-workspace/testing-demo" name="user.dir"/>
+ <property value="1.5.0_16-b06-284" name="java.runtime.version"/>
+ <property value="apple.awt.CGraphicsEnvironment" name="java.awt.graphicsenv"/>
+ <property value="/Users/jared/Documents/programming/java/netbeans-workspace/testing-demo" name="basedir"/>
+ <property value="/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/endorsed" name="java.endorsed.dirs"/>
+ <property value="i386" name="os.arch"/>
+ <property value="/tmp/surefirebooter16574.jar" name="surefire.real.class.path"/>
+ <property value="/tmp" name="java.io.tmpdir"/>
+ <property value="
+" name="line.separator"/>
+ <property value="Sun Microsystems Inc." name="java.vm.specification.vendor"/>
+ <property value="Mac OS X" name="os.name"/>
+ <property value="MacRoman" name="sun.jnu.encoding"/>
+ <property value=".:/Users/jared/Library/Java/Extensions:/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java" name="java.library.path"/>
+ <property value="/Users/jared/Documents/programming/java/netbeans-workspace/testing-demo/target/test-classes:/Users/jared/Documents/programming/java/netbeans-workspace/testing-demo/target/classes:/Users/jared/.m2/junit/junit/4.4/junit-4.4.jar:/Users/jared/.m2/org/springframework/spring-webmvc/2.5.6/spring-webmvc-2.5.6.jar:/Users/jared/.m2/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar:/Users/jared/.m2/org/springframework/spring-beans/2.5.6/spring-beans-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-core/2.5.6/spring-core-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-context/2.5.6/spring-context-2.5.6.jar:/Users/jared/.m2/aopalliance/aopalliance/1.0/aopalliance-1.0.jar:/Users/jared/.m2/org/springframework/spring-context-support/2.5.6/spring-context-support-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-web/2.5.6/spring-web-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-test/2.5.6/spring-test-2.5.6.jar:/Users/jared/.m2/org/openqa/selenium/client-drivers/selenium-java-client-driver/1.0-beta-2/selenium-java-client-driver-1.0-beta-2.jar:src/main/webapp/WEB-INF/:" name="surefire.test.class.path"/>
+ <property value="Java Platform API Specification" name="java.specification.name"/>
+ <property value="49.0" name="java.class.version"/>
+ <property value="HotSpot Client Compiler" name="sun.management.compiler"/>
+ <property value="10.5.6" name="os.version"/>
+ <property value="local|*.local|169.254/16|*.169.254/16" name="http.nonProxyHosts"/>
+ <property value="/Users/jared" name="user.home"/>
+ <property value="" name="user.timezone"/>
+ <property value="apple.awt.CPrinterJob" name="java.awt.printerjob"/>
+ <property value="1.5" name="java.specification.version"/>
+ <property value="MacRoman" name="file.encoding"/>
+ <property value="jared" name="user.name"/>
+ <property value="/Users/jared/Documents/programming/java/netbeans-workspace/testing-demo/target/test-classes:/Users/jared/Documents/programming/java/netbeans-workspace/testing-demo/target/classes:/Users/jared/.m2/junit/junit/4.4/junit-4.4.jar:/Users/jared/.m2/org/springframework/spring-webmvc/2.5.6/spring-webmvc-2.5.6.jar:/Users/jared/.m2/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar:/Users/jared/.m2/org/springframework/spring-beans/2.5.6/spring-beans-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-core/2.5.6/spring-core-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-context/2.5.6/spring-context-2.5.6.jar:/Users/jared/.m2/aopalliance/aopalliance/1.0/aopalliance-1.0.jar:/Users/jared/.m2/org/springframework/spring-context-support/2.5.6/spring-context-support-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-web/2.5.6/spring-web-2.5.6.jar:/Users/jared/.m2/org/springframework/spring-test/2.5.6/spring-test-2.5.6.jar:/Users/jared/.m2/org/openqa/selenium/client-drivers/selenium-java-client-driver/1.0-beta-2/selenium-java-client-driver-1.0-beta-2.jar:src/main/webapp/WEB-INF/:" name="java.class.path"/>
+ <property value="1.0" name="java.vm.specification.version"/>
+ <property value="32" name="sun.arch.data.model"/>
+ <property value="/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home" name="java.home"/>
+ <property value="Sun Microsystems Inc." name="java.specification.vendor"/>
+ <property value="en" name="user.language"/>
+ <property value="apple.awt.CToolkit" name="awt.toolkit"/>
+ <property value="mixed mode, sharing" name="java.vm.info"/>
+ <property value="1.5.0_16" name="java.version"/>
+ <property value="/Users/jared/Library/Java/Extensions:/Library/Java/Extensions:/System/Library/Java/Extensions:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/ext" name="java.ext.dirs"/>
+ <property value="/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/classes.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/ui.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/laf.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/sunrsasign.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/jsse.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/jce.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/charsets.jar" name="sun.boot.class.path"/>
+ <property value="Apple Inc." name="java.vendor"/>
+ <property value="/Users/jared/.m2" name="localRepository"/>
+ <property value="/" name="file.separator"/>
+ <property value="http://bugreport.apple.com/" name="java.vendor.url.bug"/>
+ <property value="little" name="sun.cpu.endian"/>
+ <property value="UnicodeLittle" name="sun.io.unicode.encoding"/>
+ <property value="1050.1.5.0_16-284" name="mrj.version"/>
+ <property value="local|*.local|169.254/16|*.169.254/16" name="socksNonProxyHosts"/>
+ <property value="local|*.local|169.254/16|*.169.254/16" name="ftp.nonProxyHosts"/>
+ <property value="" name="sun.cpu.isalist"/>
+ </properties>
+ <testcase classname="net.blitzstein.demo.testing.integration.web.ProductSeleniumTest" time="7.244" name="testSomethingSimple">
+ <error type="com.thoughtworks.selenium.SeleniumException" message="ERROR: Element //input[@name='q'] not found">com.thoughtworks.selenium.SeleniumException: ERROR: Element //input[@name='q'] not found
+ at com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(HttpCommandProcessor.java:97)
+ at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:91)
+ at com.thoughtworks.selenium.DefaultSelenium.type(DefaultSelenium.java:291)
+ at net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.testSomethingSimple(ProductSeleniumTest.java:40)
+ at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
+ at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
+ at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
+ at java.lang.reflect.Method.invoke(Method.java:585)
+ at junit.framework.TestCase.runTest(TestCase.java:168)
+ at junit.framework.TestCase.runBare(TestCase.java:134)
+ at com.thoughtworks.selenium.SeleneseTestCase.runBare(SeleneseTestCase.java:212)
+ at junit.framework.TestResult$1.protect(TestResult.java:110)
+ at junit.framework.TestResult.runProtected(TestResult.java:128)
+ at junit.framework.TestResult.run(TestResult.java:113)
+ at junit.framework.TestCase.run(TestCase.java:124)
+ at junit.framework.TestSuite.runTest(TestSuite.java:232)
+ at junit.framework.TestSuite.run(TestSuite.java:227)
+ at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:81)
+ at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:62)
+ at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140)
+ at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127)
+ at org.apache.maven.surefire.Surefire.run(Surefire.java:177)
+ at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
+ at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
+ at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
+ at java.lang.reflect.Method.invoke(Method.java:585)
+ at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345)
+ at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009)
+</error>
+ </testcase>
+</testsuite>
\ No newline at end of file
diff --git a/target/surefire-reports/net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.txt b/target/surefire-reports/net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.txt
new file mode 100644
index 0000000..fce6599
--- /dev/null
+++ b/target/surefire-reports/net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.txt
@@ -0,0 +1,35 @@
+-------------------------------------------------------------------------------
+Test set: net.blitzstein.demo.testing.integration.web.ProductSeleniumTest
+-------------------------------------------------------------------------------
+Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 7.284 sec <<< FAILURE!
+testSomethingSimple(net.blitzstein.demo.testing.integration.web.ProductSeleniumTest) Time elapsed: 7.251 sec <<< ERROR!
+com.thoughtworks.selenium.SeleniumException: ERROR: Element //input[@name='q'] not found
+ at com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(HttpCommandProcessor.java:97)
+ at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:91)
+ at com.thoughtworks.selenium.DefaultSelenium.type(DefaultSelenium.java:291)
+ at net.blitzstein.demo.testing.integration.web.ProductSeleniumTest.testSomethingSimple(ProductSeleniumTest.java:40)
+ at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
+ at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
+ at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
+ at java.lang.reflect.Method.invoke(Method.java:585)
+ at junit.framework.TestCase.runTest(TestCase.java:168)
+ at junit.framework.TestCase.runBare(TestCase.java:134)
+ at com.thoughtworks.selenium.SeleneseTestCase.runBare(SeleneseTestCase.java:212)
+ at junit.framework.TestResult$1.protect(TestResult.java:110)
+ at junit.framework.TestResult.runProtected(TestResult.java:128)
+ at junit.framework.TestResult.run(TestResult.java:113)
+ at junit.framework.TestCase.run(TestCase.java:124)
+ at junit.framework.TestSuite.runTest(TestSuite.java:232)
+ at junit.framework.TestSuite.run(TestSuite.java:227)
+ at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:81)
+ at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:62)
+ at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140)
+ at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127)
+ at org.apache.maven.surefire.Surefire.run(Surefire.java:177)
+ at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
+ at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
+ at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
+ at java.lang.reflect.Method.invoke(Method.java:585)
+ at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345)
+ at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009)
+
diff --git a/target/test-classes/net/blitzstein/demo/testing/integration/web/ProductSeleniumTest.class b/target/test-classes/net/blitzstein/demo/testing/integration/web/ProductSeleniumTest.class
new file mode 100644
index 0000000..f5917b8
Binary files /dev/null and b/target/test-classes/net/blitzstein/demo/testing/integration/web/ProductSeleniumTest.class differ
diff --git a/target/testing-demo.war b/target/testing-demo.war
new file mode 100644
index 0000000..4bcd442
Binary files /dev/null and b/target/testing-demo.war differ
diff --git a/target/testing-demo/WEB-INF/classes/display.properties b/target/testing-demo/WEB-INF/classes/display.properties
new file mode 100644
index 0000000..57ed665
--- /dev/null
+++ b/target/testing-demo/WEB-INF/classes/display.properties
@@ -0,0 +1,3 @@
+# To change this template, choose Tools | Templates
+# and open the template in the editor.
+
diff --git a/target/testing-demo/WEB-INF/classes/net/blitzstein/demo/testing/domain/Product.class b/target/testing-demo/WEB-INF/classes/net/blitzstein/demo/testing/domain/Product.class
new file mode 100644
index 0000000..fe2818b
Binary files /dev/null and b/target/testing-demo/WEB-INF/classes/net/blitzstein/demo/testing/domain/Product.class differ
diff --git a/target/testing-demo/WEB-INF/classes/net/blitzstein/demo/testing/web/ProductController.class b/target/testing-demo/WEB-INF/classes/net/blitzstein/demo/testing/web/ProductController.class
new file mode 100644
index 0000000..533eec0
Binary files /dev/null and b/target/testing-demo/WEB-INF/classes/net/blitzstein/demo/testing/web/ProductController.class differ
diff --git a/target/testing-demo/WEB-INF/lib/aopalliance-1.0.jar b/target/testing-demo/WEB-INF/lib/aopalliance-1.0.jar
new file mode 100644
index 0000000..578b1a0
Binary files /dev/null and b/target/testing-demo/WEB-INF/lib/aopalliance-1.0.jar differ
diff --git a/target/testing-demo/WEB-INF/lib/commons-logging-1.1.1.jar b/target/testing-demo/WEB-INF/lib/commons-logging-1.1.1.jar
new file mode 100644
index 0000000..1deef14
Binary files /dev/null and b/target/testing-demo/WEB-INF/lib/commons-logging-1.1.1.jar differ
diff --git a/target/testing-demo/WEB-INF/lib/spring-beans-2.5.6.jar b/target/testing-demo/WEB-INF/lib/spring-beans-2.5.6.jar
new file mode 100644
index 0000000..3f306b6
Binary files /dev/null and b/target/testing-demo/WEB-INF/lib/spring-beans-2.5.6.jar differ
diff --git a/target/testing-demo/WEB-INF/lib/spring-context-2.5.6.jar b/target/testing-demo/WEB-INF/lib/spring-context-2.5.6.jar
new file mode 100644
index 0000000..29fabcc
Binary files /dev/null and b/target/testing-demo/WEB-INF/lib/spring-context-2.5.6.jar differ
diff --git a/target/testing-demo/WEB-INF/lib/spring-context-support-2.5.6.jar b/target/testing-demo/WEB-INF/lib/spring-context-support-2.5.6.jar
new file mode 100644
index 0000000..2927c6e
Binary files /dev/null and b/target/testing-demo/WEB-INF/lib/spring-context-support-2.5.6.jar differ
diff --git a/target/testing-demo/WEB-INF/lib/spring-core-2.5.6.jar b/target/testing-demo/WEB-INF/lib/spring-core-2.5.6.jar
new file mode 100644
index 0000000..aafa336
Binary files /dev/null and b/target/testing-demo/WEB-INF/lib/spring-core-2.5.6.jar differ
diff --git a/target/testing-demo/WEB-INF/lib/spring-test-2.5.6.jar b/target/testing-demo/WEB-INF/lib/spring-test-2.5.6.jar
new file mode 100644
index 0000000..2589840
Binary files /dev/null and b/target/testing-demo/WEB-INF/lib/spring-test-2.5.6.jar differ
diff --git a/target/testing-demo/WEB-INF/lib/spring-web-2.5.6.jar b/target/testing-demo/WEB-INF/lib/spring-web-2.5.6.jar
new file mode 100644
index 0000000..432e8f0
Binary files /dev/null and b/target/testing-demo/WEB-INF/lib/spring-web-2.5.6.jar differ
diff --git a/target/testing-demo/WEB-INF/lib/spring-webmvc-2.5.6.jar b/target/testing-demo/WEB-INF/lib/spring-webmvc-2.5.6.jar
new file mode 100644
index 0000000..613f595
Binary files /dev/null and b/target/testing-demo/WEB-INF/lib/spring-webmvc-2.5.6.jar differ
diff --git a/target/testing-demo/WEB-INF/testingdemo-servlet.xml b/target/testing-demo/WEB-INF/testingdemo-servlet.xml
new file mode 100644
index 0000000..37b710d
--- /dev/null
+++ b/target/testing-demo/WEB-INF/testingdemo-servlet.xml
@@ -0,0 +1,231 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xsi:schemaLocation="
+ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
+ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
+ http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
+ http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
+ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
+
+ <context:component-scan base-package="net.blitzstein.demo.testing.web"/>
+ <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
+
+
+ <bean id="messageSource"
+ class="org.springframework.context.support.ResourceBundleMessageSource">
+ <property name="basenames">
+ <list>
+ <value>display</value>
+ </list>
+ </property>
+ </bean>
+
+ <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
+ <property name="mappings">
+ <value>
+ /product/*=productController
+ </value>
+ </property>
+ </bean>
+
+ <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
+ <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
+ <property name="prefix" value="/WEB-INF/views/"/>
+ <property name="suffix" value=".jsp"/>
+ <property name="order" value="2" />
+ </bean>
+
+ <bean id="productController" class="net.blitzstein.demo.testing.web.ProductController">
+
+ </bean>
+
+
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="1" />
+ <property name="name" value="eu" />
+ <property name="manufacturer" value="ullamcorper," />
+ <property name="price" value="254" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="2" />
+ <property name="name" value="eget" />
+ <property name="manufacturer" value="rutrum" />
+ <property name="price" value="605" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="3" />
+ <property name="name" value="vulputate dui," />
+ <property name="manufacturer" value="eu" />
+ <property name="price" value="325" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="4" />
+ <property name="name" value="diam. Pellentesque habitant" />
+ <property name="manufacturer" value="tellus." />
+ <property name="price" value="559" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="5" />
+ <property name="name" value="eros" />
+ <property name="manufacturer" value="sagittis. Nullam" />
+ <property name="price" value="435" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="6" />
+ <property name="name" value="nibh vulputate" />
+ <property name="manufacturer" value="suscipit," />
+ <property name="price" value="667" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="7" />
+ <property name="name" value="dignissim magna a" />
+ <property name="manufacturer" value="nunc." />
+ <property name="price" value="413" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="8" />
+ <property name="name" value="massa. Integer" />
+ <property name="manufacturer" value="ultrices sit" />
+ <property name="price" value="728" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="9" />
+ <property name="name" value="convallis in," />
+ <property name="manufacturer" value="vel," />
+ <property name="price" value="530" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="10" />
+ <property name="name" value="magnis dis parturient" />
+ <property name="manufacturer" value="vitae, orci." />
+ <property name="price" value="954" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="11" />
+ <property name="name" value="quis," />
+ <property name="manufacturer" value="fringilla" />
+ <property name="price" value="167" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="12" />
+ <property name="name" value="non dui" />
+ <property name="manufacturer" value="dui, in" />
+ <property name="price" value="824" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="13" />
+ <property name="name" value="dignissim" />
+ <property name="manufacturer" value="luctus. Curabitur" />
+ <property name="price" value="409" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="14" />
+ <property name="name" value="amet, consectetuer adipiscing" />
+ <property name="manufacturer" value="mi eleifend" />
+ <property name="price" value="532" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="15" />
+ <property name="name" value="vitae," />
+ <property name="manufacturer" value="lobortis" />
+ <property name="price" value="973" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="16" />
+ <property name="name" value="ut, nulla. Cras" />
+ <property name="manufacturer" value="orci," />
+ <property name="price" value="530" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="17" />
+ <property name="name" value="Curabitur" />
+ <property name="manufacturer" value="urna. Nullam" />
+ <property name="price" value="430" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="18" />
+ <property name="name" value="eros. Proin ultrices." />
+ <property name="manufacturer" value="eget magna." />
+ <property name="price" value="676" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="19" />
+ <property name="name" value="fermentum vel," />
+ <property name="manufacturer" value="porttitor" />
+ <property name="price" value="528" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="20" />
+ <property name="name" value="sem. Pellentesque" />
+ <property name="manufacturer" value="eu eros." />
+ <property name="price" value="658" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="21" />
+ <property name="name" value="sodales" />
+ <property name="manufacturer" value="Quisque varius." />
+ <property name="price" value="87" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="22" />
+ <property name="name" value="torquent per conubia" />
+ <property name="manufacturer" value="diam" />
+ <property name="price" value="722" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="23" />
+ <property name="name" value="risus. Donec nibh" />
+ <property name="manufacturer" value="Proin" />
+ <property name="price" value="872" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="24" />
+ <property name="name" value="malesuada vel," />
+ <property name="manufacturer" value="Morbi vehicula." />
+ <property name="price" value="538" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="25" />
+ <property name="name" value="Ut semper" />
+ <property name="manufacturer" value="pretium" />
+ <property name="price" value="661" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="26" />
+ <property name="name" value="urna suscipit nonummy." />
+ <property name="manufacturer" value="Ut" />
+ <property name="price" value="370" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="27" />
+ <property name="name" value="mattis" />
+ <property name="manufacturer" value="eget metus." />
+ <property name="price" value="883" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="28" />
+ <property name="name" value="arcu et pede." />
+ <property name="manufacturer" value="mauris" />
+ <property name="price" value="337" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="29" />
+ <property name="name" value="ut, molestie in," />
+ <property name="manufacturer" value="erat. Sed" />
+ <property name="price" value="119" />
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="30" />
+ <property name="name" value="sagittis. Nullam vitae" />
+ <property name="manufacturer" value="eget massa." />
+ <property name="price" value="80" />
+ </bean>
+
+
+</beans>
\ No newline at end of file
diff --git a/target/testing-demo/WEB-INF/views/product/create.jsp b/target/testing-demo/WEB-INF/views/product/create.jsp
new file mode 100644
index 0000000..5c81a19
--- /dev/null
+++ b/target/testing-demo/WEB-INF/views/product/create.jsp
@@ -0,0 +1,13 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
+ <title>
+ Edit
+ </title>
+ </head>
+ <body>
+ <h1>Edit</h1>
+ </body>
+</html>
diff --git a/target/testing-demo/WEB-INF/views/product/edit.jsp b/target/testing-demo/WEB-INF/views/product/edit.jsp
new file mode 100644
index 0000000..c05e513
--- /dev/null
+++ b/target/testing-demo/WEB-INF/views/product/edit.jsp
@@ -0,0 +1,38 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
+ <title>
+ Edit
+ </title>
+ </head>
+ <body>
+ <h1>Edit</h1>
+
+ <form:form commandName="product" action="${pageContext.request.contextPath}/product/save.htm">
+ <form:hidden path="id" />
+ <table>
+ <tr>
+ <td>Name:</td>
+ <td><form:input path="name" /></td>
+ </tr>
+ <tr>
+ <td>Manufacturer:</td>
+ <td><form:input path="manufacturer" /></td>
+ </tr>
+ <tr>
+ <td>Price:</td>
+ <td><form:input path="price" /></td>
+ </tr>
+ <tr>
+ <td colspan="2">
+ <input type="submit" value="Save Changes" />
+ <a href="${pageContext.request.contextPath}/product/view.htm?id=${product.id}">Cancel</a>
+ </td>
+ </tr>
+ </table>
+ </form:form>
+ </body>
+</html>
diff --git a/target/testing-demo/WEB-INF/views/product/index.jsp b/target/testing-demo/WEB-INF/views/product/index.jsp
new file mode 100644
index 0000000..f676002
--- /dev/null
+++ b/target/testing-demo/WEB-INF/views/product/index.jsp
@@ -0,0 +1,47 @@
+<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
+<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
+ <title>
+ Index
+ </title>
+ </head>
+ <body>
+ <h1>Index</h1>
+
+ <table>
+ <tr>
+ <th>Id</th>
+ <th>Name</th>
+ <th>Manufacturer</th>
+ <th>Price</th>
+ <th>Action</th>
+ </tr>
+ <c:forEach var="product" items="${products}">
+ <tr>
+ <td><c:out value="${product.id}" /></td>
+ <td><c:out value="${product.name}" /></td>
+ <td><c:out value="${product.manufacturer}" /></td>
+ <td><fmt:formatNumber value="${product.price}" type="currency"/></td>
+ <td>
+ <a href="${pageContext.request.contextPath}/product/view.htm?id=${product.id}">View</a>
+ <a href="${pageContext.request.contextPath}/product/edit.htm?id=${product.id}">Edit</a>
+ <a href="${pageContext.request.contextPath}/product/delete.htm?id=${product.id}">Delete</a>
+ </td>
+
+
+
+ </tr>
+ </c:forEach>
+ </table>
+
+
+ <a title="Create a new product" href="${pageContext.request.contextPath}/product/create.htm">Create</a>
+ </body>
+</html>
diff --git a/target/testing-demo/WEB-INF/views/product/view.jsp b/target/testing-demo/WEB-INF/views/product/view.jsp
new file mode 100644
index 0000000..ad6cac3
--- /dev/null
+++ b/target/testing-demo/WEB-INF/views/product/view.jsp
@@ -0,0 +1,38 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
+ <title>
+ View
+ </title>
+ </head>
+ <body>
+ <h1>View</h1>
+
+ ${sessionScope.message}
+ <c:remove var="message" scope="session"/>
+
+ <div>
+ <span>id: </span> ${product.id}
+ </div>
+ <div>
+ <span>name: </span> ${product.name}
+ </div>
+ <div>
+ <span>manufactuerer: </span> ${product.manufacturer}
+ </div>
+ <div>
+ <span>price: </span> ${product.price}
+ </div>
+
+ <div>
+ <a href="${pageContext.request.contextPath}/product/index.htm">Index</a>
+ <a href="${pageContext.request.contextPath}/product/edit.htm?id=${product.id}">Edit</a>
+ <a href="${pageContext.request.contextPath}/product/delete.htm?id=${product.id}">Delete</a>
+ </div>
+ </body>
+</html>
diff --git a/target/testing-demo/WEB-INF/web.xml b/target/testing-demo/WEB-INF/web.xml
new file mode 100644
index 0000000..629d65d
--- /dev/null
+++ b/target/testing-demo/WEB-INF/web.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<web-app id="MessengerWebApp" version="2.4"
+ xmlns="http://java.sun.com/xml/ns/j2ee"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
+ <display-name>Archetype Created Web Application</display-name>
+
+<context-param>
+ <param-name>contextConfigLocation</param-name>
+ <param-value>/WEB-INF/testingdemo-servlet.xml</param-value>
+ </context-param>
+
+ <servlet>
+ <servlet-name>testingdemo</servlet-name>
+ <servlet-class>
+ org.springframework.web.servlet.DispatcherServlet
+ </servlet-class>
+ <load-on-startup>1</load-on-startup>
+ </servlet>
+
+ <servlet-mapping>
+ <servlet-name>testingdemo</servlet-name>
+ <url-pattern>*.htm</url-pattern>
+ </servlet-mapping>
+
+ <listener>
+ <listener-class>
+ org.springframework.web.context.ContextLoaderListener
+ </listener-class>
+ </listener>
+</web-app>
diff --git a/target/testing-demo/index.jsp b/target/testing-demo/index.jsp
new file mode 100644
index 0000000..9e9d551
--- /dev/null
+++ b/target/testing-demo/index.jsp
@@ -0,0 +1,2 @@
+<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
+<c:redirect url="/product/index.htm"/>
diff --git a/target/war/work/webapp-cache.xml b/target/war/work/webapp-cache.xml
new file mode 100644
index 0000000..d4a2a6c
--- /dev/null
+++ b/target/war/work/webapp-cache.xml
@@ -0,0 +1,82 @@
+<webapp-structure>
+ <registeredFiles>
+ <entry>
+ <string>currentBuild</string>
+ <path-set>
+ <pathsSet class="linked-hash-set">
+ <string>index.jsp</string>
+ <string>WEB-INF/testingdemo-servlet.xml</string>
+ <string>WEB-INF/views/product/create.jsp</string>
+ <string>WEB-INF/views/product/edit.jsp</string>
+ <string>WEB-INF/views/product/index.jsp</string>
+ <string>WEB-INF/views/product/view.jsp</string>
+ <string>WEB-INF/web.xml</string>
+ <string>WEB-INF/classes/display.properties</string>
+ <string>WEB-INF/classes/net/blitzstein/demo/testing/domain/Product.class</string>
+ <string>WEB-INF/classes/net/blitzstein/demo/testing/web/ProductController.class</string>
+ <string>WEB-INF/lib/spring-webmvc-2.5.6.jar</string>
+ <string>WEB-INF/lib/commons-logging-1.1.1.jar</string>
+ <string>WEB-INF/lib/spring-beans-2.5.6.jar</string>
+ <string>WEB-INF/lib/spring-core-2.5.6.jar</string>
+ <string>WEB-INF/lib/spring-context-2.5.6.jar</string>
+ <string>WEB-INF/lib/aopalliance-1.0.jar</string>
+ <string>WEB-INF/lib/spring-context-support-2.5.6.jar</string>
+ <string>WEB-INF/lib/spring-web-2.5.6.jar</string>
+ <string>WEB-INF/lib/spring-test-2.5.6.jar</string>
+ </pathsSet>
+ </path-set>
+ </entry>
+ </registeredFiles>
+ <dependenciesInfo>
+ <org.apache.maven.plugin.war.util.DependencyInfo>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.4</version>
+ <type>jar</type>
+ <scope>test</scope>
+ <exclusions/>
+ <optional>false</optional>
+ <modelEncoding>UTF-8</modelEncoding>
+ </dependency>
+ </org.apache.maven.plugin.war.util.DependencyInfo>
+ <org.apache.maven.plugin.war.util.DependencyInfo>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-webmvc</artifactId>
+ <version>2.5.6</version>
+ <type>jar</type>
+ <scope>compile</scope>
+ <exclusions/>
+ <optional>false</optional>
+ <modelEncoding>UTF-8</modelEncoding>
+ </dependency>
+ <targetFileName>spring-webmvc-2.5.6.jar</targetFileName>
+ </org.apache.maven.plugin.war.util.DependencyInfo>
+ <org.apache.maven.plugin.war.util.DependencyInfo>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
+ <version>2.5.6</version>
+ <type>jar</type>
+ <scope>compile</scope>
+ <exclusions/>
+ <optional>false</optional>
+ <modelEncoding>UTF-8</modelEncoding>
+ </dependency>
+ <targetFileName>spring-test-2.5.6.jar</targetFileName>
+ </org.apache.maven.plugin.war.util.DependencyInfo>
+ <org.apache.maven.plugin.war.util.DependencyInfo>
+ <dependency>
+ <groupId>org.openqa.selenium.client-drivers</groupId>
+ <artifactId>selenium-java-client-driver</artifactId>
+ <version>1.0-beta-2</version>
+ <type>jar</type>
+ <scope>test</scope>
+ <exclusions/>
+ <optional>false</optional>
+ <modelEncoding>UTF-8</modelEncoding>
+ </dependency>
+ </org.apache.maven.plugin.war.util.DependencyInfo>
+ </dependenciesInfo>
+</webapp-structure>
\ No newline at end of file
diff --git a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/edit_jsp.class b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/edit_jsp.class
new file mode 100644
index 0000000..abe9071
Binary files /dev/null and b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/edit_jsp.class differ
diff --git a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/edit_jsp.java b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/edit_jsp.java
new file mode 100644
index 0000000..f8cbcf7
--- /dev/null
+++ b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/edit_jsp.java
@@ -0,0 +1,267 @@
+package org.apache.jsp.WEB_002dINF.views.product;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+import javax.servlet.jsp.*;
+
+public final class edit_jsp extends org.apache.jasper.runtime.HttpJspBase
+ implements org.apache.jasper.runtime.JspSourceDependent {
+
+ private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
+
+ private static java.util.Vector _jspx_dependants;
+
+ private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_form_form_commandName_action;
+ private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_form_hidden_path_nobody;
+ private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_form_input_path_nobody;
+
+ private org.apache.jasper.runtime.ResourceInjector _jspx_resourceInjector;
+
+ public Object getDependants() {
+ return _jspx_dependants;
+ }
+
+ public void _jspInit() {
+ _jspx_tagPool_form_form_commandName_action = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
+ _jspx_tagPool_form_hidden_path_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
+ _jspx_tagPool_form_input_path_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
+ }
+
+ public void _jspDestroy() {
+ _jspx_tagPool_form_form_commandName_action.release();
+ _jspx_tagPool_form_hidden_path_nobody.release();
+ _jspx_tagPool_form_input_path_nobody.release();
+ }
+
+ public void _jspService(HttpServletRequest request, HttpServletResponse response)
+ throws java.io.IOException, ServletException {
+
+ PageContext pageContext = null;
+ HttpSession session = null;
+ ServletContext application = null;
+ ServletConfig config = null;
+ JspWriter out = null;
+ Object page = this;
+ JspWriter _jspx_out = null;
+ PageContext _jspx_page_context = null;
+
+ try {
+ response.setContentType("text/html");
+ pageContext = _jspxFactory.getPageContext(this, request, response,
+ null, true, 8192, true);
+ _jspx_page_context = pageContext;
+ application = pageContext.getServletContext();
+ config = pageContext.getServletConfig();
+ session = pageContext.getSession();
+ out = pageContext.getOut();
+ _jspx_out = out;
+ _jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
+
+ out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n");
+ out.write("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
+ out.write("\n");
+ out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
+ out.write("\t<head>\n");
+ out.write("\t\t<meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />\n");
+ out.write("\t\t<title>\n");
+ out.write("\t\t\tEdit\n");
+ out.write("\t\t</title>\n");
+ out.write("\t</head>\n");
+ out.write("\t<body>\n");
+ out.write(" <h1>Edit</h1>\n");
+ out.write("\n");
+ out.write(" ");
+ if (_jspx_meth_form_form_0(_jspx_page_context))
+ return;
+ out.write("\n");
+ out.write("\t</body>\n");
+ out.write("</html>\n");
+ } catch (Throwable t) {
+ if (!(t instanceof SkipPageException)){
+ out = _jspx_out;
+ if (out != null && out.getBufferSize() != 0)
+ out.clearBuffer();
+ if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
+ }
+ } finally {
+ _jspxFactory.releasePageContext(_jspx_page_context);
+ }
+ }
+
+ private boolean _jspx_meth_form_form_0(PageContext _jspx_page_context)
+ throws Throwable {
+ PageContext pageContext = _jspx_page_context;
+ JspWriter out = _jspx_page_context.getOut();
+ // form:form
+ org.springframework.web.servlet.tags.form.FormTag _jspx_th_form_form_0 = (org.springframework.web.servlet.tags.form.FormTag) _jspx_tagPool_form_form_commandName_action.get(org.springframework.web.servlet.tags.form.FormTag.class);
+ _jspx_th_form_form_0.setPageContext(_jspx_page_context);
+ _jspx_th_form_form_0.setParent(null);
+ _jspx_th_form_form_0.setCommandName("product");
+ _jspx_th_form_form_0.setAction((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}/product/save.htm", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ int[] _jspx_push_body_count_form_form_0 = new int[] { 0 };
+ try {
+ int _jspx_eval_form_form_0 = _jspx_th_form_form_0.doStartTag();
+ if (_jspx_eval_form_form_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
+ do {
+ out.write("\n");
+ out.write(" ");
+ if (_jspx_meth_form_hidden_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_form_form_0, _jspx_page_context, _jspx_push_body_count_form_form_0))
+ return true;
+ out.write("\n");
+ out.write(" <table>\n");
+ out.write(" <tr>\n");
+ out.write(" <td>Name:</td>\n");
+ out.write(" <td>");
+ if (_jspx_meth_form_input_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_form_form_0, _jspx_page_context, _jspx_push_body_count_form_form_0))
+ return true;
+ out.write("</td>\n");
+ out.write(" </tr>\n");
+ out.write(" <tr>\n");
+ out.write(" <td>Manufacturer:</td>\n");
+ out.write(" <td>");
+ if (_jspx_meth_form_input_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_form_form_0, _jspx_page_context, _jspx_push_body_count_form_form_0))
+ return true;
+ out.write("</td>\n");
+ out.write(" </tr>\n");
+ out.write(" <tr>\n");
+ out.write(" <td>Price:</td>\n");
+ out.write(" <td>");
+ if (_jspx_meth_form_input_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_form_form_0, _jspx_page_context, _jspx_push_body_count_form_form_0))
+ return true;
+ out.write("</td>\n");
+ out.write(" </tr>\n");
+ out.write(" <tr>\n");
+ out.write(" <td colspan=\"2\">\n");
+ out.write(" <input type=\"submit\" value=\"Save Changes\" />\n");
+ out.write(" <a href=\"");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("/product/view.htm?id=");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\">Cancel</a>\n");
+ out.write(" </td>\n");
+ out.write(" </tr>\n");
+ out.write(" </table>\n");
+ out.write(" ");
+ int evalDoAfterBody = _jspx_th_form_form_0.doAfterBody();
+ if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
+ break;
+ } while (true);
+ }
+ if (_jspx_th_form_form_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
+ return true;
+ }
+ } catch (Throwable _jspx_exception) {
+ while (_jspx_push_body_count_form_form_0[0]-- > 0)
+ out = _jspx_page_context.popBody();
+ _jspx_th_form_form_0.doCatch(_jspx_exception);
+ } finally {
+ _jspx_th_form_form_0.doFinally();
+ _jspx_tagPool_form_form_commandName_action.reuse(_jspx_th_form_form_0);
+ }
+ return false;
+ }
+
+ private boolean _jspx_meth_form_hidden_0(javax.servlet.jsp.tagext.JspTag _jspx_th_form_form_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_form_form_0)
+ throws Throwable {
+ PageContext pageContext = _jspx_page_context;
+ JspWriter out = _jspx_page_context.getOut();
+ // form:hidden
+ org.springframework.web.servlet.tags.form.HiddenInputTag _jspx_th_form_hidden_0 = (org.springframework.web.servlet.tags.form.HiddenInputTag) _jspx_tagPool_form_hidden_path_nobody.get(org.springframework.web.servlet.tags.form.HiddenInputTag.class);
+ _jspx_th_form_hidden_0.setPageContext(_jspx_page_context);
+ _jspx_th_form_hidden_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_form_0);
+ _jspx_th_form_hidden_0.setPath("id");
+ int[] _jspx_push_body_count_form_hidden_0 = new int[] { 0 };
+ try {
+ int _jspx_eval_form_hidden_0 = _jspx_th_form_hidden_0.doStartTag();
+ if (_jspx_th_form_hidden_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
+ return true;
+ }
+ } catch (Throwable _jspx_exception) {
+ while (_jspx_push_body_count_form_hidden_0[0]-- > 0)
+ out = _jspx_page_context.popBody();
+ _jspx_th_form_hidden_0.doCatch(_jspx_exception);
+ } finally {
+ _jspx_th_form_hidden_0.doFinally();
+ _jspx_tagPool_form_hidden_path_nobody.reuse(_jspx_th_form_hidden_0);
+ }
+ return false;
+ }
+
+ private boolean _jspx_meth_form_input_0(javax.servlet.jsp.tagext.JspTag _jspx_th_form_form_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_form_form_0)
+ throws Throwable {
+ PageContext pageContext = _jspx_page_context;
+ JspWriter out = _jspx_page_context.getOut();
+ // form:input
+ org.springframework.web.servlet.tags.form.InputTag _jspx_th_form_input_0 = (org.springframework.web.servlet.tags.form.InputTag) _jspx_tagPool_form_input_path_nobody.get(org.springframework.web.servlet.tags.form.InputTag.class);
+ _jspx_th_form_input_0.setPageContext(_jspx_page_context);
+ _jspx_th_form_input_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_form_0);
+ _jspx_th_form_input_0.setPath("name");
+ int[] _jspx_push_body_count_form_input_0 = new int[] { 0 };
+ try {
+ int _jspx_eval_form_input_0 = _jspx_th_form_input_0.doStartTag();
+ if (_jspx_th_form_input_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
+ return true;
+ }
+ } catch (Throwable _jspx_exception) {
+ while (_jspx_push_body_count_form_input_0[0]-- > 0)
+ out = _jspx_page_context.popBody();
+ _jspx_th_form_input_0.doCatch(_jspx_exception);
+ } finally {
+ _jspx_th_form_input_0.doFinally();
+ _jspx_tagPool_form_input_path_nobody.reuse(_jspx_th_form_input_0);
+ }
+ return false;
+ }
+
+ private boolean _jspx_meth_form_input_1(javax.servlet.jsp.tagext.JspTag _jspx_th_form_form_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_form_form_0)
+ throws Throwable {
+ PageContext pageContext = _jspx_page_context;
+ JspWriter out = _jspx_page_context.getOut();
+ // form:input
+ org.springframework.web.servlet.tags.form.InputTag _jspx_th_form_input_1 = (org.springframework.web.servlet.tags.form.InputTag) _jspx_tagPool_form_input_path_nobody.get(org.springframework.web.servlet.tags.form.InputTag.class);
+ _jspx_th_form_input_1.setPageContext(_jspx_page_context);
+ _jspx_th_form_input_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_form_0);
+ _jspx_th_form_input_1.setPath("manufacturer");
+ int[] _jspx_push_body_count_form_input_1 = new int[] { 0 };
+ try {
+ int _jspx_eval_form_input_1 = _jspx_th_form_input_1.doStartTag();
+ if (_jspx_th_form_input_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
+ return true;
+ }
+ } catch (Throwable _jspx_exception) {
+ while (_jspx_push_body_count_form_input_1[0]-- > 0)
+ out = _jspx_page_context.popBody();
+ _jspx_th_form_input_1.doCatch(_jspx_exception);
+ } finally {
+ _jspx_th_form_input_1.doFinally();
+ _jspx_tagPool_form_input_path_nobody.reuse(_jspx_th_form_input_1);
+ }
+ return false;
+ }
+
+ private boolean _jspx_meth_form_input_2(javax.servlet.jsp.tagext.JspTag _jspx_th_form_form_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_form_form_0)
+ throws Throwable {
+ PageContext pageContext = _jspx_page_context;
+ JspWriter out = _jspx_page_context.getOut();
+ // form:input
+ org.springframework.web.servlet.tags.form.InputTag _jspx_th_form_input_2 = (org.springframework.web.servlet.tags.form.InputTag) _jspx_tagPool_form_input_path_nobody.get(org.springframework.web.servlet.tags.form.InputTag.class);
+ _jspx_th_form_input_2.setPageContext(_jspx_page_context);
+ _jspx_th_form_input_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_form_0);
+ _jspx_th_form_input_2.setPath("price");
+ int[] _jspx_push_body_count_form_input_2 = new int[] { 0 };
+ try {
+ int _jspx_eval_form_input_2 = _jspx_th_form_input_2.doStartTag();
+ if (_jspx_th_form_input_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
+ return true;
+ }
+ } catch (Throwable _jspx_exception) {
+ while (_jspx_push_body_count_form_input_2[0]-- > 0)
+ out = _jspx_page_context.popBody();
+ _jspx_th_form_input_2.doCatch(_jspx_exception);
+ } finally {
+ _jspx_th_form_input_2.doFinally();
+ _jspx_tagPool_form_input_path_nobody.reuse(_jspx_th_form_input_2);
+ }
+ return false;
+ }
+}
diff --git a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/index_jsp.class b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/index_jsp.class
new file mode 100644
index 0000000..23e8cf5
Binary files /dev/null and b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/index_jsp.class differ
diff --git a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/index_jsp.java b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/index_jsp.java
new file mode 100644
index 0000000..e0b3a0d
--- /dev/null
+++ b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/index_jsp.java
@@ -0,0 +1,255 @@
+package org.apache.jsp.WEB_002dINF.views.product;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+import javax.servlet.jsp.*;
+
+public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
+ implements org.apache.jasper.runtime.JspSourceDependent {
+
+ private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
+
+ private static java.util.Vector _jspx_dependants;
+
+ private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_forEach_var_items;
+ private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_out_value_nobody;
+ private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_fmt_formatNumber_value_type_nobody;
+
+ private org.apache.jasper.runtime.ResourceInjector _jspx_resourceInjector;
+
+ public Object getDependants() {
+ return _jspx_dependants;
+ }
+
+ public void _jspInit() {
+ _jspx_tagPool_c_forEach_var_items = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
+ _jspx_tagPool_c_out_value_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
+ _jspx_tagPool_fmt_formatNumber_value_type_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
+ }
+
+ public void _jspDestroy() {
+ _jspx_tagPool_c_forEach_var_items.release();
+ _jspx_tagPool_c_out_value_nobody.release();
+ _jspx_tagPool_fmt_formatNumber_value_type_nobody.release();
+ }
+
+ public void _jspService(HttpServletRequest request, HttpServletResponse response)
+ throws java.io.IOException, ServletException {
+
+ PageContext pageContext = null;
+ HttpSession session = null;
+ ServletContext application = null;
+ ServletConfig config = null;
+ JspWriter out = null;
+ Object page = this;
+ JspWriter _jspx_out = null;
+ PageContext _jspx_page_context = null;
+
+ try {
+ response.setContentType("text/html");
+ pageContext = _jspxFactory.getPageContext(this, request, response,
+ null, true, 8192, true);
+ _jspx_page_context = pageContext;
+ application = pageContext.getServletContext();
+ config = pageContext.getServletConfig();
+ session = pageContext.getSession();
+ out = pageContext.getOut();
+ _jspx_out = out;
+ _jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
+
+ out.write("\n");
+ out.write("\n");
+ out.write("\n");
+ out.write("\n");
+ out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n");
+ out.write("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
+ out.write("\n");
+ out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
+ out.write("\t<head>\n");
+ out.write("\t\t<meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />\n");
+ out.write("\t\t<title>\n");
+ out.write("\t\t\tIndex\n");
+ out.write("\t\t</title>\n");
+ out.write("\t</head>\n");
+ out.write("\t<body>\n");
+ out.write(" <h1>Index</h1>\n");
+ out.write("\n");
+ out.write(" <table>\n");
+ out.write(" <tr>\n");
+ out.write(" <th>Id</th>\n");
+ out.write(" <th>Name</th>\n");
+ out.write(" <th>Manufacturer</th>\n");
+ out.write(" <th>Price</th>\n");
+ out.write(" <th>Action</th>\n");
+ out.write(" </tr>\n");
+ out.write(" ");
+ if (_jspx_meth_c_forEach_0(_jspx_page_context))
+ return;
+ out.write("\n");
+ out.write(" </table>\n");
+ out.write("\n");
+ out.write("\n");
+ out.write(" <a title=\"Create a new product\" href=\"");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("/product/create.htm\">Create</a>\n");
+ out.write("\t</body>\n");
+ out.write("</html>\n");
+ } catch (Throwable t) {
+ if (!(t instanceof SkipPageException)){
+ out = _jspx_out;
+ if (out != null && out.getBufferSize() != 0)
+ out.clearBuffer();
+ if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
+ }
+ } finally {
+ _jspxFactory.releasePageContext(_jspx_page_context);
+ }
+ }
+
+ private boolean _jspx_meth_c_forEach_0(PageContext _jspx_page_context)
+ throws Throwable {
+ PageContext pageContext = _jspx_page_context;
+ JspWriter out = _jspx_page_context.getOut();
+ // c:forEach
+ org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_0 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
+ _jspx_th_c_forEach_0.setPageContext(_jspx_page_context);
+ _jspx_th_c_forEach_0.setParent(null);
+ _jspx_th_c_forEach_0.setVar("product");
+ _jspx_th_c_forEach_0.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${products}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
+ int[] _jspx_push_body_count_c_forEach_0 = new int[] { 0 };
+ try {
+ int _jspx_eval_c_forEach_0 = _jspx_th_c_forEach_0.doStartTag();
+ if (_jspx_eval_c_forEach_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
+ do {
+ out.write("\n");
+ out.write(" <tr>\n");
+ out.write(" <td>");
+ if (_jspx_meth_c_out_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_0, _jspx_page_context, _jspx_push_body_count_c_forEach_0))
+ return true;
+ out.write("</td>\n");
+ out.write(" <td>");
+ if (_jspx_meth_c_out_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_0, _jspx_page_context, _jspx_push_body_count_c_forEach_0))
+ return true;
+ out.write("</td>\n");
+ out.write(" <td>");
+ if (_jspx_meth_c_out_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_0, _jspx_page_context, _jspx_push_body_count_c_forEach_0))
+ return true;
+ out.write("</td>\n");
+ out.write(" <td>");
+ if (_jspx_meth_fmt_formatNumber_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_0, _jspx_page_context, _jspx_push_body_count_c_forEach_0))
+ return true;
+ out.write("</td>\n");
+ out.write(" <td>\n");
+ out.write(" <a href=\"");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("/product/view.htm?id=");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\">View</a>\n");
+ out.write(" <a href=\"");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("/product/edit.htm?id=");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\">Edit</a>\n");
+ out.write(" <a href=\"");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("/product/delete.htm?id=");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\">Delete</a>\n");
+ out.write(" </td>\n");
+ out.write("\n");
+ out.write("\n");
+ out.write(" \n");
+ out.write(" </tr>\n");
+ out.write(" ");
+ int evalDoAfterBody = _jspx_th_c_forEach_0.doAfterBody();
+ if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
+ break;
+ } while (true);
+ }
+ if (_jspx_th_c_forEach_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
+ return true;
+ }
+ } catch (Throwable _jspx_exception) {
+ while (_jspx_push_body_count_c_forEach_0[0]-- > 0)
+ out = _jspx_page_context.popBody();
+ _jspx_th_c_forEach_0.doCatch(_jspx_exception);
+ } finally {
+ _jspx_th_c_forEach_0.doFinally();
+ _jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_0);
+ }
+ return false;
+ }
+
+ private boolean _jspx_meth_c_out_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_0)
+ throws Throwable {
+ PageContext pageContext = _jspx_page_context;
+ JspWriter out = _jspx_page_context.getOut();
+ // c:out
+ org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_0 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
+ _jspx_th_c_out_0.setPageContext(_jspx_page_context);
+ _jspx_th_c_out_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_0);
+ _jspx_th_c_out_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
+ int _jspx_eval_c_out_0 = _jspx_th_c_out_0.doStartTag();
+ if (_jspx_th_c_out_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
+ _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_0);
+ return true;
+ }
+ _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_0);
+ return false;
+ }
+
+ private boolean _jspx_meth_c_out_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_0)
+ throws Throwable {
+ PageContext pageContext = _jspx_page_context;
+ JspWriter out = _jspx_page_context.getOut();
+ // c:out
+ org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_1 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
+ _jspx_th_c_out_1.setPageContext(_jspx_page_context);
+ _jspx_th_c_out_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_0);
+ _jspx_th_c_out_1.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.name}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
+ int _jspx_eval_c_out_1 = _jspx_th_c_out_1.doStartTag();
+ if (_jspx_th_c_out_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
+ _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_1);
+ return true;
+ }
+ _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_1);
+ return false;
+ }
+
+ private boolean _jspx_meth_c_out_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_0)
+ throws Throwable {
+ PageContext pageContext = _jspx_page_context;
+ JspWriter out = _jspx_page_context.getOut();
+ // c:out
+ org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_2 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
+ _jspx_th_c_out_2.setPageContext(_jspx_page_context);
+ _jspx_th_c_out_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_0);
+ _jspx_th_c_out_2.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.manufacturer}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
+ int _jspx_eval_c_out_2 = _jspx_th_c_out_2.doStartTag();
+ if (_jspx_th_c_out_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
+ _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_2);
+ return true;
+ }
+ _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_2);
+ return false;
+ }
+
+ private boolean _jspx_meth_fmt_formatNumber_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_0)
+ throws Throwable {
+ PageContext pageContext = _jspx_page_context;
+ JspWriter out = _jspx_page_context.getOut();
+ // fmt:formatNumber
+ org.apache.taglibs.standard.tag.rt.fmt.FormatNumberTag _jspx_th_fmt_formatNumber_0 = (org.apache.taglibs.standard.tag.rt.fmt.FormatNumberTag) _jspx_tagPool_fmt_formatNumber_value_type_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.FormatNumberTag.class);
+ _jspx_th_fmt_formatNumber_0.setPageContext(_jspx_page_context);
+ _jspx_th_fmt_formatNumber_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_0);
+ _jspx_th_fmt_formatNumber_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.price}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
+ _jspx_th_fmt_formatNumber_0.setType("currency");
+ int _jspx_eval_fmt_formatNumber_0 = _jspx_th_fmt_formatNumber_0.doStartTag();
+ if (_jspx_th_fmt_formatNumber_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
+ _jspx_tagPool_fmt_formatNumber_value_type_nobody.reuse(_jspx_th_fmt_formatNumber_0);
+ return true;
+ }
+ _jspx_tagPool_fmt_formatNumber_value_type_nobody.reuse(_jspx_th_fmt_formatNumber_0);
+ return false;
+ }
+}
diff --git a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/view_jsp.class b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/view_jsp.class
new file mode 100644
index 0000000..d6f1562
Binary files /dev/null and b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/view_jsp.class differ
diff --git a/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/view_jsp.java b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/view_jsp.java
new file mode 100644
index 0000000..73b9cfc
--- /dev/null
+++ b/target/work/jsp/org/apache/jsp/WEB_002dINF/views/product/view_jsp.java
@@ -0,0 +1,145 @@
+package org.apache.jsp.WEB_002dINF.views.product;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+import javax.servlet.jsp.*;
+
+public final class view_jsp extends org.apache.jasper.runtime.HttpJspBase
+ implements org.apache.jasper.runtime.JspSourceDependent {
+
+ private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
+
+ private static java.util.Vector _jspx_dependants;
+
+ private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_remove_var_scope_nobody;
+
+ private org.apache.jasper.runtime.ResourceInjector _jspx_resourceInjector;
+
+ public Object getDependants() {
+ return _jspx_dependants;
+ }
+
+ public void _jspInit() {
+ _jspx_tagPool_c_remove_var_scope_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
+ }
+
+ public void _jspDestroy() {
+ _jspx_tagPool_c_remove_var_scope_nobody.release();
+ }
+
+ public void _jspService(HttpServletRequest request, HttpServletResponse response)
+ throws java.io.IOException, ServletException {
+
+ PageContext pageContext = null;
+ HttpSession session = null;
+ ServletContext application = null;
+ ServletConfig config = null;
+ JspWriter out = null;
+ Object page = this;
+ JspWriter _jspx_out = null;
+ PageContext _jspx_page_context = null;
+
+ try {
+ response.setContentType("text/html");
+ pageContext = _jspxFactory.getPageContext(this, request, response,
+ null, true, 8192, true);
+ _jspx_page_context = pageContext;
+ application = pageContext.getServletContext();
+ config = pageContext.getServletConfig();
+ session = pageContext.getSession();
+ out = pageContext.getOut();
+ _jspx_out = out;
+ _jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
+
+ out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n");
+ out.write("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
+ out.write("\n");
+ out.write("\n");
+ out.write("\n");
+ out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
+ out.write("\t<head>\n");
+ out.write("\t\t<meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />\n");
+ out.write("\t\t<title>\n");
+ out.write("\t\t\tView\n");
+ out.write("\t\t</title>\n");
+ out.write("\t</head>\n");
+ out.write("\t<body>\n");
+ out.write(" <h1>View</h1>\n");
+ out.write("\n");
+ out.write(" ");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionScope.message}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\n");
+ out.write(" ");
+ if (_jspx_meth_c_remove_0(_jspx_page_context))
+ return;
+ out.write("\n");
+ out.write("\n");
+ out.write(" <div>\n");
+ out.write(" <span>id: </span> ");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\n");
+ out.write(" </div>\n");
+ out.write(" <div>\n");
+ out.write(" <span>name: </span> ");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.name}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\n");
+ out.write(" </div>\n");
+ out.write(" <div>\n");
+ out.write(" <span>manufactuerer: </span> ");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.manufacturer}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\n");
+ out.write(" </div>\n");
+ out.write(" <div>\n");
+ out.write(" <span>price: </span> ");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.price}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\n");
+ out.write(" </div>\n");
+ out.write("\n");
+ out.write(" <div>\n");
+ out.write(" <a href=\"");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("/product/index.htm\">Index</a>\n");
+ out.write(" <a href=\"");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("/product/edit.htm?id=");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\">Edit</a>\n");
+ out.write(" <a href=\"");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("/product/delete.htm?id=");
+ out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${product.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
+ out.write("\">Delete</a>\n");
+ out.write(" </div>\n");
+ out.write("\t</body>\n");
+ out.write("</html>\n");
+ } catch (Throwable t) {
+ if (!(t instanceof SkipPageException)){
+ out = _jspx_out;
+ if (out != null && out.getBufferSize() != 0)
+ out.clearBuffer();
+ if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
+ }
+ } finally {
+ _jspxFactory.releasePageContext(_jspx_page_context);
+ }
+ }
+
+ private boolean _jspx_meth_c_remove_0(PageContext _jspx_page_context)
+ throws Throwable {
+ PageContext pageContext = _jspx_page_context;
+ JspWriter out = _jspx_page_context.getOut();
+ // c:remove
+ org.apache.taglibs.standard.tag.common.core.RemoveTag _jspx_th_c_remove_0 = (org.apache.taglibs.standard.tag.common.core.RemoveTag) _jspx_tagPool_c_remove_var_scope_nobody.get(org.apache.taglibs.standard.tag.common.core.RemoveTag.class);
+ _jspx_th_c_remove_0.setPageContext(_jspx_page_context);
+ _jspx_th_c_remove_0.setParent(null);
+ _jspx_th_c_remove_0.setVar("message");
+ _jspx_th_c_remove_0.setScope("session");
+ int _jspx_eval_c_remove_0 = _jspx_th_c_remove_0.doStartTag();
+ if (_jspx_th_c_remove_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
+ _jspx_tagPool_c_remove_var_scope_nobody.reuse(_jspx_th_c_remove_0);
+ return true;
+ }
+ _jspx_tagPool_c_remove_var_scope_nobody.reuse(_jspx_th_c_remove_0);
+ return false;
+ }
+}
diff --git a/target/work/jsp/org/apache/jsp/index_jsp.class b/target/work/jsp/org/apache/jsp/index_jsp.class
new file mode 100644
index 0000000..6b990b2
Binary files /dev/null and b/target/work/jsp/org/apache/jsp/index_jsp.class differ
diff --git a/target/work/jsp/org/apache/jsp/index_jsp.java b/target/work/jsp/org/apache/jsp/index_jsp.java
new file mode 100644
index 0000000..7765295
--- /dev/null
+++ b/target/work/jsp/org/apache/jsp/index_jsp.java
@@ -0,0 +1,87 @@
+package org.apache.jsp;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+import javax.servlet.jsp.*;
+
+public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
+ implements org.apache.jasper.runtime.JspSourceDependent {
+
+ private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
+
+ private static java.util.Vector _jspx_dependants;
+
+ private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_redirect_url_nobody;
+
+ private org.apache.jasper.runtime.ResourceInjector _jspx_resourceInjector;
+
+ public Object getDependants() {
+ return _jspx_dependants;
+ }
+
+ public void _jspInit() {
+ _jspx_tagPool_c_redirect_url_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
+ }
+
+ public void _jspDestroy() {
+ _jspx_tagPool_c_redirect_url_nobody.release();
+ }
+
+ public void _jspService(HttpServletRequest request, HttpServletResponse response)
+ throws java.io.IOException, ServletException {
+
+ PageContext pageContext = null;
+ HttpSession session = null;
+ ServletContext application = null;
+ ServletConfig config = null;
+ JspWriter out = null;
+ Object page = this;
+ JspWriter _jspx_out = null;
+ PageContext _jspx_page_context = null;
+
+ try {
+ response.setContentType("text/html");
+ pageContext = _jspxFactory.getPageContext(this, request, response,
+ null, true, 8192, true);
+ _jspx_page_context = pageContext;
+ application = pageContext.getServletContext();
+ config = pageContext.getServletConfig();
+ session = pageContext.getSession();
+ out = pageContext.getOut();
+ _jspx_out = out;
+ _jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
+
+ out.write('\n');
+ if (_jspx_meth_c_redirect_0(_jspx_page_context))
+ return;
+ out.write('\n');
+ } catch (Throwable t) {
+ if (!(t instanceof SkipPageException)){
+ out = _jspx_out;
+ if (out != null && out.getBufferSize() != 0)
+ out.clearBuffer();
+ if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
+ }
+ } finally {
+ _jspxFactory.releasePageContext(_jspx_page_context);
+ }
+ }
+
+ private boolean _jspx_meth_c_redirect_0(PageContext _jspx_page_context)
+ throws Throwable {
+ PageContext pageContext = _jspx_page_context;
+ JspWriter out = _jspx_page_context.getOut();
+ // c:redirect
+ org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_redirect_0 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _jspx_tagPool_c_redirect_url_nobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class);
+ _jspx_th_c_redirect_0.setPageContext(_jspx_page_context);
+ _jspx_th_c_redirect_0.setParent(null);
+ _jspx_th_c_redirect_0.setUrl("/product/index.htm");
+ int _jspx_eval_c_redirect_0 = _jspx_th_c_redirect_0.doStartTag();
+ if (_jspx_th_c_redirect_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
+ _jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_0);
+ return true;
+ }
+ _jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_0);
+ return false;
+ }
+}
|
jcblitz/maven-selenium-demo
|
acb92a54460aa974cfa6fc89634766933dbe5252
|
Initial check in
|
diff --git a/nb-configuration.xml b/nb-configuration.xml
new file mode 100644
index 0000000..4d0a538
--- /dev/null
+++ b/nb-configuration.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project-shared-configuration>
+ <!--
+This file contains additional configuration written by modules in the NetBeans IDE.
+The configuration is intended to be shared among all the users of project and
+therefore it is assumed to be part of version control checkout.
+Without this configuration present, some functionality in the IDE may be limited or fail altogether.
+-->
+ <spring-data xmlns="http://www.netbeans.org/ns/spring-data/1">
+ <config-files>
+ <config-file>src/main/webapp/WEB-INF/testingdemo-servlet.xml</config-file>
+ </config-files>
+ <config-file-groups/>
+ </spring-data>
+</project-shared-configuration>
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000..bd05c5b
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,61 @@
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>net.blitzstein.demo</groupId>
+ <artifactId>testing-demo</artifactId>
+ <packaging>war</packaging>
+ <version>1.0-SNAPSHOT</version>
+ <name>testing-demo Maven Webapp</name>
+ <url>http://maven.apache.org</url>
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.4</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-webmvc</artifactId>
+ <version>2.5.6</version>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
+ <version>2.5.6</version>
+ </dependency>
+
+ </dependencies>
+ <build>
+ <finalName>testing-demo</finalName>
+ <plugins>
+ <plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.5</source>
+ <target>1.5</target>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <additionalClasspathElements>
+ <additionalClasspathElement>
+ src/main/webapp/WEB-INF/
+ </additionalClasspathElement>
+ </additionalClasspathElements>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>cobertura-maven-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.mortbay.jetty</groupId>
+ <artifactId>maven-jetty-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/src/main/java/net/blitzstein/demo/testing/domain/Product.java b/src/main/java/net/blitzstein/demo/testing/domain/Product.java
new file mode 100644
index 0000000..22a2831
--- /dev/null
+++ b/src/main/java/net/blitzstein/demo/testing/domain/Product.java
@@ -0,0 +1,71 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package net.blitzstein.demo.testing.domain;
+
+/**
+ *
+ * @author jared
+ */
+public class Product {
+ private Integer id;
+ private String name, description;
+ private float price;
+ private String manufacturer;
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getManufacturer() {
+ return manufacturer;
+ }
+
+ public void setManufacturer(String manufacturer) {
+ this.manufacturer = manufacturer;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public float getPrice() {
+ return price;
+ }
+
+ public void setPrice(float price) {
+ this.price = price;
+ }
+
+ public Product() {
+ }
+
+ public Product(Integer id, String name, String description, String manufacturer, float price) {
+ this.id = id;
+ this.name = name;
+ this.description = description;
+ this.price = price;
+ this.manufacturer = manufacturer;
+ }
+
+
+
+}
diff --git a/src/main/java/net/blitzstein/demo/testing/web/ProductController.java b/src/main/java/net/blitzstein/demo/testing/web/ProductController.java
new file mode 100644
index 0000000..528fba8
--- /dev/null
+++ b/src/main/java/net/blitzstein/demo/testing/web/ProductController.java
@@ -0,0 +1,101 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package net.blitzstein.demo.testing.web;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import net.blitzstein.demo.testing.domain.Product;
+import org.springframework.beans.BeansException;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+
+/**
+ *
+ * @author jared
+ */
+@Controller
+public class ProductController implements ApplicationContextAware {
+ private List<Product> products = new ArrayList();
+ private ApplicationContext context;
+
+ @RequestMapping(value = "/product/index.htm", method = RequestMethod.GET)
+ public void index(Model model) {
+ model.addAttribute("products", getProducts());
+ }
+
+ public void setProducts(List<Product> products) {
+ this.products = products;
+ }
+
+ @RequestMapping(value = "/product/view.htm", method = RequestMethod.GET)
+ public void view(Model model, @RequestParam("id") int id) {
+ Product product = getProduct(id);
+ model.addAttribute(product);
+ }
+
+ @RequestMapping(value = "/product/edit.htm", method = RequestMethod.GET)
+ public void edit(Model model, @RequestParam("id") int id) {
+ Product product = getProduct(id);
+ model.addAttribute(product);
+ }
+
+ @RequestMapping(value = "/product/create.htm", method = RequestMethod.GET)
+ public String create(Model model) {
+ model.addAttribute(new Product());
+ return "product/edit";
+ }
+
+ @RequestMapping(value = "/product/save.htm", method = RequestMethod.POST)
+ public void save(
+ @ModelAttribute("Product") Product product) {
+
+ }
+
+
+ @RequestMapping(value = "/product/delete.htm", method = RequestMethod.GET)
+ public String delete(@RequestParam("id") int id) {
+ deleteProduct(id);
+ return "redirect:index.htm";
+ }
+
+ private void deleteProduct(int id) {
+ Product product = getProduct(id);
+ this.products.remove(product);
+ }
+
+ private List<Product> getProducts() {
+ //return products;
+ if (this.products == null || this.products.isEmpty()) {
+ Map productMap = context.getBeansOfType(net.blitzstein.demo.testing.domain.Product.class);
+ this.products = new ArrayList(productMap.values());
+ }
+
+ return this.products;
+ }
+
+ private Product getProduct(Integer id) {
+ for (Product product : products) {
+
+ if (product.getId().equals(id)) {
+ return product;
+ }
+
+ }
+
+ return null;
+ }
+
+ public void setApplicationContext(ApplicationContext context) throws BeansException {
+ this.context = context;
+ }
+}
diff --git a/src/main/resources/display.properties b/src/main/resources/display.properties
new file mode 100644
index 0000000..57ed665
--- /dev/null
+++ b/src/main/resources/display.properties
@@ -0,0 +1,3 @@
+# To change this template, choose Tools | Templates
+# and open the template in the editor.
+
diff --git a/src/main/webapp/WEB-INF/testingdemo-servlet.xml b/src/main/webapp/WEB-INF/testingdemo-servlet.xml
new file mode 100644
index 0000000..c92fe68
--- /dev/null
+++ b/src/main/webapp/WEB-INF/testingdemo-servlet.xml
@@ -0,0 +1,65 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xsi:schemaLocation="
+ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
+ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
+ http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
+ http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
+ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
+
+ <context:component-scan base-package="net.blitzstein.demo.testing.web"/>
+ <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
+
+
+ <bean id="messageSource"
+ class="org.springframework.context.support.ResourceBundleMessageSource">
+ <property name="basenames">
+ <list>
+ <value>display</value>
+ </list>
+ </property>
+ </bean>
+
+ <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
+ <property name="mappings">
+ <value>
+ /product/*=productController
+ </value>
+ </property>
+ </bean>
+
+ <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
+ <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
+ <property name="prefix" value="/WEB-INF/views/"/>
+ <property name="suffix" value=".jsp"/>
+ <property name="order" value="2" />
+ </bean>
+
+ <bean id="productController" class="net.blitzstein.demo.testing.web.ProductController">
+
+ </bean>
+
+
+
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="1" />
+ <property name="name" value="Product One" />
+ <property name="manufacturer" value="Apple" />
+ <property name="price" value="3000.50" />
+
+ </bean>
+ <bean class="net.blitzstein.demo.testing.domain.Product">
+ <property name="id" value="2" />
+ <property name="name" value="Product Two" />
+ <property name="manufacturer" value="IBM" />
+ <property name="price" value="1500.00" />
+ </bean>
+
+
+</beans>
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/views/product/create.jsp b/src/main/webapp/WEB-INF/views/product/create.jsp
new file mode 100644
index 0000000..5c81a19
--- /dev/null
+++ b/src/main/webapp/WEB-INF/views/product/create.jsp
@@ -0,0 +1,13 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
+ <title>
+ Edit
+ </title>
+ </head>
+ <body>
+ <h1>Edit</h1>
+ </body>
+</html>
diff --git a/src/main/webapp/WEB-INF/views/product/edit.jsp b/src/main/webapp/WEB-INF/views/product/edit.jsp
new file mode 100644
index 0000000..5c81a19
--- /dev/null
+++ b/src/main/webapp/WEB-INF/views/product/edit.jsp
@@ -0,0 +1,13 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
+ <title>
+ Edit
+ </title>
+ </head>
+ <body>
+ <h1>Edit</h1>
+ </body>
+</html>
diff --git a/src/main/webapp/WEB-INF/views/product/index.jsp b/src/main/webapp/WEB-INF/views/product/index.jsp
new file mode 100644
index 0000000..f676002
--- /dev/null
+++ b/src/main/webapp/WEB-INF/views/product/index.jsp
@@ -0,0 +1,47 @@
+<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
+<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
+ <title>
+ Index
+ </title>
+ </head>
+ <body>
+ <h1>Index</h1>
+
+ <table>
+ <tr>
+ <th>Id</th>
+ <th>Name</th>
+ <th>Manufacturer</th>
+ <th>Price</th>
+ <th>Action</th>
+ </tr>
+ <c:forEach var="product" items="${products}">
+ <tr>
+ <td><c:out value="${product.id}" /></td>
+ <td><c:out value="${product.name}" /></td>
+ <td><c:out value="${product.manufacturer}" /></td>
+ <td><fmt:formatNumber value="${product.price}" type="currency"/></td>
+ <td>
+ <a href="${pageContext.request.contextPath}/product/view.htm?id=${product.id}">View</a>
+ <a href="${pageContext.request.contextPath}/product/edit.htm?id=${product.id}">Edit</a>
+ <a href="${pageContext.request.contextPath}/product/delete.htm?id=${product.id}">Delete</a>
+ </td>
+
+
+
+ </tr>
+ </c:forEach>
+ </table>
+
+
+ <a title="Create a new product" href="${pageContext.request.contextPath}/product/create.htm">Create</a>
+ </body>
+</html>
diff --git a/src/main/webapp/WEB-INF/views/product/view.jsp b/src/main/webapp/WEB-INF/views/product/view.jsp
new file mode 100644
index 0000000..aab2b7e
--- /dev/null
+++ b/src/main/webapp/WEB-INF/views/product/view.jsp
@@ -0,0 +1,13 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
+ <title>
+ View
+ </title>
+ </head>
+ <body>
+ <h1>View</h1>
+ </body>
+</html>
diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000..629d65d
--- /dev/null
+++ b/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<web-app id="MessengerWebApp" version="2.4"
+ xmlns="http://java.sun.com/xml/ns/j2ee"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
+ <display-name>Archetype Created Web Application</display-name>
+
+<context-param>
+ <param-name>contextConfigLocation</param-name>
+ <param-value>/WEB-INF/testingdemo-servlet.xml</param-value>
+ </context-param>
+
+ <servlet>
+ <servlet-name>testingdemo</servlet-name>
+ <servlet-class>
+ org.springframework.web.servlet.DispatcherServlet
+ </servlet-class>
+ <load-on-startup>1</load-on-startup>
+ </servlet>
+
+ <servlet-mapping>
+ <servlet-name>testingdemo</servlet-name>
+ <url-pattern>*.htm</url-pattern>
+ </servlet-mapping>
+
+ <listener>
+ <listener-class>
+ org.springframework.web.context.ContextLoaderListener
+ </listener-class>
+ </listener>
+</web-app>
diff --git a/src/main/webapp/index.jsp b/src/main/webapp/index.jsp
new file mode 100644
index 0000000..c38169b
--- /dev/null
+++ b/src/main/webapp/index.jsp
@@ -0,0 +1,5 @@
+<html>
+<body>
+<h2>Hello World!</h2>
+</body>
+</html>
|
paupawsan/Irrlicht
|
17ce4a30f6779da632d5226e5b3ce35740fcafc1
|
Fix compiling CFileSystem.cpp on Windows (thx pc0de for reporting). Fix warning in COpenGLDriver about initialization order.
|
diff --git a/source/Irrlicht/CFileSystem.cpp b/source/Irrlicht/CFileSystem.cpp
index 62a85c2..423bbb2 100644
--- a/source/Irrlicht/CFileSystem.cpp
+++ b/source/Irrlicht/CFileSystem.cpp
@@ -1,837 +1,837 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "IrrCompileConfig.h"
#include "CFileSystem.h"
#include "IReadFile.h"
#include "IWriteFile.h"
#include "CZipReader.h"
#include "CMountPointReader.h"
#include "CPakReader.h"
#include "CNPKReader.h"
#include "CTarReader.h"
#include "CFileList.h"
#include "CXMLReader.h"
#include "CXMLWriter.h"
#include "stdio.h"
#include "os.h"
#include "CAttributes.h"
#include "CMemoryFile.h"
#include "CLimitReadFile.h"
-
#if defined (_IRR_WINDOWS_API_)
#if !defined ( _WIN32_WCE )
#include <direct.h> // for _chdir
#include <io.h> // for _access
+ #include <tchar.h>
#endif
#else
#if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#endif
namespace irr
{
namespace io
{
//! constructor
CFileSystem::CFileSystem()
{
#ifdef _DEBUG
setDebugName("CFileSystem");
#endif
setFileListSystem(FILESYSTEM_NATIVE);
//! reset current working directory
getWorkingDirectory();
#ifdef __IRR_COMPILE_WITH_ZIP_ARCHIVE_LOADER_
ArchiveLoader.push_back(new CArchiveLoaderZIP(this));
#endif
#ifdef __IRR_COMPILE_WITH_MOUNT_ARCHIVE_LOADER_
ArchiveLoader.push_back(new CArchiveLoaderMount(this));
#endif
#ifdef __IRR_COMPILE_WITH_PAK_ARCHIVE_LOADER_
ArchiveLoader.push_back(new CArchiveLoaderPAK(this));
#endif
#ifdef __IRR_COMPILE_WITH_NPK_ARCHIVE_LOADER_
ArchiveLoader.push_back(new CArchiveLoaderNPK(this));
#endif
#ifdef __IRR_COMPILE_WITH_TAR_ARCHIVE_LOADER_
ArchiveLoader.push_back(new CArchiveLoaderTAR(this));
#endif
}
//! destructor
CFileSystem::~CFileSystem()
{
u32 i;
for ( i=0; i < FileArchives.size(); ++i)
{
FileArchives[i]->drop();
}
for ( i=0; i < ArchiveLoader.size(); ++i)
{
ArchiveLoader[i]->drop();
}
}
//! opens a file for read access
IReadFile* CFileSystem::createAndOpenFile(const io::path& filename)
{
IReadFile* file = 0;
u32 i;
for (i=0; i< FileArchives.size(); ++i)
{
file = FileArchives[i]->createAndOpenFile(filename);
if (file)
return file;
}
// Create the file using an absolute path so that it matches
// the scheme used by CNullDriver::getTexture().
return createReadFile(getAbsolutePath(filename));
}
//! Creates an IReadFile interface for treating memory like a file.
IReadFile* CFileSystem::createMemoryReadFile(void* memory, s32 len,
const io::path& fileName, bool deleteMemoryWhenDropped)
{
if (!memory)
return 0;
else
return new CMemoryFile(memory, len, fileName, deleteMemoryWhenDropped);
}
//! Creates an IReadFile interface for reading files inside files
IReadFile* CFileSystem::createLimitReadFile(const io::path& fileName,
IReadFile* alreadyOpenedFile, long pos, long areaSize)
{
if (!alreadyOpenedFile)
return 0;
else
return new CLimitReadFile(alreadyOpenedFile, pos, areaSize, fileName);
}
//! Creates an IReadFile interface for treating memory like a file.
IWriteFile* CFileSystem::createMemoryWriteFile(void* memory, s32 len,
const io::path& fileName, bool deleteMemoryWhenDropped)
{
if (!memory)
return 0;
else
return new CMemoryFile(memory, len, fileName, deleteMemoryWhenDropped);
}
//! Opens a file for write access.
IWriteFile* CFileSystem::createAndWriteFile(const io::path& filename, bool append)
{
return createWriteFile(filename, append);
}
//! Adds an external archive loader to the engine.
void CFileSystem::addArchiveLoader(IArchiveLoader* loader)
{
if (!loader)
return;
loader->grab();
ArchiveLoader.push_back(loader);
}
//! move the hirarchy of the filesystem. moves sourceIndex relative up or down
bool CFileSystem::moveFileArchive(u32 sourceIndex, s32 relative)
{
bool r = false;
const s32 dest = (s32) sourceIndex + relative;
const s32 dir = relative < 0 ? -1 : 1;
const s32 sourceEnd = ((s32) FileArchives.size() ) - 1;
IFileArchive *t;
for (s32 s = (s32) sourceIndex;s != dest; s += dir)
{
if (s < 0 || s > sourceEnd || s + dir < 0 || s + dir > sourceEnd)
continue;
t = FileArchives[s + dir];
FileArchives[s + dir] = FileArchives[s];
FileArchives[s] = t;
r = true;
}
return r;
}
//! Adds an archive to the file system.
bool CFileSystem::addFileArchive(const io::path& filename, bool ignoreCase,
bool ignorePaths, E_FILE_ARCHIVE_TYPE archiveType,
const core::stringc& password)
{
IFileArchive* archive = 0;
bool ret = false;
u32 i;
// check if the archive was already loaded
for (i = 0; i < FileArchives.size(); ++i)
{
if (getAbsolutePath(filename) == FileArchives[i]->getFileList()->getPath())
{
if (password.size())
FileArchives[i]->Password=password;
return true;
}
}
// do we know what type it should be?
if (archiveType == EFAT_UNKNOWN || archiveType == EFAT_FOLDER)
{
// try to load archive based on file name
for (i = 0; i < ArchiveLoader.size(); ++i)
{
if (ArchiveLoader[i]->isALoadableFileFormat(filename))
{
archive = ArchiveLoader[i]->createArchive(filename, ignoreCase, ignorePaths);
if (archive)
break;
}
}
// try to load archive based on content
if (!archive)
{
io::IReadFile* file = createAndOpenFile(filename);
if (file)
{
for (i = 0; i < ArchiveLoader.size(); ++i)
{
file->seek(0);
if (ArchiveLoader[i]->isALoadableFileFormat(file))
{
file->seek(0);
archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
if (archive)
break;
}
}
file->drop();
}
}
}
else
{
// try to open archive based on archive loader type
io::IReadFile* file = 0;
for (i = 0; i < ArchiveLoader.size(); ++i)
{
if (ArchiveLoader[i]->isALoadableFileFormat(archiveType))
{
// attempt to open file
if (!file)
file = createAndOpenFile(filename);
// is the file open?
if (file)
{
// attempt to open archive
file->seek(0);
if (ArchiveLoader[i]->isALoadableFileFormat(file))
{
file->seek(0);
archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
if (archive)
break;
}
}
else
{
// couldn't open file
break;
}
}
}
// if open, close the file
if (file)
file->drop();
}
if (archive)
{
FileArchives.push_back(archive);
if (password.size())
archive->Password=password;
ret = true;
}
else
{
os::Printer::log("Could not create archive for", filename, ELL_ERROR);
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return ret;
}
//! removes an archive from the file system.
bool CFileSystem::removeFileArchive(u32 index)
{
bool ret = false;
if (index < FileArchives.size())
{
FileArchives[index]->drop();
FileArchives.erase(index);
ret = true;
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return ret;
}
//! removes an archive from the file system.
bool CFileSystem::removeFileArchive(const io::path& filename)
{
for (u32 i=0; i < FileArchives.size(); ++i)
{
if (filename == FileArchives[i]->getFileList()->getPath())
return removeFileArchive(i);
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
//! gets an archive
u32 CFileSystem::getFileArchiveCount() const
{
return FileArchives.size();
}
IFileArchive* CFileSystem::getFileArchive(u32 index)
{
return index < getFileArchiveCount() ? FileArchives[index] : 0;
}
//! Returns the string of the current working directory
const io::path& CFileSystem::getWorkingDirectory()
{
EFileSystemType type = FileSystemType;
if (type != FILESYSTEM_NATIVE)
{
type = FILESYSTEM_VIRTUAL;
}
else
{
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
// does not need this
#elif defined(_IRR_WINDOWS_API_)
fschar_t tmp[_MAX_PATH];
#if defined(_IRR_WCHAR_FILESYSTEM )
_wgetcwd(tmp, _MAX_PATH);
WorkingDirectory[FILESYSTEM_NATIVE] = tmp;
WorkingDirectory[FILESYSTEM_NATIVE].replace(L'\\', L'/');
#else
_getcwd(tmp, _MAX_PATH);
WorkingDirectory[FILESYSTEM_NATIVE] = tmp;
WorkingDirectory[FILESYSTEM_NATIVE].replace('\\', '/');
#endif
#endif
#if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
// getting the CWD is rather complex as we do not know the size
// so try it until the call was successful
// Note that neither the first nor the second parameter may be 0 according to POSIX
#if defined(_IRR_WCHAR_FILESYSTEM )
u32 pathSize=256;
wchar_t *tmpPath = new wchar_t[pathSize];
while ((pathSize < (1<<16)) && !(wgetcwd(tmpPath,pathSize)))
{
delete [] tmpPath;
pathSize *= 2;
tmpPath = new char[pathSize];
}
if (tmpPath)
{
WorkingDirectory[FILESYSTEM_NATIVE] = tmpPath;
delete [] tmpPath;
}
#else
u32 pathSize=256;
char *tmpPath = new char[pathSize];
while ((pathSize < (1<<16)) && !(getcwd(tmpPath,pathSize)))
{
delete [] tmpPath;
pathSize *= 2;
tmpPath = new char[pathSize];
}
if (tmpPath)
{
WorkingDirectory[FILESYSTEM_NATIVE] = tmpPath;
delete [] tmpPath;
}
#endif
#endif
WorkingDirectory[type].validate();
}
return WorkingDirectory[type];
}
//! Changes the current Working Directory to the given string.
bool CFileSystem::changeWorkingDirectoryTo(const io::path& newDirectory)
{
bool success=false;
if (FileSystemType != FILESYSTEM_NATIVE)
{
WorkingDirectory[FILESYSTEM_VIRTUAL] = newDirectory;
flattenFilename(WorkingDirectory[FILESYSTEM_VIRTUAL], "");
success = 1;
}
else
{
WorkingDirectory[FILESYSTEM_NATIVE] = newDirectory;
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
success = true;
#elif defined(_MSC_VER)
#if defined(_IRR_WCHAR_FILESYSTEM)
success=(_wchdir(newDirectory.c_str()) == 0);
#else
success=(_chdir(newDirectory.c_str()) == 0);
#endif
#else
success=(chdir(newDirectory.c_str()) == 0);
#endif
}
return success;
}
io::path CFileSystem::getAbsolutePath(const io::path& filename) const
{
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
return filename;
#elif defined(_IRR_WINDOWS_API_)
fschar_t *p=0;
fschar_t fpath[_MAX_PATH];
#if defined(_IRR_WCHAR_FILESYSTEM )
p = _wfullpath(fpath, filename.c_str(), _MAX_PATH);
core::stringw tmp(p);
tmp.replace(L'\\', L'/');
#else
p = _fullpath(fpath, filename.c_str(), _MAX_PATH);
core::stringc tmp(p);
tmp.replace('\\', '/');
#endif
return tmp;
#elif (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
c8* p=0;
c8 fpath[4096];
fpath[0]=0;
p = realpath(filename.c_str(), fpath);
if (!p)
{
// content in fpath is unclear at this point
if (!fpath[0]) // seems like fpath wasn't altered, use our best guess
{
io::path tmp(filename);
return flattenFilename(tmp);
}
else
return io::path(fpath);
}
if (filename[filename.size()-1]=='/')
return io::path(p)+"/";
else
return io::path(p);
#else
return io::path(filename);
#endif
}
//! returns the directory part of a filename, i.e. all until the first
//! slash or backslash, excluding it. If no directory path is prefixed, a '.'
//! is returned.
io::path CFileSystem::getFileDir(const io::path& filename) const
{
// find last forward or backslash
s32 lastSlash = filename.findLast('/');
const s32 lastBackSlash = filename.findLast('\\');
lastSlash = lastSlash > lastBackSlash ? lastSlash : lastBackSlash;
if ((u32)lastSlash < filename.size())
return filename.subString(0, lastSlash);
else
return ".";
}
//! returns the base part of a filename, i.e. all except for the directory
//! part. If no directory path is prefixed, the full name is returned.
io::path CFileSystem::getFileBasename(const io::path& filename, bool keepExtension) const
{
// find last forward or backslash
s32 lastSlash = filename.findLast('/');
const s32 lastBackSlash = filename.findLast('\\');
lastSlash = core::max_(lastSlash, lastBackSlash);
// get number of chars after last dot
s32 end = 0;
if (!keepExtension)
{
// take care to search only after last slash to check only for
// dots in the filename
end = filename.findLast('.');
if (end == -1 || end < lastSlash)
end=0;
else
end = filename.size()-end;
}
if ((u32)lastSlash < filename.size())
return filename.subString(lastSlash+1, filename.size()-lastSlash-1-end);
else if (end != 0)
return filename.subString(0, filename.size()-end);
else
return filename;
}
//! flatten a path and file name for example: "/you/me/../." becomes "/you"
io::path& CFileSystem::flattenFilename(io::path& directory, const io::path& root) const
{
directory.replace('\\', '/');
if (directory.lastChar() != '/')
directory.append('/');
io::path dir;
io::path subdir;
s32 lastpos = 0;
s32 pos = 0;
bool lastWasRealDir=false;
while ((pos = directory.findNext('/', lastpos)) >= 0)
{
subdir = directory.subString(lastpos, pos - lastpos + 1);
if (subdir == "../")
{
if (lastWasRealDir)
{
deletePathFromPath(dir, 2);
lastWasRealDir=(dir.size()!=0);
}
else
{
dir.append(subdir);
lastWasRealDir=false;
}
}
else if (subdir == "/")
{
dir = root;
}
else if (subdir != "./" )
{
dir.append(subdir);
lastWasRealDir=true;
}
lastpos = pos + 1;
}
directory = dir;
return directory;
}
//! Creates a list of files and directories in the current working directory
EFileSystemType CFileSystem::setFileListSystem(EFileSystemType listType)
{
EFileSystemType current = FileSystemType;
FileSystemType = listType;
return current;
}
//! Creates a list of files and directories in the current working directory
IFileList* CFileSystem::createFileList()
{
CFileList* r = 0;
io::path Path = getWorkingDirectory();
Path.replace('\\', '/');
if (Path.lastChar() != '/')
Path.append('/');
//! Construct from native filesystem
if (FileSystemType == FILESYSTEM_NATIVE)
{
// --------------------------------------------
//! Windows version
#ifdef _IRR_WINDOWS_API_
#if !defined ( _WIN32_WCE )
r = new CFileList(Path, true, false);
struct _tfinddata_t c_file;
long hFile;
- if( (hFile = _tfindfirst( __TEXT"*", &c_file )) != -1L )
+ if( (hFile = _tfindfirst( _T("*"), &c_file )) != -1L )
{
do
{
r->addItem(Path + c_file.name, c_file.size, (_A_SUBDIR & c_file.attrib) != 0, 0);
}
while( _tfindnext( hFile, &c_file ) == 0 );
_findclose( hFile );
}
#endif
//TODO add drives
//entry.Name = "E:\\";
//entry.isDirectory = true;
//Files.push_back(entry);
#endif
// --------------------------------------------
//! Linux version
#if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
r = new CFileList(Path, false, false);
r->addItem(Path + "..", 0, true, 0);
//! We use the POSIX compliant methods instead of scandir
DIR* dirHandle=opendir(Path.c_str());
if (dirHandle)
{
struct dirent *dirEntry;
while ((dirEntry=readdir(dirHandle)))
{
u32 size = 0;
bool isDirectory = false;
if((strcmp(dirEntry->d_name, ".")==0) ||
(strcmp(dirEntry->d_name, "..")==0))
{
continue;
}
struct stat buf;
if (stat(dirEntry->d_name, &buf)==0)
{
size = buf.st_size;
isDirectory = S_ISDIR(buf.st_mode);
}
#if !defined(_IRR_SOLARIS_PLATFORM_) && !defined(__CYGWIN__)
// only available on some systems
else
{
isDirectory = dirEntry->d_type == DT_DIR;
}
#endif
r->addItem(Path + dirEntry->d_name, size, isDirectory, 0);
}
closedir(dirHandle);
}
#endif
}
else
{
//! create file list for the virtual filesystem
r = new CFileList(Path, false, false);
//! add relative navigation
SFileListEntry e2;
SFileListEntry e3;
//! PWD
r->addItem(Path + ".", 0, true, 0);
//! parent
r->addItem(Path + "..", 0, true, 0);
//! merge archives
for (u32 i=0; i < FileArchives.size(); ++i)
{
const IFileList *merge = FileArchives[i]->getFileList();
for (u32 j=0; j < merge->getFileCount(); ++j)
{
if (core::isInSameDirectory(Path, merge->getFullFileName(j)) == 0)
{
r->addItem(merge->getFullFileName(j), merge->getFileSize(j), merge->isDirectory(j), 0);
}
}
}
}
if (r)
r->sort();
return r;
}
//! Creates an empty filelist
IFileList* CFileSystem::createEmptyFileList(const io::path& path, bool ignoreCase, bool ignorePaths)
{
return new CFileList(path, ignoreCase, ignorePaths);
}
//! determines if a file exists and would be able to be opened.
bool CFileSystem::existFile(const io::path& filename) const
{
for (u32 i=0; i < FileArchives.size(); ++i)
if (FileArchives[i]->getFileList()->findFile(filename)!=-1)
return true;
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
#if defined(_IRR_WCHAR_FILESYSTEM)
HANDLE hFile = CreateFileW(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
#else
HANDLE hFile = CreateFileW(core::stringw(filename).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
#endif
if (hFile == INVALID_HANDLE_VALUE)
return false;
else
{
CloseHandle(hFile);
return true;
}
#else
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
#if defined(_MSC_VER)
#if defined(_IRR_WCHAR_FILESYSTEM)
return (_waccess(filename.c_str(), 0) != -1);
#else
return (_access(filename.c_str(), 0) != -1);
#endif
#elif defined(F_OK)
return (access(filename.c_str(), F_OK) != -1);
#else
return (access(filename.c_str(), 0) != -1);
#endif
#endif
}
//! Creates a XML Reader from a file.
IXMLReader* CFileSystem::createXMLReader(const io::path& filename)
{
IReadFile* file = createAndOpenFile(filename);
if (!file)
return 0;
IXMLReader* reader = createXMLReader(file);
file->drop();
return reader;
}
//! Creates a XML Reader from a file.
IXMLReader* CFileSystem::createXMLReader(IReadFile* file)
{
if (!file)
return 0;
return createIXMLReader(file);
}
//! Creates a XML Reader from a file.
IXMLReaderUTF8* CFileSystem::createXMLReaderUTF8(const io::path& filename)
{
IReadFile* file = createAndOpenFile(filename);
if (!file)
return 0;
IXMLReaderUTF8* reader = createIXMLReaderUTF8(file);
file->drop();
return reader;
}
//! Creates a XML Reader from a file.
IXMLReaderUTF8* CFileSystem::createXMLReaderUTF8(IReadFile* file)
{
if (!file)
return 0;
return createIXMLReaderUTF8(file);
}
//! Creates a XML Writer from a file.
IXMLWriter* CFileSystem::createXMLWriter(const io::path& filename)
{
IWriteFile* file = createAndWriteFile(filename);
IXMLWriter* writer = createXMLWriter(file);
file->drop();
return writer;
}
//! Creates a XML Writer from a file.
IXMLWriter* CFileSystem::createXMLWriter(IWriteFile* file)
{
return new CXMLWriter(file);
}
//! creates a filesystem which is able to open files from the ordinary file system,
//! and out of zipfiles, which are able to be added to the filesystem.
IFileSystem* createFileSystem()
{
return new CFileSystem();
}
//! Creates a new empty collection of attributes, usable for serialization and more.
IAttributes* CFileSystem::createEmptyAttributes(video::IVideoDriver* driver)
{
return new CAttributes(driver);
}
} // end namespace irr
} // end namespace io
diff --git a/source/Irrlicht/COpenGLDriver.cpp b/source/Irrlicht/COpenGLDriver.cpp
index 810e320..6efc6cd 100644
--- a/source/Irrlicht/COpenGLDriver.cpp
+++ b/source/Irrlicht/COpenGLDriver.cpp
@@ -1,920 +1,920 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "COpenGLDriver.h"
// needed here also because of the create methods' parameters
#include "CNullDriver.h"
#ifdef _IRR_COMPILE_WITH_OPENGL_
#include "COpenGLTexture.h"
#include "COpenGLMaterialRenderer.h"
#include "COpenGLShaderMaterialRenderer.h"
#include "COpenGLSLMaterialRenderer.h"
#include "COpenGLNormalMapRenderer.h"
#include "COpenGLParallaxMapRenderer.h"
#include "CImage.h"
#include "os.h"
#ifdef _IRR_COMPILE_WITH_SDL_DEVICE_
#include <SDL/SDL.h>
#endif
namespace irr
{
namespace video
{
// -----------------------------------------------------------------------
// WINDOWS CONSTRUCTOR
// -----------------------------------------------------------------------
#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_
//! Windows constructor and init code
COpenGLDriver::COpenGLDriver(const irr::SIrrlichtCreationParameters& params,
io::IFileSystem* io, CIrrDeviceWin32* device)
: CNullDriver(io, params.WindowSize), COpenGLExtensionHandler(),
CurrentRenderMode(ERM_NONE), ResetRenderStates(true), Transformation3DChanged(true),
AntiAlias(params.AntiAlias), RenderTargetTexture(0),
CurrentRendertargetSize(0,0), ColorFormat(ECF_R8G8B8),
CurrentTarget(ERT_FRAME_BUFFER),
Doublebuffer(params.Doublebuffer), Stereo(params.Stereobuffer),
- HDc(0), Device(device), Window(static_cast<HWND>(params.WindowId)),
+ HDc(0), Window(static_cast<HWND>(params.WindowId)), Device(device),
DeviceType(EIDT_WIN32)
{
#ifdef _DEBUG
setDebugName("COpenGLDriver");
#endif
}
bool COpenGLDriver::changeRenderContext(const SExposedVideoData& videoData, CIrrDeviceWin32* device)
{
if (videoData.OpenGLWin32.HWnd && videoData.OpenGLWin32.HDc && videoData.OpenGLWin32.HRc)
{
if (!wglMakeCurrent((HDC)videoData.OpenGLWin32.HDc, (HGLRC)videoData.OpenGLWin32.HRc))
{
os::Printer::log("Render Context switch failed.");
return false;
}
else
{
HDc = (HDC)videoData.OpenGLWin32.HDc;
}
}
// set back to main context
else if (HDc != ExposedData.OpenGLWin32.HDc)
{
if (!wglMakeCurrent((HDC)ExposedData.OpenGLWin32.HDc, (HGLRC)ExposedData.OpenGLWin32.HRc))
{
os::Printer::log("Render Context switch failed.");
return false;
}
else
{
HDc = (HDC)ExposedData.OpenGLWin32.HDc;
}
}
return true;
}
//! inits the open gl driver
bool COpenGLDriver::initDriver(irr::SIrrlichtCreationParameters params, CIrrDeviceWin32* device)
{
// Create a window to test antialiasing support
const fschar_t* ClassName = __TEXT("GLCIrrDeviceWin32");
HINSTANCE lhInstance = GetModuleHandle(0);
// Register Class
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)DefWindowProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = lhInstance;
wcex.hIcon = NULL;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = 0;
wcex.lpszClassName = ClassName;
wcex.hIconSm = 0;
wcex.hIcon = 0;
RegisterClassEx(&wcex);
RECT clientSize;
clientSize.top = 0;
clientSize.left = 0;
clientSize.right = params.WindowSize.Width;
clientSize.bottom = params.WindowSize.Height;
DWORD style = WS_POPUP;
if (!params.Fullscreen)
style = WS_SYSMENU | WS_BORDER | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
AdjustWindowRect(&clientSize, style, FALSE);
const s32 realWidth = clientSize.right - clientSize.left;
const s32 realHeight = clientSize.bottom - clientSize.top;
const s32 windowLeft = (GetSystemMetrics(SM_CXSCREEN) - realWidth) / 2;
const s32 windowTop = (GetSystemMetrics(SM_CYSCREEN) - realHeight) / 2;
HWND temporary_wnd=CreateWindow(ClassName, __TEXT(""), style, windowLeft,
windowTop, realWidth, realHeight, NULL, NULL, lhInstance, NULL);
if (!temporary_wnd)
{
os::Printer::log("Cannot create a temporary window.", ELL_ERROR);
return false;
}
HDc = GetDC(temporary_wnd);
// Set up pixel format descriptor with desired parameters
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
(params.Doublebuffer?PFD_DOUBLEBUFFER:0) | // Must Support Double Buffering
(params.Stereobuffer?PFD_STEREO:0), // Must Support Stereo Buffer
PFD_TYPE_RGBA, // Request An RGBA Format
params.Bits, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
params.ZBufferBits, // Z-Buffer (Depth Buffer)
params.Stencilbuffer ? 1 : 0, // Stencil Buffer Depth
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
GLuint PixelFormat;
for (u32 i=0; i<5; ++i)
{
if (i == 1)
{
if (params.Stencilbuffer)
{
os::Printer::log("Cannot create a GL device with stencil buffer, disabling stencil shadows.", ELL_WARNING);
params.Stencilbuffer = false;
pfd.cStencilBits = 0;
}
else
continue;
}
else
if (i == 2)
{
pfd.cDepthBits = 24;
}
if (i == 3)
{
if (params.Bits!=16)
pfd.cDepthBits = 16;
else
continue;
}
else
if (i == 4)
{
// try single buffer
if (params.Doublebuffer)
pfd.dwFlags &= ~PFD_DOUBLEBUFFER;
else
continue;
}
else
if (i == 5)
{
os::Printer::log("Cannot create a GL device context", "No suitable format for temporary window.", ELL_ERROR);
ReleaseDC(temporary_wnd, HDc);
DestroyWindow(temporary_wnd);
return false;
}
// choose pixelformat
PixelFormat = ChoosePixelFormat(HDc, &pfd);
if (PixelFormat)
break;
}
SetPixelFormat(HDc, PixelFormat, &pfd);
HGLRC hrc=wglCreateContext(HDc);
if (!hrc)
{
os::Printer::log("Cannot create a temporary GL rendering context.", ELL_ERROR);
ReleaseDC(temporary_wnd, HDc);
DestroyWindow(temporary_wnd);
return false;
}
SExposedVideoData data;
data.OpenGLWin32.HDc = HDc;
data.OpenGLWin32.HRc = hrc;
data.OpenGLWin32.HWnd = temporary_wnd;
-
+
if (!changeRenderContext(data, device))
{
os::Printer::log("Cannot activate a temporary GL rendering context.", ELL_ERROR);
wglDeleteContext(hrc);
ReleaseDC(temporary_wnd, HDc);
DestroyWindow(temporary_wnd);
return false;
}
#ifdef _DEBUG
core::stringc wglExtensions;
#ifdef WGL_ARB_extensions_string
PFNWGLGETEXTENSIONSSTRINGARBPROC irrGetExtensionsString = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB");
if (irrGetExtensionsString)
wglExtensions = irrGetExtensionsString(HDc);
#elif defined(WGL_EXT_extensions_string)
PFNWGLGETEXTENSIONSSTRINGEXTPROC irrGetExtensionsString = (PFNWGLGETEXTENSIONSSTRINGEXTPROC)wglGetProcAddress("wglGetExtensionsStringEXT");
if (irrGetExtensionsString)
wglExtensions = irrGetExtensionsString(HDc);
#endif
os::Printer::log("WGL_extensions", wglExtensions);
#endif
#ifdef WGL_ARB_pixel_format
PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormat_ARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
if (wglChoosePixelFormat_ARB)
{
// This value determines the number of samples used for antialiasing
// My experience is that 8 does not show a big
// improvement over 4, but 4 shows a big improvement
// over 2.
if(AntiAlias > 32)
AntiAlias = 32;
f32 fAttributes[] = {0.0, 0.0};
s32 iAttributes[] =
{
WGL_DRAW_TO_WINDOW_ARB,GL_TRUE,
WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
WGL_COLOR_BITS_ARB,(params.Bits==32) ? 24 : 15,
WGL_ALPHA_BITS_ARB,(params.Bits==32) ? 8 : 1,
WGL_DEPTH_BITS_ARB,params.ZBufferBits, // 10,11
WGL_STENCIL_BITS_ARB,(params.Stencilbuffer) ? 1 : 0,
WGL_DOUBLE_BUFFER_ARB,(params.Doublebuffer) ? GL_TRUE : GL_FALSE,
WGL_STEREO_ARB,(params.Stereobuffer) ? GL_TRUE : GL_FALSE,
#ifdef WGL_ARB_multisample
WGL_SAMPLE_BUFFERS_ARB, 1,
WGL_SAMPLES_ARB,AntiAlias, // 20,21
#elif defined(WGL_EXT_multisample)
WGL_SAMPLE_BUFFERS_EXT, 1,
WGL_SAMPLES_EXT,AntiAlias, // 20,21
#elif defined(WGL_3DFX_multisample)
WGL_SAMPLE_BUFFERS_3DFX, 1,
WGL_SAMPLES_3DFX,AntiAlias, // 20,21
#endif
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
// other possible values:
// WGL_ARB_pixel_format_float: WGL_TYPE_RGBA_FLOAT_ARB
// WGL_EXT_pixel_format_packed_float: WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT
#if 0
#ifdef WGL_EXT_framebuffer_sRGB
WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT, GL_FALSE,
#endif
#endif
0,0
};
s32 rv=0;
// Try to get an acceptable pixel format
while(rv==0 && iAttributes[21]>1)
{
s32 pixelFormat=0;
u32 numFormats=0;
const s32 valid = wglChoosePixelFormat_ARB(HDc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
if (valid && numFormats>0)
rv = pixelFormat;
else
iAttributes[21] -= 1;
}
if (rv)
{
PixelFormat=rv;
AntiAlias=iAttributes[21];
}
}
else
#endif
AntiAlias=0;
wglMakeCurrent(HDc, NULL);
wglDeleteContext(hrc);
ReleaseDC(temporary_wnd, HDc);
DestroyWindow(temporary_wnd);
// get hdc
HDc=GetDC(Window);
if (!HDc)
{
os::Printer::log("Cannot create a GL device context.", ELL_ERROR);
return false;
}
// search for pixel format the simple way
if (AntiAlias < 2)
{
for (u32 i=0; i<5; ++i)
{
if (i == 1)
{
if (params.Stencilbuffer)
{
os::Printer::log("Cannot create a GL device with stencil buffer, disabling stencil shadows.", ELL_WARNING);
params.Stencilbuffer = false;
pfd.cStencilBits = 0;
}
else
continue;
}
else
if (i == 2)
{
pfd.cDepthBits = 24;
}
if (i == 3)
{
if (params.Bits!=16)
pfd.cDepthBits = 16;
else
continue;
}
else
if (i == 4)
{
os::Printer::log("Cannot create a GL device context", "No suitable format.", ELL_ERROR);
return false;
}
// choose pixelformat
PixelFormat = ChoosePixelFormat(HDc, &pfd);
if (PixelFormat)
break;
}
}
// set pixel format
if (!SetPixelFormat(HDc, PixelFormat, &pfd))
{
os::Printer::log("Cannot set the pixel format.", ELL_ERROR);
return false;
}
// create rendering context
#ifdef WGL_ARB_create_context
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribs_ARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
if (wglCreateContextAttribs_ARB)
{
int iAttribs[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
WGL_CONTEXT_MINOR_VERSION_ARB, 1,
0
};
hrc=wglCreateContextAttribs_ARB(HDc, 0, iAttribs);
}
else
#endif
hrc=wglCreateContext(HDc);
if (!hrc)
{
os::Printer::log("Cannot create a GL rendering context.", ELL_ERROR);
return false;
}
// set exposed data
ExposedData.OpenGLWin32.HDc = HDc;
ExposedData.OpenGLWin32.HRc = hrc;
ExposedData.OpenGLWin32.HWnd = Window;
// activate rendering context
-
+
if (!changeRenderContext(ExposedData, device))
{
os::Printer::log("Cannot activate GL rendering context", ELL_ERROR);
wglDeleteContext(hrc);
return false;
}
int pf = GetPixelFormat(HDc);
DescribePixelFormat(HDc, pf, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
if (pfd.cAlphaBits != 0)
{
if (pfd.cRedBits == 8)
ColorFormat = ECF_A8R8G8B8;
else
ColorFormat = ECF_A1R5G5B5;
}
else
{
if (pfd.cRedBits == 8)
ColorFormat = ECF_R8G8B8;
else
ColorFormat = ECF_R5G6B5;
}
genericDriverInit(params.WindowSize, params.Stencilbuffer);
#ifdef WGL_EXT_swap_control
PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT;
// vsync extension
wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT");
// set vsync
if (wglSwapIntervalEXT)
wglSwapIntervalEXT(params.Vsync ? 1 : 0);
#endif
return true;
}
#endif // _IRR_COMPILE_WITH_WINDOWS_DEVICE_
// -----------------------------------------------------------------------
// MacOSX CONSTRUCTOR
// -----------------------------------------------------------------------
#ifdef _IRR_COMPILE_WITH_OSX_DEVICE_
//! Windows constructor and init code
COpenGLDriver::COpenGLDriver(const SIrrlichtCreationParameters& params,
io::IFileSystem* io, CIrrDeviceMacOSX *device)
: CNullDriver(io, params.WindowSize), COpenGLExtensionHandler(),
CurrentRenderMode(ERM_NONE), ResetRenderStates(true), Transformation3DChanged(true),
AntiAlias(params.AntiAlias), RenderTargetTexture(0),
CurrentRendertargetSize(0,0), ColorFormat(ECF_R8G8B8),
CurrentTarget(ERT_FRAME_BUFFER),
Doublebuffer(params.Doublebuffer), Stereo(params.Stereobuffer),
Device(device), DeviceType(EIDT_OSX)
{
#ifdef _DEBUG
setDebugName("COpenGLDriver");
#endif
genericDriverInit(params.WindowSize, params.Stencilbuffer);
}
#endif
// -----------------------------------------------------------------------
// LINUX CONSTRUCTOR
// -----------------------------------------------------------------------
#ifdef _IRR_COMPILE_WITH_X11_DEVICE_
//! Linux constructor and init code
COpenGLDriver::COpenGLDriver(const SIrrlichtCreationParameters& params,
io::IFileSystem* io, CIrrDeviceLinux* device)
: CNullDriver(io, params.WindowSize), COpenGLExtensionHandler(),
CurrentRenderMode(ERM_NONE), ResetRenderStates(true),
Transformation3DChanged(true), AntiAlias(params.AntiAlias),
RenderTargetTexture(0), CurrentRendertargetSize(0,0), ColorFormat(ECF_R8G8B8),
CurrentTarget(ERT_FRAME_BUFFER),
Doublebuffer(params.Doublebuffer), Stereo(params.Stereobuffer),
Device(device), DeviceType(EIDT_X11)
{
#ifdef _DEBUG
setDebugName("COpenGLDriver");
#endif
}
bool COpenGLDriver::changeRenderContext(const SExposedVideoData& videoData, CIrrDeviceLinux* device)
{
if (videoData.OpenGLLinux.X11Display && videoData.OpenGLLinux.X11Window && videoData.OpenGLLinux.X11Context)
{
if (!glXMakeCurrent((Display*)videoData.OpenGLLinux.X11Display, videoData.OpenGLLinux.X11Window, (GLXContext)videoData.OpenGLLinux.X11Context))
{
os::Printer::log("Render Context switch failed.");
return false;
}
else
{
Drawable = videoData.OpenGLLinux.X11Window;
X11Display = (Display*)videoData.OpenGLLinux.X11Display;
}
}
// set back to main context
else if (X11Display != ExposedData.OpenGLLinux.X11Display)
{
if (!glXMakeCurrent((Display*)ExposedData.OpenGLLinux.X11Display, ExposedData.OpenGLLinux.X11Window, (GLXContext)ExposedData.OpenGLLinux.X11Context))
{
os::Printer::log("Render Context switch failed.");
return false;
}
else
{
Drawable = ExposedData.OpenGLLinux.X11Window;
X11Display = (Display*)ExposedData.OpenGLLinux.X11Display;
}
}
return true;
}
//! inits the open gl driver
bool COpenGLDriver::initDriver(irr::SIrrlichtCreationParameters params, CIrrDeviceLinux* device)
{
ExposedData.OpenGLLinux.X11Context = glXGetCurrentContext();
ExposedData.OpenGLLinux.X11Display = glXGetCurrentDisplay();
ExposedData.OpenGLLinux.X11Window = (unsigned long)params.WindowId;
Drawable = glXGetCurrentDrawable();
X11Display = (Display*)ExposedData.OpenGLLinux.X11Display;
genericDriverInit(params.WindowSize, params.Stencilbuffer);
// set vsync
//TODO: Check GLX_EXT_swap_control and GLX_MESA_swap_control
#ifdef GLX_SGI_swap_control
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (params.Vsync && glxSwapIntervalSGI)
glxSwapIntervalSGI(1);
#else
if (params.Vsync)
glXSwapIntervalSGI(1);
#endif
#endif
return true;
}
#endif // _IRR_COMPILE_WITH_X11_DEVICE_
// -----------------------------------------------------------------------
// SDL CONSTRUCTOR
// -----------------------------------------------------------------------
#ifdef _IRR_COMPILE_WITH_SDL_DEVICE_
//! SDL constructor and init code
COpenGLDriver::COpenGLDriver(const SIrrlichtCreationParameters& params,
io::IFileSystem* io, CIrrDeviceSDL* device)
: CNullDriver(io, params.WindowSize), COpenGLExtensionHandler(),
CurrentRenderMode(ERM_NONE), ResetRenderStates(true),
Transformation3DChanged(true), AntiAlias(params.AntiAlias),
RenderTargetTexture(0), CurrentRendertargetSize(0,0), ColorFormat(ECF_R8G8B8),
CurrentTarget(ERT_FRAME_BUFFER),
Doublebuffer(params.Doublebuffer), Stereo(params.Stereobuffer),
Device(device), DeviceType(EIDT_SDL)
{
#ifdef _DEBUG
setDebugName("COpenGLDriver");
#endif
genericDriverInit(params.WindowSize, params.Stencilbuffer);
}
#endif // _IRR_COMPILE_WITH_SDL_DEVICE_
//! destructor
COpenGLDriver::~COpenGLDriver()
{
RequestedLights.clear();
deleteMaterialRenders();
// I get a blue screen on my laptop, when I do not delete the
// textures manually before releasing the dc. Oh how I love this.
deleteAllTextures();
#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_
if (DeviceType == EIDT_WIN32)
{
if (ExposedData.OpenGLWin32.HRc)
{
if (!wglMakeCurrent(0, 0))
os::Printer::log("Release of dc and rc failed.", ELL_WARNING);
if (!wglDeleteContext((HGLRC)ExposedData.OpenGLWin32.HRc))
os::Printer::log("Release of rendering context failed.", ELL_WARNING);
}
if (HDc)
ReleaseDC(Window, HDc);
}
#endif
}
// -----------------------------------------------------------------------
// METHODS
// -----------------------------------------------------------------------
bool COpenGLDriver::genericDriverInit(const core::dimension2d<u32>& screenSize, bool stencilBuffer)
{
Name=L"OpenGL ";
Name.append(glGetString(GL_VERSION));
s32 pos=Name.findNext(L' ', 7);
if (pos != -1)
Name=Name.subString(0, pos);
printVersion();
// print renderer information
const GLubyte* renderer = glGetString(GL_RENDERER);
const GLubyte* vendor = glGetString(GL_VENDOR);
if (renderer && vendor)
{
os::Printer::log(reinterpret_cast<const c8*>(renderer), reinterpret_cast<const c8*>(vendor), ELL_INFORMATION);
VendorName = reinterpret_cast<const c8*>(vendor);
}
u32 i;
for (i=0; i<MATERIAL_MAX_TEXTURES; ++i)
CurrentTexture[i]=0;
// load extensions
initExtensions(stencilBuffer);
if (queryFeature(EVDF_ARB_GLSL))
{
char buf[32];
const u32 maj = ShaderLanguageVersion/100;
snprintf(buf, 32, "%u.%u", maj, ShaderLanguageVersion-maj*100);
os::Printer::log("GLSL version", buf, ELL_INFORMATION);
}
else
os::Printer::log("GLSL not available.", ELL_INFORMATION);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
// Reset The Current Viewport
glViewport(0, 0, screenSize.Width, screenSize.Height);
UserClipPlanes.reallocate(MaxUserClipPlanes);
for (i=0; i<MaxUserClipPlanes; ++i)
UserClipPlanes.push_back(SUserClipPlane());
for (i=0; i<ETS_COUNT; ++i)
setTransform(static_cast<E_TRANSFORMATION_STATE>(i), core::IdentityMatrix);
setAmbientLight(SColorf(0.0f,0.0f,0.0f,0.0f));
#ifdef GL_EXT_separate_specular_color
if (FeatureAvailable[IRR_EXT_separate_specular_color])
glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
#endif
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
// This is a fast replacement for NORMALIZE_NORMALS
// if ((Version>101) || FeatureAvailable[IRR_EXT_rescale_normal])
// glEnable(GL_RESCALE_NORMAL_EXT);
glClearDepth(1.0);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glHint(GL_POINT_SMOOTH_HINT, GL_FASTEST);
glDepthFunc(GL_LEQUAL);
glFrontFace(GL_CW);
// adjust flat coloring scheme to DirectX version
#if defined(GL_ARB_provoking_vertex) || defined(GL_EXT_provoking_vertex)
extGlProvokingVertex(GL_FIRST_VERTEX_CONVENTION_EXT);
#endif
// create material renderers
createMaterialRenderers();
// set the renderstates
setRenderStates3DMode();
glAlphaFunc(GL_GREATER, 0.f);
// set fog mode
setFog(FogColor, FogType, FogStart, FogEnd, FogDensity, PixelFog, RangeFog);
// create matrix for flipping textures
TextureFlipMatrix.buildTextureTransform(0.0f, core::vector2df(0,0), core::vector2df(0,1.0f), core::vector2df(1.0f,-1.0f));
// We need to reset once more at the beginning of the first rendering.
// This fixes problems with intermediate changes to the material during texture load.
ResetRenderStates = true;
return true;
}
void COpenGLDriver::createMaterialRenderers()
{
// create OpenGL material renderers
addAndDropMaterialRenderer(new COpenGLMaterialRenderer_SOLID(this));
addAndDropMaterialRenderer(new COpenGLMaterialRenderer_SOLID_2_LAYER(this));
// add the same renderer for all lightmap types
COpenGLMaterialRenderer_LIGHTMAP* lmr = new COpenGLMaterialRenderer_LIGHTMAP(this);
addMaterialRenderer(lmr); // for EMT_LIGHTMAP:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_ADD:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_M2:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_M4:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_LIGHTING:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_LIGHTING_M2:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_LIGHTING_M4:
lmr->drop();
// add remaining material renderer
addAndDropMaterialRenderer(new COpenGLMaterialRenderer_DETAIL_MAP(this));
addAndDropMaterialRenderer(new COpenGLMaterialRenderer_SPHERE_MAP(this));
addAndDropMaterialRenderer(new COpenGLMaterialRenderer_REFLECTION_2_LAYER(this));
addAndDropMaterialRenderer(new COpenGLMaterialRenderer_TRANSPARENT_ADD_COLOR(this));
addAndDropMaterialRenderer(new COpenGLMaterialRenderer_TRANSPARENT_ALPHA_CHANNEL(this));
addAndDropMaterialRenderer(new COpenGLMaterialRenderer_TRANSPARENT_ALPHA_CHANNEL_REF(this));
addAndDropMaterialRenderer(new COpenGLMaterialRenderer_TRANSPARENT_VERTEX_ALPHA(this));
addAndDropMaterialRenderer(new COpenGLMaterialRenderer_TRANSPARENT_REFLECTION_2_LAYER(this));
// add normal map renderers
s32 tmp = 0;
video::IMaterialRenderer* renderer = 0;
renderer = new COpenGLNormalMapRenderer(this, tmp, MaterialRenderers[EMT_SOLID].Renderer);
renderer->drop();
renderer = new COpenGLNormalMapRenderer(this, tmp, MaterialRenderers[EMT_TRANSPARENT_ADD_COLOR].Renderer);
renderer->drop();
renderer = new COpenGLNormalMapRenderer(this, tmp, MaterialRenderers[EMT_TRANSPARENT_VERTEX_ALPHA].Renderer);
renderer->drop();
// add parallax map renderers
renderer = new COpenGLParallaxMapRenderer(this, tmp, MaterialRenderers[EMT_SOLID].Renderer);
renderer->drop();
renderer = new COpenGLParallaxMapRenderer(this, tmp, MaterialRenderers[EMT_TRANSPARENT_ADD_COLOR].Renderer);
renderer->drop();
renderer = new COpenGLParallaxMapRenderer(this, tmp, MaterialRenderers[EMT_TRANSPARENT_VERTEX_ALPHA].Renderer);
renderer->drop();
// add basic 1 texture blending
addAndDropMaterialRenderer(new COpenGLMaterialRenderer_ONETEXTURE_BLEND(this));
}
//! presents the rendered scene on the screen, returns false if failed
bool COpenGLDriver::endScene()
{
CNullDriver::endScene();
glFlush();
#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_
if (DeviceType == EIDT_WIN32)
return SwapBuffers(HDc) == TRUE;
#endif
#ifdef _IRR_COMPILE_WITH_X11_DEVICE_
if (DeviceType == EIDT_X11)
{
glXSwapBuffers(X11Display, Drawable);
return true;
}
#endif
#ifdef _IRR_COMPILE_WITH_OSX_DEVICE_
if (DeviceType == EIDT_OSX)
{
Device->flush();
return true;
}
#endif
#ifdef _IRR_COMPILE_WITH_SDL_DEVICE_
if (DeviceType == EIDT_SDL)
{
SDL_GL_SwapBuffers();
return true;
}
#endif
// todo: console device present
return false;
}
//! clears the zbuffer and color buffer
void COpenGLDriver::clearBuffers(bool backBuffer, bool zBuffer, bool stencilBuffer, SColor color)
{
GLbitfield mask = 0;
if (backBuffer)
{
const f32 inv = 1.0f / 255.0f;
glClearColor(color.getRed() * inv, color.getGreen() * inv,
color.getBlue() * inv, color.getAlpha() * inv);
mask |= GL_COLOR_BUFFER_BIT;
}
if (zBuffer)
{
glDepthMask(GL_TRUE);
LastMaterial.ZWriteEnable=true;
mask |= GL_DEPTH_BUFFER_BIT;
}
if (stencilBuffer)
mask |= GL_STENCIL_BUFFER_BIT;
glClear(mask);
}
//! init call for rendering start
bool COpenGLDriver::beginScene(bool backBuffer, bool zBuffer, SColor color,
const SExposedVideoData& videoData, core::rect<s32>* sourceRect)
{
CNullDriver::beginScene(backBuffer, zBuffer, color, videoData, sourceRect);
changeRenderContext(videoData, Device);
#if defined(_IRR_COMPILE_WITH_SDL_DEVICE_)
if (DeviceType == EIDT_SDL)
{
// todo: SDL sets glFrontFace(GL_CCW) after driver creation,
// it would be better if this was fixed elsewhere.
glFrontFace(GL_CW);
}
#endif
clearBuffers(backBuffer, zBuffer, false, color);
return true;
}
//! Returns the transformation set by setTransform
const core::matrix4& COpenGLDriver::getTransform(E_TRANSFORMATION_STATE state) const
{
return Matrices[state];
}
//! sets transformation
void COpenGLDriver::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat)
{
Matrices[state] = mat;
Transformation3DChanged = true;
switch (state)
{
case ETS_VIEW:
case ETS_WORLD:
{
// OpenGL only has a model matrix, view and world is not existent. so lets fake these two.
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf((Matrices[ETS_VIEW] * Matrices[ETS_WORLD]).pointer());
// we have to update the clip planes to the latest view matrix
for (u32 i=0; i<MaxUserClipPlanes; ++i)
if (UserClipPlanes[i].Enabled)
uploadClipPlane(i);
}
break;
case ETS_PROJECTION:
{
GLfloat glmat[16];
createGLMatrix(glmat, mat);
// flip z to compensate OpenGLs right-hand coordinate system
glmat[12] *= -1.0f;
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(glmat);
}
break;
case ETS_COUNT:
return;
default:
{
const u32 i = state - ETS_TEXTURE_0;
if (i >= MATERIAL_MAX_TEXTURES)
break;
const bool isRTT = Material.getTexture(i) && Material.getTexture(i)->isRenderTarget();
if (MultiTextureExtension)
extGlActiveTexture(GL_TEXTURE0_ARB + i);
glMatrixMode(GL_TEXTURE);
if (!isRTT && mat.isIdentity() )
glLoadIdentity();
else
{
GLfloat glmat[16];
if (isRTT)
createGLTextureMatrix(glmat, mat * TextureFlipMatrix);
else
createGLTextureMatrix(glmat, mat);
glLoadMatrixf(glmat);
}
break;
}
}
}
bool COpenGLDriver::updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer)
{
if (!HWBuffer)
return false;
if (!FeatureAvailable[IRR_ARB_vertex_buffer_object])
return false;
@@ -3253,852 +3253,852 @@ void COpenGLDriver::drawStencilShadowVolume(const core::vector3df* triangles, s3
extGlStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, 0, ~0);
glDrawArrays(GL_TRIANGLES,0,count);
}
}
else
#endif
{
glEnable(GL_CULL_FACE);
if (!zfail)
{
// ZPASS Method
glCullFace(GL_BACK);
glStencilOp(GL_KEEP, GL_KEEP, incr);
glDrawArrays(GL_TRIANGLES,0,count);
glCullFace(GL_FRONT);
glStencilOp(GL_KEEP, GL_KEEP, decr);
glDrawArrays(GL_TRIANGLES,0,count);
}
else
{
// ZFAIL Method
glStencilOp(GL_KEEP, incr, GL_KEEP);
glCullFace(GL_FRONT);
glDrawArrays(GL_TRIANGLES,0,count);
glStencilOp(GL_KEEP, decr, GL_KEEP);
glCullFace(GL_BACK);
glDrawArrays(GL_TRIANGLES,0,count);
}
}
glDisableClientState(GL_VERTEX_ARRAY); //not stored on stack
glPopAttrib();
}
void COpenGLDriver::drawStencilShadow(bool clearStencilBuffer, video::SColor leftUpEdge,
video::SColor rightUpEdge, video::SColor leftDownEdge, video::SColor rightDownEdge)
{
if (!StencilBuffer)
return;
disableTextures();
// store attributes
glPushAttrib(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT | GL_POLYGON_BIT | GL_STENCIL_BUFFER_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_FOG);
glDepthMask(GL_FALSE);
glShadeModel(GL_FLAT);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_NOTEQUAL, 0, ~0);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
// draw a shadow rectangle covering the entire screen using stencil buffer
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glBegin(GL_QUADS);
glColor4ub(leftDownEdge.getRed(), leftDownEdge.getGreen(), leftDownEdge.getBlue(), leftDownEdge.getAlpha());
glVertex3f(-1.f,-1.f,-0.9f);
glColor4ub(leftUpEdge.getRed(), leftUpEdge.getGreen(), leftUpEdge.getBlue(), leftUpEdge.getAlpha());
glVertex3f(-1.f, 1.f,-0.9f);
glColor4ub(rightUpEdge.getRed(), rightUpEdge.getGreen(), rightUpEdge.getBlue(), rightUpEdge.getAlpha());
glVertex3f(1.f, 1.f,-0.9f);
glColor4ub(rightDownEdge.getRed(), rightDownEdge.getGreen(), rightDownEdge.getBlue(), rightDownEdge.getAlpha());
glVertex3f(1.f,-1.f,-0.9f);
glEnd();
clearBuffers(false, false, clearStencilBuffer, 0x0);
// restore settings
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();
}
//! Sets the fog mode.
void COpenGLDriver::setFog(SColor c, E_FOG_TYPE fogType, f32 start,
f32 end, f32 density, bool pixelFog, bool rangeFog)
{
CNullDriver::setFog(c, fogType, start, end, density, pixelFog, rangeFog);
glFogf(GL_FOG_MODE, GLfloat((fogType==EFT_FOG_LINEAR)? GL_LINEAR : (fogType==EFT_FOG_EXP)?GL_EXP:GL_EXP2));
#ifdef GL_EXT_fog_coord
if (FeatureAvailable[IRR_EXT_fog_coord])
glFogi(GL_FOG_COORDINATE_SOURCE, GL_FRAGMENT_DEPTH);
#endif
#ifdef GL_NV_fog_distance
if (FeatureAvailable[IRR_NV_fog_distance])
{
if (rangeFog)
glFogi(GL_FOG_DISTANCE_MODE_NV, GL_EYE_RADIAL_NV);
else
glFogi(GL_FOG_DISTANCE_MODE_NV, GL_EYE_PLANE_ABSOLUTE_NV);
}
#endif
if (fogType==EFT_FOG_LINEAR)
{
glFogf(GL_FOG_START, start);
glFogf(GL_FOG_END, end);
}
else
glFogf(GL_FOG_DENSITY, density);
if (pixelFog)
glHint(GL_FOG_HINT, GL_NICEST);
else
glHint(GL_FOG_HINT, GL_FASTEST);
SColorf color(c);
GLfloat data[4] = {color.r, color.g, color.b, color.a};
glFogfv(GL_FOG_COLOR, data);
}
//! Draws a 3d line.
void COpenGLDriver::draw3DLine(const core::vector3df& start,
const core::vector3df& end, SColor color)
{
setRenderStates3DMode();
glBegin(GL_LINES);
glColor4ub(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
glVertex3f(start.X, start.Y, start.Z);
glVertex3f(end.X, end.Y, end.Z);
glEnd();
}
//! Only used by the internal engine. Used to notify the driver that
//! the window was resized.
void COpenGLDriver::OnResize(const core::dimension2d<u32>& size)
{
CNullDriver::OnResize(size);
glViewport(0, 0, size.Width, size.Height);
Transformation3DChanged = true;
}
//! Returns type of video driver
E_DRIVER_TYPE COpenGLDriver::getDriverType() const
{
return EDT_OPENGL;
}
//! returns color format
ECOLOR_FORMAT COpenGLDriver::getColorFormat() const
{
return ColorFormat;
}
//! Sets a vertex shader constant.
void COpenGLDriver::setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
{
#ifdef GL_ARB_vertex_program
for (s32 i=0; i<constantAmount; ++i)
extGlProgramLocalParameter4fv(GL_VERTEX_PROGRAM_ARB, startRegister+i, &data[i*4]);
#endif
}
//! Sets a pixel shader constant.
void COpenGLDriver::setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
{
#ifdef GL_ARB_fragment_program
for (s32 i=0; i<constantAmount; ++i)
extGlProgramLocalParameter4fv(GL_FRAGMENT_PROGRAM_ARB, startRegister+i, &data[i*4]);
#endif
}
//! Sets a constant for the vertex shader based on a name.
bool COpenGLDriver::setVertexShaderConstant(const c8* name, const f32* floats, int count)
{
//pass this along, as in GLSL the same routine is used for both vertex and fragment shaders
return setPixelShaderConstant(name, floats, count);
}
//! Sets a constant for the pixel shader based on a name.
bool COpenGLDriver::setPixelShaderConstant(const c8* name, const f32* floats, int count)
{
os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
return false;
}
//! Adds a new material renderer to the VideoDriver, using pixel and/or
//! vertex shaders to render geometry.
s32 COpenGLDriver::addShaderMaterial(const c8* vertexShaderProgram,
const c8* pixelShaderProgram,
IShaderConstantSetCallBack* callback,
E_MATERIAL_TYPE baseMaterial, s32 userData)
{
s32 nr = -1;
COpenGLShaderMaterialRenderer* r = new COpenGLShaderMaterialRenderer(
this, nr, vertexShaderProgram, pixelShaderProgram,
callback, getMaterialRenderer(baseMaterial), userData);
r->drop();
return nr;
}
//! Adds a new material renderer to the VideoDriver, using GLSL to render geometry.
s32 COpenGLDriver::addHighLevelShaderMaterial(
const c8* vertexShaderProgram,
const c8* vertexShaderEntryPointName,
E_VERTEX_SHADER_TYPE vsCompileTarget,
const c8* pixelShaderProgram,
const c8* pixelShaderEntryPointName,
E_PIXEL_SHADER_TYPE psCompileTarget,
const c8* geometryShaderProgram,
const c8* geometryShaderEntryPointName,
E_GEOMETRY_SHADER_TYPE gsCompileTarget,
scene::E_PRIMITIVE_TYPE inType,
scene::E_PRIMITIVE_TYPE outType,
u32 verticesOut,
IShaderConstantSetCallBack* callback,
E_MATERIAL_TYPE baseMaterial,
s32 userData)
{
s32 nr = -1;
COpenGLSLMaterialRenderer* r = new COpenGLSLMaterialRenderer(
this, nr,
vertexShaderProgram, vertexShaderEntryPointName, vsCompileTarget,
pixelShaderProgram, pixelShaderEntryPointName, psCompileTarget,
geometryShaderProgram, geometryShaderEntryPointName, gsCompileTarget,
inType, outType, verticesOut,
callback,getMaterialRenderer(baseMaterial), userData);
r->drop();
return nr;
}
//! Returns a pointer to the IVideoDriver interface. (Implementation for
//! IMaterialRendererServices)
IVideoDriver* COpenGLDriver::getVideoDriver()
{
return this;
}
ITexture* COpenGLDriver::addRenderTargetTexture(const core::dimension2d<u32>& size,
const io::path& name,
const ECOLOR_FORMAT format)
{
//disable mip-mapping
bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS);
setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false);
video::ITexture* rtt = 0;
#if defined(GL_EXT_framebuffer_object)
// if driver supports FrameBufferObjects, use them
if (queryFeature(EVDF_FRAMEBUFFER_OBJECT))
{
rtt = new COpenGLFBOTexture(size, name, this, format);
if (rtt)
{
bool success = false;
addTexture(rtt);
ITexture* tex = createDepthTexture(rtt);
if (tex)
{
success = static_cast<video::COpenGLFBODepthTexture*>(tex)->attach(rtt);
if ( !success )
{
removeDepthTexture(tex);
}
tex->drop();
}
rtt->drop();
if (!success)
{
removeTexture(rtt);
rtt=0;
}
}
}
else
#endif
{
// the simple texture is only possible for size <= screensize
// we try to find an optimal size with the original constraints
core::dimension2du destSize(core::min_(size.Width,ScreenSize.Width), core::min_(size.Height,ScreenSize.Height));
destSize = destSize.getOptimalSize((size==size.getOptimalSize()), false, false);
rtt = addTexture(destSize, name, ECF_A8R8G8B8);
if (rtt)
{
static_cast<video::COpenGLTexture*>(rtt)->setIsRenderTarget(true);
}
}
//restore mip-mapping
setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels);
return rtt;
}
//! Returns the maximum amount of primitives (mostly vertices) which
//! the device is able to render with one drawIndexedTriangleList
//! call.
u32 COpenGLDriver::getMaximalPrimitiveCount() const
{
return 0x7fffffff;
}
//! set or reset render target
bool COpenGLDriver::setRenderTarget(video::E_RENDER_TARGET target, bool clearTarget,
bool clearZBuffer, SColor color)
{
if (target != CurrentTarget)
setRenderTarget(0, false, false, 0x0);
if (ERT_RENDER_TEXTURE == target)
{
os::Printer::log("Fatal Error: For render textures call setRenderTarget with the actual texture as first parameter.", ELL_ERROR);
return false;
}
if (Stereo && (ERT_STEREO_RIGHT_BUFFER == target))
{
if (Doublebuffer)
glDrawBuffer(GL_BACK_RIGHT);
else
glDrawBuffer(GL_FRONT_RIGHT);
}
else if (Stereo && ERT_STEREO_BOTH_BUFFERS == target)
{
if (Doublebuffer)
glDrawBuffer(GL_BACK);
else
glDrawBuffer(GL_FRONT);
}
else if ((target >= ERT_AUX_BUFFER0) && (target-ERT_AUX_BUFFER0 < MaxAuxBuffers))
{
glDrawBuffer(GL_AUX0+target-ERT_AUX_BUFFER0);
}
else
{
if (Doublebuffer)
glDrawBuffer(GL_BACK_LEFT);
else
glDrawBuffer(GL_FRONT_LEFT);
// exit with false, but also with working color buffer
if (target != ERT_FRAME_BUFFER)
return false;
}
CurrentTarget=target;
clearBuffers(clearTarget, clearZBuffer, false, color);
return true;
}
//! set or reset render target
bool COpenGLDriver::setRenderTarget(video::ITexture* texture, bool clearBackBuffer,
bool clearZBuffer, SColor color)
{
// check for right driver type
if (texture && texture->getDriverType() != EDT_OPENGL)
{
os::Printer::log("Fatal Error: Tried to set a texture not owned by this driver.", ELL_ERROR);
return false;
}
// check if we should set the previous RT back
setActiveTexture(0, 0);
ResetRenderStates=true;
if (RenderTargetTexture!=0)
{
RenderTargetTexture->unbindRTT();
}
if (texture)
{
// we want to set a new target. so do this.
glViewport(0, 0, texture->getSize().Width, texture->getSize().Height);
RenderTargetTexture = static_cast<COpenGLTexture*>(texture);
RenderTargetTexture->bindRTT();
CurrentRendertargetSize = texture->getSize();
CurrentTarget=ERT_RENDER_TEXTURE;
}
else
{
glViewport(0,0,ScreenSize.Width,ScreenSize.Height);
RenderTargetTexture = 0;
CurrentRendertargetSize = core::dimension2d<u32>(0,0);
CurrentTarget=ERT_FRAME_BUFFER;
glDrawBuffer(Doublebuffer?GL_BACK_LEFT:GL_FRONT_LEFT);
}
clearBuffers(clearBackBuffer, clearZBuffer, false, color);
return true;
}
//! Sets multiple render targets
bool COpenGLDriver::setRenderTarget(const core::array<video::IRenderTarget>& targets,
bool clearBackBuffer, bool clearZBuffer, SColor color)
{
if (targets.size()==0)
return setRenderTarget(0, clearBackBuffer, clearZBuffer, color);
u32 maxMultipleRTTs = core::min_(static_cast<u32>(MaxMultipleRenderTargets), targets.size());
// determine common size
core::dimension2du rttSize = CurrentRendertargetSize;
if (targets[0].TargetType==ERT_RENDER_TEXTURE)
{
if (!targets[0].RenderTexture)
{
os::Printer::log("Missing render texture for MRT.", ELL_ERROR);
return false;
}
rttSize=targets[0].RenderTexture->getSize();
}
for (u32 i = 0; i < maxMultipleRTTs; ++i)
{
// check for right driver type
if (targets[i].TargetType==ERT_RENDER_TEXTURE)
{
if (!targets[i].RenderTexture)
{
maxMultipleRTTs=i;
os::Printer::log("Missing render texture for MRT.", ELL_WARNING);
break;
}
if (targets[i].RenderTexture->getDriverType() != EDT_OPENGL)
{
maxMultipleRTTs=i;
os::Printer::log("Tried to set a texture not owned by this driver.", ELL_WARNING);
break;
}
// check for valid render target
if (!targets[i].RenderTexture->isRenderTarget() || !static_cast<COpenGLTexture*>(targets[i].RenderTexture)->isFrameBufferObject())
{
maxMultipleRTTs=i;
os::Printer::log("Tried to set a non FBO-RTT as render target.", ELL_WARNING);
break;
}
// check for valid size
if (rttSize != targets[i].RenderTexture->getSize())
{
maxMultipleRTTs=i;
os::Printer::log("Render target texture has wrong size.", ELL_WARNING);
break;
}
}
}
if (maxMultipleRTTs==0)
{
os::Printer::log("No valid MRTs.", ELL_ERROR);
return false;
}
// init FBO, if any
for (u32 i=0; i<maxMultipleRTTs; ++i)
{
if (targets[i].TargetType==ERT_RENDER_TEXTURE)
{
setRenderTarget(targets[i].RenderTexture, false, false, 0x0);
break;
}
}
// init other main buffer, if necessary
if (targets[0].TargetType!=ERT_RENDER_TEXTURE)
setRenderTarget(targets[0].TargetType, false, false, 0x0);
// attach other textures and store buffers into array
if (maxMultipleRTTs > 1)
{
CurrentTarget=ERT_MULTI_RENDER_TEXTURES;
core::array<GLenum> MRTs;
MRTs.set_used(maxMultipleRTTs);
for(u32 i = 0; i < maxMultipleRTTs; i++)
{
if (FeatureAvailable[IRR_EXT_draw_buffers2])
{
- extGlColorMaskIndexed(i,
+ extGlColorMaskIndexed(i,
(targets[i].ColorMask & ECP_RED)?GL_TRUE:GL_FALSE,
(targets[i].ColorMask & ECP_GREEN)?GL_TRUE:GL_FALSE,
(targets[i].ColorMask & ECP_BLUE)?GL_TRUE:GL_FALSE,
(targets[i].ColorMask & ECP_ALPHA)?GL_TRUE:GL_FALSE);
if (targets[i].BlendEnable)
extGlEnableIndexed(GL_BLEND, i);
else
extGlDisableIndexed(GL_BLEND, i);
}
if (FeatureAvailable[IRR_AMD_draw_buffers_blend] || FeatureAvailable[IRR_ARB_draw_buffers_blend])
{
extGlBlendFuncIndexed(i, targets[i].BlendFuncSrc, targets[i].BlendFuncDst);
}
if (targets[i].TargetType==ERT_RENDER_TEXTURE)
{
GLenum attachment = GL_NONE;
#ifdef GL_EXT_framebuffer_object
// attach texture to FrameBuffer Object on Color [i]
attachment = GL_COLOR_ATTACHMENT0_EXT+i;
extGlFramebufferTexture2D(GL_FRAMEBUFFER_EXT, attachment, GL_TEXTURE_2D, static_cast<COpenGLTexture*>(targets[i].RenderTexture)->getOpenGLTextureName(), 0);
#endif
MRTs[i]=attachment;
}
else
{
switch(targets[i].TargetType)
{
case ERT_FRAME_BUFFER:
MRTs[i]=GL_BACK_LEFT;
break;
case ERT_STEREO_BOTH_BUFFERS:
MRTs[i]=GL_BACK;
break;
case ERT_STEREO_RIGHT_BUFFER:
MRTs[i]=GL_BACK_RIGHT;
break;
case ERT_STEREO_LEFT_BUFFER:
MRTs[i]=GL_BACK_LEFT;
break;
default:
MRTs[i]=GL_AUX0+(targets[i].TargetType-ERT_AUX_BUFFER0);
break;
}
}
}
extGlDrawBuffers(maxMultipleRTTs, MRTs.const_pointer());
}
clearBuffers(clearBackBuffer, clearZBuffer, false, color);
return true;
}
// returns the current size of the screen or rendertarget
const core::dimension2d<u32>& COpenGLDriver::getCurrentRenderTargetSize() const
{
if (CurrentRendertargetSize.Width == 0)
return ScreenSize;
else
return CurrentRendertargetSize;
}
//! Clears the ZBuffer.
void COpenGLDriver::clearZBuffer()
{
clearBuffers(false, true, false, 0x0);
}
//! Returns an image created from the last rendered frame.
IImage* COpenGLDriver::createScreenShot()
{
IImage* newImage = new CImage(ECF_R8G8B8, ScreenSize);
u8* pixels = static_cast<u8*>(newImage->lock());
if (!pixels)
{
newImage->drop();
return 0;
}
// allows to read pixels in top-to-bottom order
#ifdef GL_MESA_pack_invert
if (FeatureAvailable[IRR_MESA_pack_invert])
glPixelStorei(GL_PACK_INVERT_MESA, GL_TRUE);
#endif
// We want to read the front buffer to get the latest render finished.
glReadBuffer(GL_FRONT);
glReadPixels(0, 0, ScreenSize.Width, ScreenSize.Height, GL_RGB, GL_UNSIGNED_BYTE, pixels);
glReadBuffer(GL_BACK);
#ifdef GL_MESA_pack_invert
if (FeatureAvailable[IRR_MESA_pack_invert])
glPixelStorei(GL_PACK_INVERT_MESA, GL_FALSE);
else
#endif
{
// opengl images are horizontally flipped, so we have to fix that here.
const s32 pitch=newImage->getPitch();
u8* p2 = pixels + (ScreenSize.Height - 1) * pitch;
u8* tmpBuffer = new u8[pitch];
for (u32 i=0; i < ScreenSize.Height; i += 2)
{
memcpy(tmpBuffer, pixels, pitch);
memcpy(pixels, p2, pitch);
memcpy(p2, tmpBuffer, pitch);
pixels += pitch;
p2 -= pitch;
}
delete [] tmpBuffer;
}
newImage->unlock();
if (testGLError())
{
newImage->drop();
return 0;
}
return newImage;
}
//! get depth texture for the given render target texture
ITexture* COpenGLDriver::createDepthTexture(ITexture* texture, bool shared)
{
if ((texture->getDriverType() != EDT_OPENGL) || (!texture->isRenderTarget()))
return 0;
COpenGLTexture* tex = static_cast<COpenGLTexture*>(texture);
if (!tex->isFrameBufferObject())
return 0;
if (shared)
{
for (u32 i=0; i<DepthTextures.size(); ++i)
{
if (DepthTextures[i]->getSize()==texture->getSize())
{
DepthTextures[i]->grab();
return DepthTextures[i];
}
}
DepthTextures.push_back(new COpenGLFBODepthTexture(texture->getSize(), "depth1", this));
return DepthTextures.getLast();
}
return (new COpenGLFBODepthTexture(texture->getSize(), "depth1", this));
}
void COpenGLDriver::removeDepthTexture(ITexture* texture)
{
for (u32 i=0; i<DepthTextures.size(); ++i)
{
if (texture==DepthTextures[i])
{
DepthTextures.erase(i);
return;
}
}
}
//! Set/unset a clipping plane.
bool COpenGLDriver::setClipPlane(u32 index, const core::plane3df& plane, bool enable)
{
if (index >= MaxUserClipPlanes)
return false;
UserClipPlanes[index].Plane=plane;
enableClipPlane(index, enable);
return true;
}
void COpenGLDriver::uploadClipPlane(u32 index)
{
// opengl needs an array of doubles for the plane equation
double clip_plane[4];
clip_plane[0] = UserClipPlanes[index].Plane.Normal.X;
clip_plane[1] = UserClipPlanes[index].Plane.Normal.Y;
clip_plane[2] = UserClipPlanes[index].Plane.Normal.Z;
clip_plane[3] = UserClipPlanes[index].Plane.D;
glClipPlane(GL_CLIP_PLANE0 + index, clip_plane);
}
//! Enable/disable a clipping plane.
void COpenGLDriver::enableClipPlane(u32 index, bool enable)
{
if (index >= MaxUserClipPlanes)
return;
if (enable)
{
if (!UserClipPlanes[index].Enabled)
{
uploadClipPlane(index);
glEnable(GL_CLIP_PLANE0 + index);
}
}
else
glDisable(GL_CLIP_PLANE0 + index);
UserClipPlanes[index].Enabled=enable;
}
core::dimension2du COpenGLDriver::getMaxTextureSize() const
{
return core::dimension2du(MaxTextureSize, MaxTextureSize);
}
//! Convert E_PRIMITIVE_TYPE to OpenGL equivalent
GLenum COpenGLDriver::primitiveTypeToGL(scene::E_PRIMITIVE_TYPE type) const
{
switch (type)
{
case scene::EPT_POINTS:
return GL_POINTS;
case scene::EPT_LINE_STRIP:
return GL_LINE_STRIP;
case scene::EPT_LINE_LOOP:
return GL_LINE_LOOP;
case scene::EPT_LINES:
return GL_LINES;
case scene::EPT_TRIANGLE_STRIP:
return GL_TRIANGLE_STRIP;
case scene::EPT_TRIANGLE_FAN:
return GL_TRIANGLE_FAN;
case scene::EPT_TRIANGLES:
return GL_TRIANGLES;
case scene::EPT_QUAD_STRIP:
return GL_QUAD_STRIP;
case scene::EPT_QUADS:
return GL_QUADS;
case scene::EPT_POLYGON:
return GL_POLYGON;
case scene::EPT_POINT_SPRITES:
#ifdef GL_ARB_point_sprite
return GL_POINT_SPRITE_ARB;
#else
return GL_POINTS;
#endif
}
return GL_TRIANGLES;
}
} // end namespace
} // end namespace
#endif // _IRR_COMPILE_WITH_OPENGL_
namespace irr
{
namespace video
{
// -----------------------------------
// WINDOWS VERSION
// -----------------------------------
#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_
IVideoDriver* createOpenGLDriver(const SIrrlichtCreationParameters& params,
io::IFileSystem* io, CIrrDeviceWin32* device)
{
#ifdef _IRR_COMPILE_WITH_OPENGL_
COpenGLDriver* ogl = new COpenGLDriver(params, io, device);
if (!ogl->initDriver(params, device))
{
ogl->drop();
ogl = 0;
}
return ogl;
#else
return 0;
#endif // _IRR_COMPILE_WITH_OPENGL_
}
#endif // _IRR_COMPILE_WITH_WINDOWS_DEVICE_
// -----------------------------------
// MACOSX VERSION
// -----------------------------------
#if defined(_IRR_COMPILE_WITH_OSX_DEVICE_)
IVideoDriver* createOpenGLDriver(const SIrrlichtCreationParameters& params,
io::IFileSystem* io, CIrrDeviceMacOSX *device)
{
#ifdef _IRR_COMPILE_WITH_OPENGL_
return new COpenGLDriver(params, io, device);
#else
return 0;
#endif // _IRR_COMPILE_WITH_OPENGL_
}
#endif // _IRR_COMPILE_WITH_OSX_DEVICE_
// -----------------------------------
// X11 VERSION
// -----------------------------------
#ifdef _IRR_COMPILE_WITH_X11_DEVICE_
IVideoDriver* createOpenGLDriver(const SIrrlichtCreationParameters& params,
io::IFileSystem* io, CIrrDeviceLinux* device)
{
#ifdef _IRR_COMPILE_WITH_OPENGL_
COpenGLDriver* ogl = new COpenGLDriver(params, io, device);
if (!ogl->initDriver(params, device))
{
ogl->drop();
ogl = 0;
}
return ogl;
#else
return 0;
#endif // _IRR_COMPILE_WITH_OPENGL_
}
#endif // _IRR_COMPILE_WITH_X11_DEVICE_
// -----------------------------------
// SDL VERSION
// -----------------------------------
#ifdef _IRR_COMPILE_WITH_SDL_DEVICE_
IVideoDriver* createOpenGLDriver(const SIrrlichtCreationParameters& params,
io::IFileSystem* io, CIrrDeviceSDL* device)
{
#ifdef _IRR_COMPILE_WITH_OPENGL_
return new COpenGLDriver(params, io, device);
#else
return 0;
#endif // _IRR_COMPILE_WITH_OPENGL_
}
#endif // _IRR_COMPILE_WITH_SDL_DEVICE_
} // end namespace
} // end namespace
|
paupawsan/Irrlicht
|
815231497d3a0cd9fb7a2213dd036a66b7bf17ce
|
RGB confusion fixed by shine5128
|
diff --git a/source/Irrlicht/CIrrMeshWriter.cpp b/source/Irrlicht/CIrrMeshWriter.cpp
index f6b2d94..06de87f 100644
--- a/source/Irrlicht/CIrrMeshWriter.cpp
+++ b/source/Irrlicht/CIrrMeshWriter.cpp
@@ -1,315 +1,315 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_IRR_WRITER_
#include "CIrrMeshWriter.h"
#include "os.h"
#include "IWriteFile.h"
#include "IXMLWriter.h"
#include "IMesh.h"
#include "IAttributes.h"
namespace irr
{
namespace scene
{
CIrrMeshWriter::CIrrMeshWriter(video::IVideoDriver* driver,
io::IFileSystem* fs)
: FileSystem(fs), VideoDriver(driver), Writer(0)
{
#ifdef _DEBUG
setDebugName("CIrrMeshWriter");
#endif
if (VideoDriver)
VideoDriver->grab();
if (FileSystem)
FileSystem->grab();
}
CIrrMeshWriter::~CIrrMeshWriter()
{
if (VideoDriver)
VideoDriver->drop();
if (FileSystem)
FileSystem->drop();
}
//! Returns the type of the mesh writer
EMESH_WRITER_TYPE CIrrMeshWriter::getType() const
{
return EMWT_IRR_MESH;
}
//! writes a mesh
bool CIrrMeshWriter::writeMesh(io::IWriteFile* file, scene::IMesh* mesh, s32 flags)
{
if (!file)
return false;
Writer = FileSystem->createXMLWriter(file);
if (!Writer)
{
os::Printer::log("Could not write file", file->getFileName());
return false;
}
os::Printer::log("Writing mesh", file->getFileName());
// write IRR MESH header
Writer->writeXMLHeader();
Writer->writeElement(L"mesh", false,
L"xmlns", L"http://irrlicht.sourceforge.net/IRRMESH_09_2007",
L"version", L"1.0");
Writer->writeLineBreak();
// add some informational comment. Add a space after and before the comment
// tags so that some braindead xml parsers (AS anyone?) are able to parse this too.
core::stringw infoComment = L" This file contains a static mesh in the Irrlicht Engine format with ";
infoComment += core::stringw(mesh->getMeshBufferCount());
infoComment += L" materials.";
Writer->writeComment(infoComment.c_str());
Writer->writeLineBreak();
// write mesh bounding box
writeBoundingBox(mesh->getBoundingBox());
Writer->writeLineBreak();
// write mesh buffers
for (int i=0; i<(int)mesh->getMeshBufferCount(); ++i)
{
scene::IMeshBuffer* buffer = mesh->getMeshBuffer(i);
if (buffer)
{
writeMeshBuffer(buffer);
Writer->writeLineBreak();
}
}
Writer->writeClosingTag(L"mesh");
Writer->drop();
return true;
}
void CIrrMeshWriter::writeBoundingBox(const core::aabbox3df& box)
{
Writer->writeElement(L"boundingBox", true,
L"minEdge", getVectorAsStringLine(box.MinEdge).c_str(),
L"maxEdge", getVectorAsStringLine(box.MaxEdge).c_str());
}
core::stringw CIrrMeshWriter::getVectorAsStringLine(const core::vector3df& v) const
{
core::stringw str;
str = core::stringw(v.X);
str += L" ";
str += core::stringw(v.Y);
str += L" ";
str += core::stringw(v.Z);
return str;
}
core::stringw CIrrMeshWriter::getVectorAsStringLine(const core::vector2df& v) const
{
core::stringw str;
str = core::stringw(v.X);
str += L" ";
str += core::stringw(v.Y);
return str;
}
void CIrrMeshWriter::writeMeshBuffer(const scene::IMeshBuffer* buffer)
{
Writer->writeElement(L"buffer", false);
Writer->writeLineBreak();
// write bounding box
writeBoundingBox(buffer->getBoundingBox());
Writer->writeLineBreak();
// write material
writeMaterial(buffer->getMaterial());
// write vertices
const core::stringw vertexTypeStr = video::sBuiltInVertexTypeNames[buffer->getVertexType()];
Writer->writeElement(L"vertices", false,
L"type", vertexTypeStr.c_str(),
L"vertexCount", core::stringw(buffer->getVertexCount()).c_str());
Writer->writeLineBreak();
u32 vertexCount = buffer->getVertexCount();
switch(buffer->getVertexType())
{
case video::EVT_STANDARD:
{
video::S3DVertex* vtx = (video::S3DVertex*)buffer->getVertices();
for (u32 j=0; j<vertexCount; ++j)
{
core::stringw str = getVectorAsStringLine(vtx[j].Pos);
str += L" ";
str += getVectorAsStringLine(vtx[j].Normal);
char tmp[12];
- sprintf(tmp, " %02x%02x%02x%02x ", vtx[j].Color.getAlpha(), vtx[j].Color.getRed(), vtx[j].Color.getBlue(), vtx[j].Color.getGreen());
+ sprintf(tmp, " %02x%02x%02x%02x ", vtx[j].Color.getAlpha(), vtx[j].Color.getRed(), vtx[j].Color.getGreen(), vtx[j].Color.getBlue());
str += tmp;
str += getVectorAsStringLine(vtx[j].TCoords);
Writer->writeText(str.c_str());
Writer->writeLineBreak();
}
}
break;
case video::EVT_2TCOORDS:
{
video::S3DVertex2TCoords* vtx = (video::S3DVertex2TCoords*)buffer->getVertices();
for (u32 j=0; j<vertexCount; ++j)
{
core::stringw str = getVectorAsStringLine(vtx[j].Pos);
str += L" ";
str += getVectorAsStringLine(vtx[j].Normal);
char tmp[12];
- sprintf(tmp, " %02x%02x%02x%02x ", vtx[j].Color.getAlpha(), vtx[j].Color.getRed(), vtx[j].Color.getBlue(), vtx[j].Color.getGreen());
+ sprintf(tmp, " %02x%02x%02x%02x ", vtx[j].Color.getAlpha(), vtx[j].Color.getRed(), vtx[j].Color.getGreen(), vtx[j].Color.getBlue());
str += tmp;
str += getVectorAsStringLine(vtx[j].TCoords);
str += L" ";
str += getVectorAsStringLine(vtx[j].TCoords2);
Writer->writeText(str.c_str());
Writer->writeLineBreak();
}
}
break;
case video::EVT_TANGENTS:
{
video::S3DVertexTangents* vtx = (video::S3DVertexTangents*)buffer->getVertices();
for (u32 j=0; j<vertexCount; ++j)
{
core::stringw str = getVectorAsStringLine(vtx[j].Pos);
str += L" ";
str += getVectorAsStringLine(vtx[j].Normal);
char tmp[12];
- sprintf(tmp, " %02x%02x%02x%02x ", vtx[j].Color.getAlpha(), vtx[j].Color.getRed(), vtx[j].Color.getBlue(), vtx[j].Color.getGreen());
+ sprintf(tmp, " %02x%02x%02x%02x ", vtx[j].Color.getAlpha(), vtx[j].Color.getRed(), vtx[j].Color.getGreen(), vtx[j].Color.getBlue());
str += tmp;
str += getVectorAsStringLine(vtx[j].TCoords);
str += L" ";
str += getVectorAsStringLine(vtx[j].Tangent);
str += L" ";
str += getVectorAsStringLine(vtx[j].Binormal);
Writer->writeText(str.c_str());
Writer->writeLineBreak();
}
}
break;
}
Writer->writeClosingTag(L"vertices");
Writer->writeLineBreak();
// write indices
Writer->writeElement(L"indices", false,
L"indexCount", core::stringw(buffer->getIndexCount()).c_str());
Writer->writeLineBreak();
int indexCount = (int)buffer->getIndexCount();
video::E_INDEX_TYPE iType = buffer->getIndexType();
const u16* idx16 = buffer->getIndices();
const u32* idx32 = (u32*) buffer->getIndices();
const int maxIndicesPerLine = 25;
for (int i=0; i<indexCount; ++i)
{
if(iType == video::EIT_16BIT)
{
core::stringw str((int)idx16[i]);
Writer->writeText(str.c_str());
}
else
{
core::stringw str((int)idx32[i]);
Writer->writeText(str.c_str());
}
if (i % maxIndicesPerLine != maxIndicesPerLine)
{
if (i % maxIndicesPerLine == maxIndicesPerLine-1)
Writer->writeLineBreak();
else
Writer->writeText(L" ");
}
}
if ((indexCount-1) % maxIndicesPerLine != maxIndicesPerLine-1)
Writer->writeLineBreak();
Writer->writeClosingTag(L"indices");
Writer->writeLineBreak();
// close buffer tag
Writer->writeClosingTag(L"buffer");
}
void CIrrMeshWriter::writeMaterial(const video::SMaterial& material)
{
// simply use irrlichts built-in attribute serialization capabilities here:
io::IAttributes* attributes =
VideoDriver->createAttributesFromMaterial(material);
if (attributes)
{
attributes->write(Writer, false, L"material");
attributes->drop();
}
}
} // end namespace
} // end namespace
#endif
|
paupawsan/Irrlicht
|
158cb20e5a9a5ae44276876de7b8b1c4c56ca929
|
cbp file provided by d3jake.
|
diff --git a/examples/23.SMeshHandling/SMeshHandling.cbp b/examples/23.SMeshHandling/SMeshHandling.cbp
new file mode 100644
index 0000000..b803657
--- /dev/null
+++ b/examples/23.SMeshHandling/SMeshHandling.cbp
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
+<CodeBlocks_project_file>
+ <FileVersion major="1" minor="6" />
+ <Project>
+ <Option title="Irrlicht Example 23 SMeshHandling" />
+ <Option pch_mode="2" />
+ <Option compiler="gcc" />
+ <Build>
+ <Target title="Windows">
+ <Option platforms="Windows;" />
+ <Option output="../../bin/Win32-gcc/SMeshHandling" prefix_auto="0" extension_auto="1" />
+ <Option type="1" />
+ <Option compiler="gcc" />
+ </Target>
+ <Target title="Linux">
+ <Option platforms="Unix;" />
+ <Option output="../../bin/Linux/SMeshHandling" prefix_auto="0" extension_auto="0" />
+ <Option type="1" />
+ <Option compiler="gcc" />
+ <Linker>
+ <Add library="Irrlicht" />
+ <Add directory="../../lib/Linux" />
+ </Linker>
+ </Target>
+ </Build>
+ <Compiler>
+ <Add directory="../../include" />
+ </Compiler>
+ <Linker>
+ <Add option="../../lib/Win32-gcc/libIrrlicht.a" />
+ </Linker>
+ <Unit filename="main.cpp" />
+ <Extensions>
+ <code_completion />
+ <envvars />
+ <debugger />
+ </Extensions>
+ </Project>
+</CodeBlocks_project_file>
|
paupawsan/Irrlicht
|
59277c3264933fbc41a00e4358b23675826c2557
|
Fix compilation of meshviewer example when _IRR_WCHAR_FILESYSTEM and UNICODE are set (found by greenya).
|
diff --git a/examples/09.Meshviewer/main.cpp b/examples/09.Meshviewer/main.cpp
index 4f6e824..4c4bc6c 100644
--- a/examples/09.Meshviewer/main.cpp
+++ b/examples/09.Meshviewer/main.cpp
@@ -1,685 +1,685 @@
/** Example 009 Mesh Viewer
This tutorial show how to create a more complex application with the engine.
We construct a simple mesh viewer using the user interface API and the
scene management of Irrlicht. The tutorial show how to create and use Buttons,
Windows, Toolbars, Menus, ComboBoxes, Tabcontrols, Editboxes, Images,
MessageBoxes, SkyBoxes, and how to parse XML files with the integrated XML
reader of the engine.
We start like in most other tutorials: Include all nesessary header files, add
a comment to let the engine be linked with the right .lib file in Visual
Studio, and declare some global variables. We also add two 'using namespace'
statements, so we do not need to write the whole names of all classes. In this
tutorial, we use a lot stuff from the gui namespace.
*/
#include <irrlicht.h>
#include "driverChoice.h"
using namespace irr;
using namespace gui;
#ifdef _MSC_VER
#pragma comment(lib, "Irrlicht.lib")
#endif
/*
Some global variables used later on
*/
IrrlichtDevice *Device = 0;
core::stringc StartUpModelFile;
core::stringw MessageText;
core::stringw Caption;
scene::ISceneNode* Model = 0;
scene::ISceneNode* SkyBox = 0;
bool Octree=false;
bool UseLight=false;
scene::ICameraSceneNode* Camera[2] = {0, 0};
// Values used to identify individual GUI elements
enum
{
GUI_ID_DIALOG_ROOT_WINDOW = 0x10000,
GUI_ID_X_SCALE,
GUI_ID_Y_SCALE,
GUI_ID_Z_SCALE,
GUI_ID_OPEN_MODEL,
GUI_ID_SET_MODEL_ARCHIVE,
GUI_ID_LOAD_AS_OCTREE,
GUI_ID_SKY_BOX_VISIBLE,
GUI_ID_TOGGLE_DEBUG_INFO,
GUI_ID_DEBUG_OFF,
GUI_ID_DEBUG_BOUNDING_BOX,
GUI_ID_DEBUG_NORMALS,
GUI_ID_DEBUG_SKELETON,
GUI_ID_DEBUG_WIRE_OVERLAY,
GUI_ID_DEBUG_HALF_TRANSPARENT,
GUI_ID_DEBUG_BUFFERS_BOUNDING_BOXES,
GUI_ID_DEBUG_ALL,
GUI_ID_MODEL_MATERIAL_SOLID,
GUI_ID_MODEL_MATERIAL_TRANSPARENT,
GUI_ID_MODEL_MATERIAL_REFLECTION,
GUI_ID_CAMERA_MAYA,
GUI_ID_CAMERA_FIRST_PERSON,
GUI_ID_POSITION_TEXT,
GUI_ID_ABOUT,
GUI_ID_QUIT,
GUI_ID_TEXTUREFILTER,
GUI_ID_SKIN_TRANSPARENCY,
GUI_ID_SKIN_ANIMATION_FPS,
GUI_ID_BUTTON_SET_SCALE,
GUI_ID_BUTTON_SCALE_MUL10,
GUI_ID_BUTTON_SCALE_DIV10,
GUI_ID_BUTTON_OPEN_MODEL,
GUI_ID_BUTTON_SHOW_ABOUT,
GUI_ID_BUTTON_SHOW_TOOLBOX,
GUI_ID_BUTTON_SELECT_ARCHIVE,
// And some magic numbers
MAX_FRAMERATE = 1000,
DEFAULT_FRAMERATE = 30
};
/*
Toggle between various cameras
*/
void setActiveCamera(scene::ICameraSceneNode* newActive)
{
if (0 == Device)
return;
scene::ICameraSceneNode * active = Device->getSceneManager()->getActiveCamera();
active->setInputReceiverEnabled(false);
newActive->setInputReceiverEnabled(true);
Device->getSceneManager()->setActiveCamera(newActive);
}
/*
Set the skin transparency by changing the alpha values of all skin-colors
*/
void SetSkinTransparency(s32 alpha, irr::gui::IGUISkin * skin)
{
for (s32 i=0; i<irr::gui::EGDC_COUNT ; ++i)
{
video::SColor col = skin->getColor((EGUI_DEFAULT_COLOR)i);
col.setAlpha(alpha);
skin->setColor((EGUI_DEFAULT_COLOR)i, col);
}
}
/*
Update the display of the model scaling
*/
void UpdateScaleInfo(scene::ISceneNode* model)
{
IGUIElement* toolboxWnd = Device->getGUIEnvironment()->getRootGUIElement()->getElementFromId(GUI_ID_DIALOG_ROOT_WINDOW, true);
if (!toolboxWnd)
return;
if (!model)
{
toolboxWnd->getElementFromId(GUI_ID_X_SCALE, true)->setText( L"-" );
toolboxWnd->getElementFromId(GUI_ID_Y_SCALE, true)->setText( L"-" );
toolboxWnd->getElementFromId(GUI_ID_Z_SCALE, true)->setText( L"-" );
}
else
{
core::vector3df scale = model->getScale();
toolboxWnd->getElementFromId(GUI_ID_X_SCALE, true)->setText( core::stringw(scale.X).c_str() );
toolboxWnd->getElementFromId(GUI_ID_Y_SCALE, true)->setText( core::stringw(scale.Y).c_str() );
toolboxWnd->getElementFromId(GUI_ID_Z_SCALE, true)->setText( core::stringw(scale.Z).c_str() );
}
}
/*
The three following functions do several stuff used by the mesh viewer. The
first function showAboutText() simply displays a messagebox with a caption and
a message text. The texts will be stored in the MessageText and Caption
variables at startup.
*/
void showAboutText()
{
// create modal message box with the text
// loaded from the xml file.
Device->getGUIEnvironment()->addMessageBox(
Caption.c_str(), MessageText.c_str());
}
/*
The second function loadModel() loads a model and displays it using an
addAnimatedMeshSceneNode and the scene manager. Nothing difficult. It also
displays a short message box, if the model could not be loaded.
*/
void loadModel(const c8* fn)
{
// modify the name if it a .pk3 file
- core::stringc filename(fn);
+ io::path filename(fn);
- core::stringc extension;
+ io::path extension;
core::getFileNameExtension(extension, filename);
extension.make_lower();
// if a texture is loaded apply it to the current model..
if (extension == ".jpg" || extension == ".pcx" ||
extension == ".png" || extension == ".ppm" ||
extension == ".pgm" || extension == ".pbm" ||
extension == ".psd" || extension == ".tga" ||
extension == ".bmp" || extension == ".wal" ||
extension == ".rgb" || extension == ".rgba")
{
video::ITexture * texture =
Device->getVideoDriver()->getTexture( filename );
if ( texture && Model )
{
// always reload texture
Device->getVideoDriver()->removeTexture(texture);
texture = Device->getVideoDriver()->getTexture( filename );
Model->setMaterialTexture(0, texture);
}
return;
}
// if a archive is loaded add it to the FileArchive..
else if (extension == ".pk3" || extension == ".zip" || extension == ".pak" || extension == ".npk")
{
Device->getFileSystem()->addFileArchive(filename.c_str());
return;
}
// load a model into the engine
if (Model)
Model->remove();
Model = 0;
if (extension==".irr")
{
core::array<scene::ISceneNode*> outNodes;
Device->getSceneManager()->loadScene(filename);
Device->getSceneManager()->getSceneNodesFromType(scene::ESNT_ANIMATED_MESH, outNodes);
if (outNodes.size())
Model = outNodes[0];
return;
}
scene::IAnimatedMesh* m = Device->getSceneManager()->getMesh( filename.c_str() );
if (!m)
{
// model could not be loaded
if (StartUpModelFile != filename)
Device->getGUIEnvironment()->addMessageBox(
Caption.c_str(), L"The model could not be loaded. " \
L"Maybe it is not a supported file format.");
return;
}
// set default material properties
if (Octree)
Model = Device->getSceneManager()->addOctreeSceneNode(m->getMesh(0));
else
{
scene::IAnimatedMeshSceneNode* animModel = Device->getSceneManager()->addAnimatedMeshSceneNode(m);
animModel->setAnimationSpeed(30);
Model = animModel;
}
Model->setMaterialFlag(video::EMF_LIGHTING, UseLight);
Model->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, UseLight);
// Model->setMaterialFlag(video::EMF_BACK_FACE_CULLING, false);
Model->setDebugDataVisible(scene::EDS_OFF);
// we need to uncheck the menu entries. would be cool to fake a menu event, but
// that's not so simple. so we do it brute force
gui::IGUIContextMenu* menu = (gui::IGUIContextMenu*)Device->getGUIEnvironment()->getRootGUIElement()->getElementFromId(GUI_ID_TOGGLE_DEBUG_INFO, true);
if (menu)
for(int item = 1; item < 6; ++item)
menu->setItemChecked(item, false);
UpdateScaleInfo(Model);
}
/*
Finally, the third function creates a toolbox window. In this simple mesh
viewer, this toolbox only contains a tab control with three edit boxes for
changing the scale of the displayed model.
*/
void createToolBox()
{
// remove tool box if already there
IGUIEnvironment* env = Device->getGUIEnvironment();
IGUIElement* root = env->getRootGUIElement();
IGUIElement* e = root->getElementFromId(GUI_ID_DIALOG_ROOT_WINDOW, true);
if (e)
e->remove();
// create the toolbox window
IGUIWindow* wnd = env->addWindow(core::rect<s32>(600,45,800,480),
false, L"Toolset", 0, GUI_ID_DIALOG_ROOT_WINDOW);
// create tab control and tabs
IGUITabControl* tab = env->addTabControl(
core::rect<s32>(2,20,800-602,480-7), wnd, true, true);
IGUITab* t1 = tab->addTab(L"Config");
// add some edit boxes and a button to tab one
env->addStaticText(L"Scale:",
core::rect<s32>(10,20,60,45), false, false, t1);
env->addStaticText(L"X:", core::rect<s32>(22,48,40,66), false, false, t1);
env->addEditBox(L"1.0", core::rect<s32>(40,46,130,66), true, t1, GUI_ID_X_SCALE);
env->addStaticText(L"Y:", core::rect<s32>(22,82,40,GUI_ID_OPEN_MODEL), false, false, t1);
env->addEditBox(L"1.0", core::rect<s32>(40,76,130,96), true, t1, GUI_ID_Y_SCALE);
env->addStaticText(L"Z:", core::rect<s32>(22,108,40,126), false, false, t1);
env->addEditBox(L"1.0", core::rect<s32>(40,106,130,126), true, t1, GUI_ID_Z_SCALE);
env->addButton(core::rect<s32>(10,134,85,165), t1, GUI_ID_BUTTON_SET_SCALE, L"Set");
// quick scale buttons
env->addButton(core::rect<s32>(65,20,95,40), t1, GUI_ID_BUTTON_SCALE_MUL10, L"* 10");
env->addButton(core::rect<s32>(100,20,130,40), t1, GUI_ID_BUTTON_SCALE_DIV10, L"* 0.1");
UpdateScaleInfo(Model);
// add transparency control
env->addStaticText(L"GUI Transparency Control:",
core::rect<s32>(10,200,150,225), true, false, t1);
IGUIScrollBar* scrollbar = env->addScrollBar(true,
core::rect<s32>(10,225,150,240), t1, GUI_ID_SKIN_TRANSPARENCY);
scrollbar->setMax(255);
scrollbar->setPos(255);
// add framerate control
env->addStaticText(L"Framerate:",
core::rect<s32>(10,240,150,265), true, false, t1);
scrollbar = env->addScrollBar(true,
core::rect<s32>(10,265,150,280), t1, GUI_ID_SKIN_ANIMATION_FPS);
scrollbar->setMax(MAX_FRAMERATE);
scrollbar->setMin(-MAX_FRAMERATE);
scrollbar->setPos(DEFAULT_FRAMERATE);
// bring irrlicht engine logo to front, because it
// now may be below the newly created toolbox
root->bringToFront(root->getElementFromId(666, true));
}
/*
To get all the events sent by the GUI Elements, we need to create an event
receiver. This one is really simple. If an event occurs, it checks the id of
the caller and the event type, and starts an action based on these values. For
example, if a menu item with id GUI_ID_OPEN_MODEL was selected, if opens a file-open-dialog.
*/
class MyEventReceiver : public IEventReceiver
{
public:
virtual bool OnEvent(const SEvent& event)
{
// Escape swaps Camera Input
if (event.EventType == EET_KEY_INPUT_EVENT &&
event.KeyInput.PressedDown == false)
{
if ( OnKeyUp(event.KeyInput.Key) )
return true;
}
if (event.EventType == EET_GUI_EVENT)
{
s32 id = event.GUIEvent.Caller->getID();
IGUIEnvironment* env = Device->getGUIEnvironment();
switch(event.GUIEvent.EventType)
{
case EGET_MENU_ITEM_SELECTED:
// a menu item was clicked
OnMenuItemSelected( (IGUIContextMenu*)event.GUIEvent.Caller );
break;
case EGET_FILE_SELECTED:
{
// load the model file, selected in the file open dialog
IGUIFileOpenDialog* dialog =
(IGUIFileOpenDialog*)event.GUIEvent.Caller;
loadModel(core::stringc(dialog->getFileName()).c_str());
}
break;
case EGET_SCROLL_BAR_CHANGED:
// control skin transparency
if (id == GUI_ID_SKIN_TRANSPARENCY)
{
const s32 pos = ((IGUIScrollBar*)event.GUIEvent.Caller)->getPos();
SetSkinTransparency(pos, env->getSkin());
}
// control animation speed
else if (id == GUI_ID_SKIN_ANIMATION_FPS)
{
const s32 pos = ((IGUIScrollBar*)event.GUIEvent.Caller)->getPos();
if (scene::ESNT_ANIMATED_MESH == Model->getType())
((scene::IAnimatedMeshSceneNode*)Model)->setAnimationSpeed((f32)pos);
}
break;
case EGET_COMBO_BOX_CHANGED:
// control anti-aliasing/filtering
if (id == GUI_ID_TEXTUREFILTER)
{
OnTextureFilterSelected( (IGUIComboBox*)event.GUIEvent.Caller );
}
break;
case EGET_BUTTON_CLICKED:
switch(id)
{
case GUI_ID_BUTTON_SET_SCALE:
{
// set scale
gui::IGUIElement* root = env->getRootGUIElement();
core::vector3df scale;
core::stringc s;
s = root->getElementFromId(GUI_ID_X_SCALE, true)->getText();
scale.X = (f32)atof(s.c_str());
s = root->getElementFromId(GUI_ID_Y_SCALE, true)->getText();
scale.Y = (f32)atof(s.c_str());
s = root->getElementFromId(GUI_ID_Z_SCALE, true)->getText();
scale.Z = (f32)atof(s.c_str());
if (Model)
Model->setScale(scale);
UpdateScaleInfo(Model);
}
break;
case GUI_ID_BUTTON_SCALE_MUL10:
if (Model)
Model->setScale(Model->getScale()*10.f);
UpdateScaleInfo(Model);
break;
case GUI_ID_BUTTON_SCALE_DIV10:
if (Model)
Model->setScale(Model->getScale()*0.1f);
UpdateScaleInfo(Model);
break;
case GUI_ID_BUTTON_OPEN_MODEL:
env->addFileOpenDialog(L"Please select a model file to open");
break;
case GUI_ID_BUTTON_SHOW_ABOUT:
showAboutText();
break;
case GUI_ID_BUTTON_SHOW_TOOLBOX:
createToolBox();
break;
case GUI_ID_BUTTON_SELECT_ARCHIVE:
env->addFileOpenDialog(L"Please select your game archive/directory");
break;
}
break;
default:
break;
}
}
return false;
}
/*
Handle key-up events
*/
bool OnKeyUp(irr::EKEY_CODE keyCode)
{
if (keyCode == irr::KEY_ESCAPE)
{
if (Device)
{
scene::ICameraSceneNode * camera =
Device->getSceneManager()->getActiveCamera();
if (camera)
{
camera->setInputReceiverEnabled( !camera->isInputReceiverEnabled() );
}
return true;
}
}
else if (keyCode == irr::KEY_F1)
{
if (Device)
{
IGUIElement* elem = Device->getGUIEnvironment()->getRootGUIElement()->getElementFromId(GUI_ID_POSITION_TEXT);
if (elem)
elem->setVisible(!elem->isVisible());
}
}
else if (keyCode == irr::KEY_KEY_M)
{
if (Device)
Device->minimizeWindow();
}
else if (keyCode == irr::KEY_KEY_L)
{
UseLight=!UseLight;
if (Model)
{
Model->setMaterialFlag(video::EMF_LIGHTING, UseLight);
Model->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, UseLight);
}
}
return false;
}
/*
Handle "menu item clicked" events.
*/
void OnMenuItemSelected( IGUIContextMenu* menu )
{
s32 id = menu->getItemCommandId(menu->getSelectedItem());
IGUIEnvironment* env = Device->getGUIEnvironment();
switch(id)
{
case GUI_ID_OPEN_MODEL: // FilOnButtonSetScalinge -> Open Model
env->addFileOpenDialog(L"Please select a model file to open");
break;
case GUI_ID_SET_MODEL_ARCHIVE: // File -> Set Model Archive
env->addFileOpenDialog(L"Please select your game archive/directory");
break;
case GUI_ID_LOAD_AS_OCTREE: // File -> LoadAsOctree
Octree = !Octree;
menu->setItemChecked(menu->getSelectedItem(), Octree);
break;
case GUI_ID_QUIT: // File -> Quit
Device->closeDevice();
break;
case GUI_ID_SKY_BOX_VISIBLE: // View -> Skybox
menu->setItemChecked(menu->getSelectedItem(), !menu->isItemChecked(menu->getSelectedItem()));
SkyBox->setVisible(!SkyBox->isVisible());
break;
case GUI_ID_DEBUG_OFF: // View -> Debug Information
menu->setItemChecked(menu->getSelectedItem()+1, false);
menu->setItemChecked(menu->getSelectedItem()+2, false);
menu->setItemChecked(menu->getSelectedItem()+3, false);
menu->setItemChecked(menu->getSelectedItem()+4, false);
menu->setItemChecked(menu->getSelectedItem()+5, false);
menu->setItemChecked(menu->getSelectedItem()+6, false);
if (Model)
Model->setDebugDataVisible(scene::EDS_OFF);
break;
case GUI_ID_DEBUG_BOUNDING_BOX: // View -> Debug Information
menu->setItemChecked(menu->getSelectedItem(), !menu->isItemChecked(menu->getSelectedItem()));
if (Model)
Model->setDebugDataVisible((scene::E_DEBUG_SCENE_TYPE)(Model->isDebugDataVisible()^scene::EDS_BBOX));
break;
case GUI_ID_DEBUG_NORMALS: // View -> Debug Information
menu->setItemChecked(menu->getSelectedItem(), !menu->isItemChecked(menu->getSelectedItem()));
if (Model)
Model->setDebugDataVisible((scene::E_DEBUG_SCENE_TYPE)(Model->isDebugDataVisible()^scene::EDS_NORMALS));
break;
case GUI_ID_DEBUG_SKELETON: // View -> Debug Information
menu->setItemChecked(menu->getSelectedItem(), !menu->isItemChecked(menu->getSelectedItem()));
if (Model)
Model->setDebugDataVisible((scene::E_DEBUG_SCENE_TYPE)(Model->isDebugDataVisible()^scene::EDS_SKELETON));
break;
case GUI_ID_DEBUG_WIRE_OVERLAY: // View -> Debug Information
menu->setItemChecked(menu->getSelectedItem(), !menu->isItemChecked(menu->getSelectedItem()));
if (Model)
Model->setDebugDataVisible((scene::E_DEBUG_SCENE_TYPE)(Model->isDebugDataVisible()^scene::EDS_MESH_WIRE_OVERLAY));
break;
case GUI_ID_DEBUG_HALF_TRANSPARENT: // View -> Debug Information
menu->setItemChecked(menu->getSelectedItem(), !menu->isItemChecked(menu->getSelectedItem()));
if (Model)
Model->setDebugDataVisible((scene::E_DEBUG_SCENE_TYPE)(Model->isDebugDataVisible()^scene::EDS_HALF_TRANSPARENCY));
break;
case GUI_ID_DEBUG_BUFFERS_BOUNDING_BOXES: // View -> Debug Information
menu->setItemChecked(menu->getSelectedItem(), !menu->isItemChecked(menu->getSelectedItem()));
if (Model)
Model->setDebugDataVisible((scene::E_DEBUG_SCENE_TYPE)(Model->isDebugDataVisible()^scene::EDS_BBOX_BUFFERS));
break;
case GUI_ID_DEBUG_ALL: // View -> Debug Information
menu->setItemChecked(menu->getSelectedItem()-1, true);
menu->setItemChecked(menu->getSelectedItem()-2, true);
menu->setItemChecked(menu->getSelectedItem()-3, true);
menu->setItemChecked(menu->getSelectedItem()-4, true);
menu->setItemChecked(menu->getSelectedItem()-5, true);
menu->setItemChecked(menu->getSelectedItem()-6, true);
if (Model)
Model->setDebugDataVisible(scene::EDS_FULL);
break;
case GUI_ID_ABOUT: // Help->About
showAboutText();
break;
case GUI_ID_MODEL_MATERIAL_SOLID: // View -> Material -> Solid
if (Model)
Model->setMaterialType(video::EMT_SOLID);
break;
case GUI_ID_MODEL_MATERIAL_TRANSPARENT: // View -> Material -> Transparent
if (Model)
Model->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
break;
case GUI_ID_MODEL_MATERIAL_REFLECTION: // View -> Material -> Reflection
if (Model)
Model->setMaterialType(video::EMT_SPHERE_MAP);
break;
case GUI_ID_CAMERA_MAYA:
setActiveCamera(Camera[0]);
break;
case GUI_ID_CAMERA_FIRST_PERSON:
setActiveCamera(Camera[1]);
break;
}
}
/*
Handle the event that one of the texture-filters was selected in the corresponding combobox.
*/
void OnTextureFilterSelected( IGUIComboBox* combo )
{
s32 pos = combo->getSelected();
switch (pos)
{
case 0:
if (Model)
{
Model->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
Model->setMaterialFlag(video::EMF_TRILINEAR_FILTER, false);
Model->setMaterialFlag(video::EMF_ANISOTROPIC_FILTER, false);
}
break;
case 1:
if (Model)
{
Model->setMaterialFlag(video::EMF_BILINEAR_FILTER, true);
Model->setMaterialFlag(video::EMF_TRILINEAR_FILTER, false);
}
break;
case 2:
if (Model)
{
Model->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
Model->setMaterialFlag(video::EMF_TRILINEAR_FILTER, true);
}
break;
case 3:
if (Model)
{
Model->setMaterialFlag(video::EMF_ANISOTROPIC_FILTER, true);
}
break;
case 4:
if (Model)
{
Model->setMaterialFlag(video::EMF_ANISOTROPIC_FILTER, false);
}
break;
}
}
};
/*
Most of the hard work is done. We only need to create the Irrlicht Engine
device and all the buttons, menus and toolbars. We start up the engine as
usual, using createDevice(). To make our application catch events, we set our
eventreceiver as parameter. As you can see, there is also a call to
IrrlichtDevice::setResizeable(). This makes the render window resizeable, which
is quite useful for a mesh viewer.
*/
int main(int argc, char* argv[])
{
// ask user for driver
video::E_DRIVER_TYPE driverType=driverChoiceConsole();
if (driverType==video::EDT_COUNT)
return 1;
// create device and exit if creation failed
MyEventReceiver receiver;
Device = createDevice(driverType, core::dimension2d<u32>(800, 600),
16, false, false, false, &receiver);
if (Device == 0)
return 1; // could not create selected driver.
Device->setResizable(true);
Device->setWindowCaption(L"Irrlicht Engine - Loading...");
video::IVideoDriver* driver = Device->getVideoDriver();
IGUIEnvironment* env = Device->getGUIEnvironment();
scene::ISceneManager* smgr = Device->getSceneManager();
smgr->getParameters()->setAttribute(scene::COLLADA_CREATE_SCENE_INSTANCES, true);
driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);
smgr->addLightSceneNode(0, core::vector3df(200,200,200),
video::SColorf(1.0f,1.0f,1.0f),2000);
smgr->setAmbientLight(video::SColorf(0.3f,0.3f,0.3f));
// add our media directory as "search path"
Device->getFileSystem()->addFolderFileArchive("../../media/");
/*
The next step is to read the configuration file. It is stored in the xml
format and looks a little bit like this:
@verbatim
<?xml version="1.0"?>
|
paupawsan/Irrlicht
|
f62f7f5ff25ebbecdeea8c0be380fff466c64ad7
|
Removed a variable and converted the win32 filelist creation to use TCHAR functions for automatic unicode/ansi conversion.
|
diff --git a/source/Irrlicht/CFileSystem.cpp b/source/Irrlicht/CFileSystem.cpp
index b07271d..62a85c2 100644
--- a/source/Irrlicht/CFileSystem.cpp
+++ b/source/Irrlicht/CFileSystem.cpp
@@ -94,750 +94,744 @@ CFileSystem::~CFileSystem()
}
}
//! opens a file for read access
IReadFile* CFileSystem::createAndOpenFile(const io::path& filename)
{
IReadFile* file = 0;
u32 i;
for (i=0; i< FileArchives.size(); ++i)
{
file = FileArchives[i]->createAndOpenFile(filename);
if (file)
return file;
}
// Create the file using an absolute path so that it matches
// the scheme used by CNullDriver::getTexture().
return createReadFile(getAbsolutePath(filename));
}
//! Creates an IReadFile interface for treating memory like a file.
IReadFile* CFileSystem::createMemoryReadFile(void* memory, s32 len,
const io::path& fileName, bool deleteMemoryWhenDropped)
{
if (!memory)
return 0;
else
return new CMemoryFile(memory, len, fileName, deleteMemoryWhenDropped);
}
//! Creates an IReadFile interface for reading files inside files
IReadFile* CFileSystem::createLimitReadFile(const io::path& fileName,
IReadFile* alreadyOpenedFile, long pos, long areaSize)
{
if (!alreadyOpenedFile)
return 0;
else
return new CLimitReadFile(alreadyOpenedFile, pos, areaSize, fileName);
}
//! Creates an IReadFile interface for treating memory like a file.
IWriteFile* CFileSystem::createMemoryWriteFile(void* memory, s32 len,
const io::path& fileName, bool deleteMemoryWhenDropped)
{
if (!memory)
return 0;
else
return new CMemoryFile(memory, len, fileName, deleteMemoryWhenDropped);
}
//! Opens a file for write access.
IWriteFile* CFileSystem::createAndWriteFile(const io::path& filename, bool append)
{
return createWriteFile(filename, append);
}
//! Adds an external archive loader to the engine.
void CFileSystem::addArchiveLoader(IArchiveLoader* loader)
{
if (!loader)
return;
loader->grab();
ArchiveLoader.push_back(loader);
}
//! move the hirarchy of the filesystem. moves sourceIndex relative up or down
bool CFileSystem::moveFileArchive(u32 sourceIndex, s32 relative)
{
bool r = false;
const s32 dest = (s32) sourceIndex + relative;
const s32 dir = relative < 0 ? -1 : 1;
const s32 sourceEnd = ((s32) FileArchives.size() ) - 1;
IFileArchive *t;
for (s32 s = (s32) sourceIndex;s != dest; s += dir)
{
if (s < 0 || s > sourceEnd || s + dir < 0 || s + dir > sourceEnd)
continue;
t = FileArchives[s + dir];
FileArchives[s + dir] = FileArchives[s];
FileArchives[s] = t;
r = true;
}
return r;
}
//! Adds an archive to the file system.
bool CFileSystem::addFileArchive(const io::path& filename, bool ignoreCase,
bool ignorePaths, E_FILE_ARCHIVE_TYPE archiveType,
const core::stringc& password)
{
IFileArchive* archive = 0;
bool ret = false;
u32 i;
// check if the archive was already loaded
for (i = 0; i < FileArchives.size(); ++i)
{
if (getAbsolutePath(filename) == FileArchives[i]->getFileList()->getPath())
{
if (password.size())
FileArchives[i]->Password=password;
return true;
}
}
// do we know what type it should be?
if (archiveType == EFAT_UNKNOWN || archiveType == EFAT_FOLDER)
{
// try to load archive based on file name
for (i = 0; i < ArchiveLoader.size(); ++i)
{
if (ArchiveLoader[i]->isALoadableFileFormat(filename))
{
archive = ArchiveLoader[i]->createArchive(filename, ignoreCase, ignorePaths);
if (archive)
break;
}
}
// try to load archive based on content
if (!archive)
{
io::IReadFile* file = createAndOpenFile(filename);
if (file)
{
for (i = 0; i < ArchiveLoader.size(); ++i)
{
file->seek(0);
if (ArchiveLoader[i]->isALoadableFileFormat(file))
{
file->seek(0);
archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
if (archive)
break;
}
}
file->drop();
}
}
}
else
{
// try to open archive based on archive loader type
io::IReadFile* file = 0;
for (i = 0; i < ArchiveLoader.size(); ++i)
{
if (ArchiveLoader[i]->isALoadableFileFormat(archiveType))
{
// attempt to open file
if (!file)
file = createAndOpenFile(filename);
// is the file open?
if (file)
{
// attempt to open archive
file->seek(0);
if (ArchiveLoader[i]->isALoadableFileFormat(file))
{
file->seek(0);
archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
if (archive)
break;
}
}
else
{
// couldn't open file
break;
}
}
}
// if open, close the file
if (file)
file->drop();
}
if (archive)
{
FileArchives.push_back(archive);
if (password.size())
archive->Password=password;
ret = true;
}
else
{
os::Printer::log("Could not create archive for", filename, ELL_ERROR);
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return ret;
}
//! removes an archive from the file system.
bool CFileSystem::removeFileArchive(u32 index)
{
bool ret = false;
if (index < FileArchives.size())
{
FileArchives[index]->drop();
FileArchives.erase(index);
ret = true;
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return ret;
}
//! removes an archive from the file system.
bool CFileSystem::removeFileArchive(const io::path& filename)
{
for (u32 i=0; i < FileArchives.size(); ++i)
{
if (filename == FileArchives[i]->getFileList()->getPath())
return removeFileArchive(i);
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
//! gets an archive
u32 CFileSystem::getFileArchiveCount() const
{
return FileArchives.size();
}
IFileArchive* CFileSystem::getFileArchive(u32 index)
{
return index < getFileArchiveCount() ? FileArchives[index] : 0;
}
//! Returns the string of the current working directory
const io::path& CFileSystem::getWorkingDirectory()
{
EFileSystemType type = FileSystemType;
if (type != FILESYSTEM_NATIVE)
{
type = FILESYSTEM_VIRTUAL;
}
else
{
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
// does not need this
#elif defined(_IRR_WINDOWS_API_)
fschar_t tmp[_MAX_PATH];
#if defined(_IRR_WCHAR_FILESYSTEM )
_wgetcwd(tmp, _MAX_PATH);
WorkingDirectory[FILESYSTEM_NATIVE] = tmp;
WorkingDirectory[FILESYSTEM_NATIVE].replace(L'\\', L'/');
#else
_getcwd(tmp, _MAX_PATH);
WorkingDirectory[FILESYSTEM_NATIVE] = tmp;
WorkingDirectory[FILESYSTEM_NATIVE].replace('\\', '/');
#endif
#endif
#if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
// getting the CWD is rather complex as we do not know the size
// so try it until the call was successful
// Note that neither the first nor the second parameter may be 0 according to POSIX
#if defined(_IRR_WCHAR_FILESYSTEM )
u32 pathSize=256;
wchar_t *tmpPath = new wchar_t[pathSize];
while ((pathSize < (1<<16)) && !(wgetcwd(tmpPath,pathSize)))
{
delete [] tmpPath;
pathSize *= 2;
tmpPath = new char[pathSize];
}
if (tmpPath)
{
WorkingDirectory[FILESYSTEM_NATIVE] = tmpPath;
delete [] tmpPath;
}
#else
u32 pathSize=256;
char *tmpPath = new char[pathSize];
while ((pathSize < (1<<16)) && !(getcwd(tmpPath,pathSize)))
{
delete [] tmpPath;
pathSize *= 2;
tmpPath = new char[pathSize];
}
if (tmpPath)
{
WorkingDirectory[FILESYSTEM_NATIVE] = tmpPath;
delete [] tmpPath;
}
#endif
#endif
WorkingDirectory[type].validate();
}
return WorkingDirectory[type];
}
//! Changes the current Working Directory to the given string.
bool CFileSystem::changeWorkingDirectoryTo(const io::path& newDirectory)
{
bool success=false;
if (FileSystemType != FILESYSTEM_NATIVE)
{
WorkingDirectory[FILESYSTEM_VIRTUAL] = newDirectory;
flattenFilename(WorkingDirectory[FILESYSTEM_VIRTUAL], "");
success = 1;
}
else
{
WorkingDirectory[FILESYSTEM_NATIVE] = newDirectory;
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
success = true;
#elif defined(_MSC_VER)
#if defined(_IRR_WCHAR_FILESYSTEM)
success=(_wchdir(newDirectory.c_str()) == 0);
#else
success=(_chdir(newDirectory.c_str()) == 0);
#endif
#else
success=(chdir(newDirectory.c_str()) == 0);
#endif
}
return success;
}
io::path CFileSystem::getAbsolutePath(const io::path& filename) const
{
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
return filename;
#elif defined(_IRR_WINDOWS_API_)
fschar_t *p=0;
fschar_t fpath[_MAX_PATH];
#if defined(_IRR_WCHAR_FILESYSTEM )
p = _wfullpath(fpath, filename.c_str(), _MAX_PATH);
core::stringw tmp(p);
tmp.replace(L'\\', L'/');
#else
p = _fullpath(fpath, filename.c_str(), _MAX_PATH);
core::stringc tmp(p);
tmp.replace('\\', '/');
#endif
return tmp;
#elif (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
c8* p=0;
c8 fpath[4096];
fpath[0]=0;
p = realpath(filename.c_str(), fpath);
if (!p)
{
// content in fpath is unclear at this point
if (!fpath[0]) // seems like fpath wasn't altered, use our best guess
{
io::path tmp(filename);
return flattenFilename(tmp);
}
else
return io::path(fpath);
}
if (filename[filename.size()-1]=='/')
return io::path(p)+"/";
else
return io::path(p);
#else
return io::path(filename);
#endif
}
//! returns the directory part of a filename, i.e. all until the first
//! slash or backslash, excluding it. If no directory path is prefixed, a '.'
//! is returned.
io::path CFileSystem::getFileDir(const io::path& filename) const
{
// find last forward or backslash
s32 lastSlash = filename.findLast('/');
const s32 lastBackSlash = filename.findLast('\\');
lastSlash = lastSlash > lastBackSlash ? lastSlash : lastBackSlash;
if ((u32)lastSlash < filename.size())
return filename.subString(0, lastSlash);
else
return ".";
}
//! returns the base part of a filename, i.e. all except for the directory
//! part. If no directory path is prefixed, the full name is returned.
io::path CFileSystem::getFileBasename(const io::path& filename, bool keepExtension) const
{
// find last forward or backslash
s32 lastSlash = filename.findLast('/');
const s32 lastBackSlash = filename.findLast('\\');
lastSlash = core::max_(lastSlash, lastBackSlash);
// get number of chars after last dot
s32 end = 0;
if (!keepExtension)
{
// take care to search only after last slash to check only for
// dots in the filename
end = filename.findLast('.');
if (end == -1 || end < lastSlash)
end=0;
else
end = filename.size()-end;
}
if ((u32)lastSlash < filename.size())
return filename.subString(lastSlash+1, filename.size()-lastSlash-1-end);
else if (end != 0)
return filename.subString(0, filename.size()-end);
else
return filename;
}
//! flatten a path and file name for example: "/you/me/../." becomes "/you"
io::path& CFileSystem::flattenFilename(io::path& directory, const io::path& root) const
{
directory.replace('\\', '/');
if (directory.lastChar() != '/')
directory.append('/');
io::path dir;
io::path subdir;
s32 lastpos = 0;
s32 pos = 0;
bool lastWasRealDir=false;
while ((pos = directory.findNext('/', lastpos)) >= 0)
{
subdir = directory.subString(lastpos, pos - lastpos + 1);
if (subdir == "../")
{
if (lastWasRealDir)
{
deletePathFromPath(dir, 2);
lastWasRealDir=(dir.size()!=0);
}
else
{
dir.append(subdir);
lastWasRealDir=false;
}
}
else if (subdir == "/")
{
dir = root;
}
else if (subdir != "./" )
{
dir.append(subdir);
lastWasRealDir=true;
}
lastpos = pos + 1;
}
directory = dir;
return directory;
}
//! Creates a list of files and directories in the current working directory
EFileSystemType CFileSystem::setFileListSystem(EFileSystemType listType)
{
EFileSystemType current = FileSystemType;
FileSystemType = listType;
return current;
}
//! Creates a list of files and directories in the current working directory
IFileList* CFileSystem::createFileList()
{
CFileList* r = 0;
io::path Path = getWorkingDirectory();
Path.replace('\\', '/');
if (Path.lastChar() != '/')
Path.append('/');
//! Construct from native filesystem
if (FileSystemType == FILESYSTEM_NATIVE)
{
- io::path fullPath;
// --------------------------------------------
//! Windows version
#ifdef _IRR_WINDOWS_API_
#if !defined ( _WIN32_WCE )
r = new CFileList(Path, true, false);
- struct _finddata_t c_file;
+ struct _tfinddata_t c_file;
long hFile;
- if( (hFile = _findfirst( "*", &c_file )) != -1L )
+ if( (hFile = _tfindfirst( __TEXT"*", &c_file )) != -1L )
{
do
{
- fullPath = Path + c_file.name;
-
- r->addItem(fullPath, c_file.size, (_A_SUBDIR & c_file.attrib) != 0, 0);
+ r->addItem(Path + c_file.name, c_file.size, (_A_SUBDIR & c_file.attrib) != 0, 0);
}
- while( _findnext( hFile, &c_file ) == 0 );
+ while( _tfindnext( hFile, &c_file ) == 0 );
_findclose( hFile );
}
#endif
//TODO add drives
//entry.Name = "E:\\";
//entry.isDirectory = true;
//Files.push_back(entry);
#endif
// --------------------------------------------
//! Linux version
#if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
r = new CFileList(Path, false, false);
r->addItem(Path + "..", 0, true, 0);
//! We use the POSIX compliant methods instead of scandir
DIR* dirHandle=opendir(Path.c_str());
if (dirHandle)
{
struct dirent *dirEntry;
while ((dirEntry=readdir(dirHandle)))
{
u32 size = 0;
bool isDirectory = false;
- fullPath = Path + dirEntry->d_name;
if((strcmp(dirEntry->d_name, ".")==0) ||
(strcmp(dirEntry->d_name, "..")==0))
{
continue;
}
struct stat buf;
if (stat(dirEntry->d_name, &buf)==0)
{
size = buf.st_size;
isDirectory = S_ISDIR(buf.st_mode);
}
#if !defined(_IRR_SOLARIS_PLATFORM_) && !defined(__CYGWIN__)
// only available on some systems
else
{
isDirectory = dirEntry->d_type == DT_DIR;
}
#endif
- r->addItem(fullPath, size, isDirectory, 0);
+ r->addItem(Path + dirEntry->d_name, size, isDirectory, 0);
}
closedir(dirHandle);
}
#endif
}
else
{
//! create file list for the virtual filesystem
r = new CFileList(Path, false, false);
//! add relative navigation
SFileListEntry e2;
SFileListEntry e3;
//! PWD
r->addItem(Path + ".", 0, true, 0);
//! parent
r->addItem(Path + "..", 0, true, 0);
//! merge archives
for (u32 i=0; i < FileArchives.size(); ++i)
{
const IFileList *merge = FileArchives[i]->getFileList();
for (u32 j=0; j < merge->getFileCount(); ++j)
{
if (core::isInSameDirectory(Path, merge->getFullFileName(j)) == 0)
{
- io::path fullPath = merge->getFullFileName(j);
- r->addItem(fullPath, merge->getFileSize(j), merge->isDirectory(j), 0);
+ r->addItem(merge->getFullFileName(j), merge->getFileSize(j), merge->isDirectory(j), 0);
}
}
}
-
}
if (r)
r->sort();
return r;
}
//! Creates an empty filelist
IFileList* CFileSystem::createEmptyFileList(const io::path& path, bool ignoreCase, bool ignorePaths)
{
return new CFileList(path, ignoreCase, ignorePaths);
}
//! determines if a file exists and would be able to be opened.
bool CFileSystem::existFile(const io::path& filename) const
{
for (u32 i=0; i < FileArchives.size(); ++i)
if (FileArchives[i]->getFileList()->findFile(filename)!=-1)
return true;
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
#if defined(_IRR_WCHAR_FILESYSTEM)
HANDLE hFile = CreateFileW(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
#else
HANDLE hFile = CreateFileW(core::stringw(filename).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
#endif
if (hFile == INVALID_HANDLE_VALUE)
return false;
else
{
CloseHandle(hFile);
return true;
}
#else
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
#if defined(_MSC_VER)
#if defined(_IRR_WCHAR_FILESYSTEM)
return (_waccess(filename.c_str(), 0) != -1);
#else
return (_access(filename.c_str(), 0) != -1);
#endif
#elif defined(F_OK)
return (access(filename.c_str(), F_OK) != -1);
#else
return (access(filename.c_str(), 0) != -1);
#endif
#endif
}
//! Creates a XML Reader from a file.
IXMLReader* CFileSystem::createXMLReader(const io::path& filename)
{
IReadFile* file = createAndOpenFile(filename);
if (!file)
return 0;
IXMLReader* reader = createXMLReader(file);
file->drop();
return reader;
}
//! Creates a XML Reader from a file.
IXMLReader* CFileSystem::createXMLReader(IReadFile* file)
{
if (!file)
return 0;
return createIXMLReader(file);
}
//! Creates a XML Reader from a file.
IXMLReaderUTF8* CFileSystem::createXMLReaderUTF8(const io::path& filename)
{
IReadFile* file = createAndOpenFile(filename);
if (!file)
return 0;
IXMLReaderUTF8* reader = createIXMLReaderUTF8(file);
file->drop();
return reader;
}
//! Creates a XML Reader from a file.
IXMLReaderUTF8* CFileSystem::createXMLReaderUTF8(IReadFile* file)
{
if (!file)
return 0;
return createIXMLReaderUTF8(file);
}
//! Creates a XML Writer from a file.
IXMLWriter* CFileSystem::createXMLWriter(const io::path& filename)
{
IWriteFile* file = createAndWriteFile(filename);
IXMLWriter* writer = createXMLWriter(file);
file->drop();
return writer;
}
//! Creates a XML Writer from a file.
IXMLWriter* CFileSystem::createXMLWriter(IWriteFile* file)
{
return new CXMLWriter(file);
}
//! creates a filesystem which is able to open files from the ordinary file system,
//! and out of zipfiles, which are able to be added to the filesystem.
IFileSystem* createFileSystem()
{
return new CFileSystem();
}
//! Creates a new empty collection of attributes, usable for serialization and more.
IAttributes* CFileSystem::createEmptyAttributes(video::IVideoDriver* driver)
{
return new CAttributes(driver);
}
} // end namespace irr
} // end namespace io
|
paupawsan/Irrlicht
|
b6c2ed4073d1348aa79c7d3133635e93c7d380fd
|
Example 14 should now link to opengl also in vc8 project file (seen by KakCAT)
|
diff --git a/examples/14.Win32Window/Win32Window_vc8.vcproj b/examples/14.Win32Window/Win32Window_vc8.vcproj
index 6759d2f..efbf43d 100644
--- a/examples/14.Win32Window/Win32Window_vc8.vcproj
+++ b/examples/14.Win32Window/Win32Window_vc8.vcproj
@@ -1,232 +1,232 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="8.00"
Name="14.Win32Window_vc8"
ProjectGUID="{772FBE05-D05A-467B-9842-BEC409EEA8D0}"
RootNamespace="Win32Window_vc8"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory=".\Debug"
IntermediateDirectory=".\Debug"
ConfigurationType="1"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TypeLibraryName=".\Debug/Win32Window.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="..\..\include"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
PrecompiledHeaderFile=".\Debug/Win32Window.pch"
AssemblerListingLocation=".\Debug/"
ObjectFile=".\Debug/"
ProgramDataBaseFileName=".\Debug/"
WarningLevel="3"
SuppressStartupBanner="true"
DebugInformationFormat="4"
CompileAs="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="_DEBUG"
Culture="3079"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
- AdditionalDependencies="kernel32.lib user32.lib gdi32.lib"
+ AdditionalDependencies="kernel32.lib user32.lib gdi32.lib opengl32.lib"
OutputFile="..\..\bin\Win32-VisualStudio\14.Win32Window.exe"
LinkIncremental="0"
SuppressStartupBanner="true"
AdditionalLibraryDirectories="..\..\lib\Win32-visualstudio"
GenerateDebugInformation="true"
ProgramDatabaseFile=".\Debug/Win32Window.pdb"
SubSystem="1"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory=".\Release"
IntermediateDirectory=".\Release"
ConfigurationType="1"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TypeLibraryName=".\Release/Win32Window.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\..\include"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
StringPooling="true"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
PrecompiledHeaderFile=".\Release/Win32Window.pch"
AssemblerListingLocation=".\Release/"
ObjectFile=".\Release/"
ProgramDataBaseFileName=".\Release/"
WarningLevel="3"
SuppressStartupBanner="true"
CompileAs="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG"
Culture="3079"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="..\..\bin\Win32-VisualStudio\14.Win32Window.exe"
LinkIncremental="0"
SuppressStartupBanner="true"
AdditionalLibraryDirectories="..\..\lib\Win32-visualstudio"
ProgramDatabaseFile=".\Release/Win32Window.pdb"
SubSystem="1"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<File
RelativePath="main.cpp"
>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
BasicRuntimeChecks="3"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
|
paupawsan/Irrlicht
|
473d2d9375cb2230aca1332be82d5b72fbc3fae3
|
Fix typo in comment. Fix allocation order for array.
|
diff --git a/source/Irrlicht/CD3D9Driver.cpp b/source/Irrlicht/CD3D9Driver.cpp
index 4efb4e2..ba415d0 100644
--- a/source/Irrlicht/CD3D9Driver.cpp
+++ b/source/Irrlicht/CD3D9Driver.cpp
@@ -2244,1025 +2244,1025 @@ void CD3D9Driver::setRenderStatesStencilShadowMode(bool zfail)
// unset last 3d material
if (CurrentRenderMode == ERM_3D &&
Material.MaterialType >= 0 && Material.MaterialType < (s32)MaterialRenderers.size())
MaterialRenderers[Material.MaterialType].Renderer->OnUnsetMaterial();
//pID3DDevice->SetRenderState(D3DRS_FOGENABLE, FALSE);
//pID3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
}
if (CurrentRenderMode != ERM_SHADOW_VOLUME_ZPASS && !zfail)
{
// USE THE ZPASS METHOD
pID3DDevice->SetRenderState( D3DRS_STENCILFUNC, D3DCMP_ALWAYS );
pID3DDevice->SetRenderState( D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP );
pID3DDevice->SetRenderState( D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP );
pID3DDevice->SetRenderState( D3DRS_STENCILREF, 0x1 );
pID3DDevice->SetRenderState( D3DRS_STENCILMASK, 0xffffffff );
pID3DDevice->SetRenderState( D3DRS_STENCILWRITEMASK, 0xffffffff );
pID3DDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE);
pID3DDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_ZERO );
pID3DDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_ONE );
}
else
if (CurrentRenderMode != ERM_SHADOW_VOLUME_ZFAIL && zfail)
{
// USE THE ZFAIL METHOD
pID3DDevice->SetRenderState( D3DRS_STENCILFUNC, D3DCMP_ALWAYS );
pID3DDevice->SetRenderState( D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP );
pID3DDevice->SetRenderState( D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP );
pID3DDevice->SetRenderState( D3DRS_STENCILPASS, D3DSTENCILOP_KEEP );
pID3DDevice->SetRenderState( D3DRS_STENCILREF, 0x0 );
pID3DDevice->SetRenderState( D3DRS_STENCILMASK, 0xffffffff );
pID3DDevice->SetRenderState( D3DRS_STENCILWRITEMASK, 0xffffffff );
pID3DDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
pID3DDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_ZERO );
pID3DDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_ONE );
}
CurrentRenderMode = zfail ? ERM_SHADOW_VOLUME_ZFAIL : ERM_SHADOW_VOLUME_ZPASS;
}
//! sets the needed renderstates
void CD3D9Driver::setRenderStatesStencilFillMode(bool alpha)
{
if (CurrentRenderMode != ERM_STENCIL_FILL || Transformation3DChanged)
{
core::matrix4 mat;
pID3DDevice->SetTransform(D3DTS_VIEW, &UnitMatrixD3D9);
pID3DDevice->SetTransform(D3DTS_WORLD, &UnitMatrixD3D9);
pID3DDevice->SetTransform(D3DTS_PROJECTION, &UnitMatrixD3D9);
pID3DDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
pID3DDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
pID3DDevice->SetRenderState(D3DRS_FOGENABLE, FALSE);
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(2, D3DTSS_COLOROP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(2, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(3, D3DTSS_COLOROP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(3, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetRenderState(D3DRS_STENCILREF, 0x1);
pID3DDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_LESSEQUAL);
//pID3DDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_GREATEREQUAL);
pID3DDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_KEEP );
pID3DDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP );
pID3DDevice->SetRenderState(D3DRS_STENCILMASK, 0xffffffff );
pID3DDevice->SetRenderState(D3DRS_STENCILWRITEMASK, 0xffffffff );
pID3DDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
Transformation3DChanged = false;
if (alpha)
{
pID3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE );
pID3DDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
pID3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
pID3DDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE );
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
pID3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
pID3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
}
else
{
pID3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE );
pID3DDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
pID3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
}
}
CurrentRenderMode = ERM_STENCIL_FILL;
}
//! Enable the 2d override material
void CD3D9Driver::enableMaterial2D(bool enable)
{
if (!enable)
CurrentRenderMode = ERM_NONE;
CNullDriver::enableMaterial2D(enable);
}
//! sets the needed renderstates
void CD3D9Driver::setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel)
{
if (!pID3DDevice)
return;
if (CurrentRenderMode != ERM_2D || Transformation3DChanged)
{
// unset last 3d material
if (CurrentRenderMode == ERM_3D)
{
if (static_cast<u32>(LastMaterial.MaterialType) < MaterialRenderers.size())
MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial();
}
if (!OverrideMaterial2DEnabled)
{
setBasicRenderStates(InitMaterial2D, LastMaterial, true);
LastMaterial=InitMaterial2D;
// fix everything that is wrongly set by InitMaterial2D default
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(2, D3DTSS_COLOROP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(2, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(3, D3DTSS_COLOROP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(3, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetRenderState( D3DRS_STENCILENABLE, FALSE );
}
pID3DDevice->SetTransform(D3DTS_WORLD, &UnitMatrixD3D9);
core::matrix4 m;
m.setTranslation(core::vector3df(-0.5f,-0.5f,0));
pID3DDevice->SetTransform(D3DTS_VIEW, (D3DMATRIX*)((void*)m.pointer()));
const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
m.buildProjectionMatrixOrthoLH(f32(renderTargetSize.Width), f32(-(s32)(renderTargetSize.Height)), -1.0, 1.0);
m.setTranslation(core::vector3df(-1,1,0));
pID3DDevice->SetTransform(D3DTS_PROJECTION, (D3DMATRIX*)((void*)m.pointer()));
Transformation3DChanged = false;
}
if (OverrideMaterial2DEnabled)
{
OverrideMaterial2D.Lighting=false;
OverrideMaterial2D.ZBuffer=ECFN_NEVER;
OverrideMaterial2D.ZWriteEnable=false;
setBasicRenderStates(OverrideMaterial2D, LastMaterial, false);
LastMaterial = OverrideMaterial2D;
}
u32 current2DSignature = 0;
current2DSignature |= alpha ? EC2D_ALPHA : 0;
current2DSignature |= texture ? EC2D_TEXTURE : 0;
current2DSignature |= alphaChannel ? EC2D_ALPHA_CHANNEL : 0;
if(CurrentRenderMode != ERM_2D || current2DSignature != Cached2DModeSignature)
{
if (texture)
{
setTransform(ETS_TEXTURE_0, core::IdentityMatrix);
if (alphaChannel)
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
if (alpha)
{
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
}
else
{
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
}
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
pID3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
pID3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
}
else
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
if (alpha)
{
pID3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
pID3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
pID3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
}
else
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
}
}
}
else
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
if (alpha)
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE );
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
pID3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
pID3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
}
else
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
}
}
}
CurrentRenderMode = ERM_2D;
Cached2DModeSignature = current2DSignature;
}
//! deletes all dynamic lights there are
void CD3D9Driver::deleteAllDynamicLights()
{
for (s32 i=0; i<LastSetLight+1; ++i)
pID3DDevice->LightEnable(i, false);
LastSetLight = -1;
CNullDriver::deleteAllDynamicLights();
}
//! adds a dynamic light
s32 CD3D9Driver::addDynamicLight(const SLight& dl)
{
CNullDriver::addDynamicLight(dl);
D3DLIGHT9 light;
switch (dl.Type)
{
case ELT_POINT:
light.Type = D3DLIGHT_POINT;
break;
case ELT_SPOT:
light.Type = D3DLIGHT_SPOT;
break;
case ELT_DIRECTIONAL:
light.Type = D3DLIGHT_DIRECTIONAL;
break;
}
light.Position = *(D3DVECTOR*)((void*)(&dl.Position));
light.Direction = *(D3DVECTOR*)((void*)(&dl.Direction));
light.Range = core::min_(dl.Radius, MaxLightDistance);
light.Falloff = dl.Falloff;
light.Diffuse = *(D3DCOLORVALUE*)((void*)(&dl.DiffuseColor));
light.Specular = *(D3DCOLORVALUE*)((void*)(&dl.SpecularColor));
light.Ambient = *(D3DCOLORVALUE*)((void*)(&dl.AmbientColor));
light.Attenuation0 = dl.Attenuation.X;
light.Attenuation1 = dl.Attenuation.Y;
light.Attenuation2 = dl.Attenuation.Z;
light.Theta = dl.InnerCone * 2.0f * core::DEGTORAD;
light.Phi = dl.OuterCone * 2.0f * core::DEGTORAD;
++LastSetLight;
if(D3D_OK == pID3DDevice->SetLight(LastSetLight, &light))
{
// I don't care if this succeeds
(void)pID3DDevice->LightEnable(LastSetLight, true);
return LastSetLight;
}
return -1;
}
//! Turns a dynamic light on or off
//! \param lightIndex: the index returned by addDynamicLight
//! \param turnOn: true to turn the light on, false to turn it off
void CD3D9Driver::turnLightOn(s32 lightIndex, bool turnOn)
{
if(lightIndex < 0 || lightIndex > LastSetLight)
return;
(void)pID3DDevice->LightEnable(lightIndex, turnOn);
}
//! returns the maximal amount of dynamic lights the device can handle
u32 CD3D9Driver::getMaximalDynamicLightAmount() const
{
return Caps.MaxActiveLights;
}
//! Sets the dynamic ambient light color. The default color is
//! (0,0,0,0) which means it is dark.
//! \param color: New color of the ambient light.
void CD3D9Driver::setAmbientLight(const SColorf& color)
{
if (!pID3DDevice)
return;
AmbientLight = color;
D3DCOLOR col = color.toSColor().color;
pID3DDevice->SetRenderState(D3DRS_AMBIENT, col);
}
//! \return Returns the name of the video driver. Example: In case of the DIRECT3D9
//! driver, it would return "Direct3D9.0".
const wchar_t* CD3D9Driver::getName() const
{
return L"Direct3D 9.0";
}
//! Draws a shadow volume into the stencil buffer. To draw a stencil shadow, do
//! this: Frist, draw all geometry. Then use this method, to draw the shadow
//! volume. Then, use IVideoDriver::drawStencilShadow() to visualize the shadow.
void CD3D9Driver::drawStencilShadowVolume(const core::vector3df* triangles, s32 count, bool zfail)
{
if (!StencilBuffer || !count)
return;
setRenderStatesStencilShadowMode(zfail);
if (!zfail)
{
// ZPASS Method
// Draw front-side of shadow volume in stencil/z only
pID3DDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW );
pID3DDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_INCRSAT);
pID3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST, count / 3, triangles, sizeof(core::vector3df));
// Now reverse cull order so front sides of shadow volume are written.
pID3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW );
pID3DDevice->SetRenderState( D3DRS_STENCILPASS, D3DSTENCILOP_DECRSAT);
pID3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST, count / 3, triangles, sizeof(core::vector3df));
}
else
{
// ZFAIL Method
// Draw front-side of shadow volume in stencil/z only
pID3DDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW );
pID3DDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_INCRSAT );
pID3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST, count / 3, triangles, sizeof(core::vector3df));
// Now reverse cull order so front sides of shadow volume are written.
pID3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW );
pID3DDevice->SetRenderState( D3DRS_STENCILZFAIL, D3DSTENCILOP_DECRSAT );
pID3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST, count / 3, triangles, sizeof(core::vector3df));
}
}
//! Fills the stencil shadow with color. After the shadow volume has been drawn
//! into the stencil buffer using IVideoDriver::drawStencilShadowVolume(), use this
//! to draw the color of the shadow.
void CD3D9Driver::drawStencilShadow(bool clearStencilBuffer, video::SColor leftUpEdge,
video::SColor rightUpEdge, video::SColor leftDownEdge, video::SColor rightDownEdge)
{
if (!StencilBuffer)
return;
S3DVertex vtx[4];
vtx[0] = S3DVertex(1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, leftUpEdge, 0.0f, 0.0f);
vtx[1] = S3DVertex(1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, rightUpEdge, 0.0f, 1.0f);
vtx[2] = S3DVertex(-1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, leftDownEdge, 1.0f, 0.0f);
vtx[3] = S3DVertex(-1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, rightDownEdge, 1.0f, 1.0f);
s16 indices[6] = {0,1,2,1,3,2};
setRenderStatesStencilFillMode(
leftUpEdge.getAlpha() < 255 ||
rightUpEdge.getAlpha() < 255 ||
leftDownEdge.getAlpha() < 255 ||
rightDownEdge.getAlpha() < 255);
setActiveTexture(0,0);
setVertexShader(EVT_STANDARD);
pID3DDevice->DrawIndexedPrimitiveUP(D3DPT_TRIANGLELIST, 0, 4, 2, &indices[0],
D3DFMT_INDEX16, &vtx[0], sizeof(S3DVertex));
if (clearStencilBuffer)
pID3DDevice->Clear( 0, NULL, D3DCLEAR_STENCIL,0, 1.0, 0);
}
//! Returns the maximum amount of primitives (mostly vertices) which
//! the device is able to render with one drawIndexedTriangleList
//! call.
u32 CD3D9Driver::getMaximalPrimitiveCount() const
{
return Caps.MaxPrimitiveCount;
}
//! Sets the fog mode.
void CD3D9Driver::setFog(SColor color, E_FOG_TYPE fogType, f32 start,
f32 end, f32 density, bool pixelFog, bool rangeFog)
{
CNullDriver::setFog(color, fogType, start, end, density, pixelFog, rangeFog);
if (!pID3DDevice)
return;
pID3DDevice->SetRenderState(D3DRS_FOGCOLOR, color.color);
pID3DDevice->SetRenderState(
pixelFog ? D3DRS_FOGTABLEMODE : D3DRS_FOGVERTEXMODE,
(fogType==EFT_FOG_LINEAR)? D3DFOG_LINEAR : (fogType==EFT_FOG_EXP)?D3DFOG_EXP:D3DFOG_EXP2);
if (fogType==EFT_FOG_LINEAR)
{
pID3DDevice->SetRenderState(D3DRS_FOGSTART, *(DWORD*)(&start));
pID3DDevice->SetRenderState(D3DRS_FOGEND, *(DWORD*)(&end));
}
else
pID3DDevice->SetRenderState(D3DRS_FOGDENSITY, *(DWORD*)(&density));
if(!pixelFog)
pID3DDevice->SetRenderState(D3DRS_RANGEFOGENABLE, rangeFog);
}
//! Draws a 3d line.
void CD3D9Driver::draw3DLine(const core::vector3df& start,
const core::vector3df& end, SColor color)
{
setVertexShader(EVT_STANDARD);
setRenderStates3DMode();
video::S3DVertex v[2];
v[0].Color = color;
v[1].Color = color;
v[0].Pos = start;
v[1].Pos = end;
pID3DDevice->DrawPrimitiveUP(D3DPT_LINELIST, 1, v, sizeof(S3DVertex));
}
//! resets the device
bool CD3D9Driver::reset()
{
u32 i;
os::Printer::log("Resetting D3D9 device.", ELL_INFORMATION);
for (i=0; i<Textures.size(); ++i)
{
if (Textures[i].Surface->isRenderTarget())
{
IDirect3DBaseTexture9* tex = ((CD3D9Texture*)(Textures[i].Surface))->getDX9Texture();
if (tex)
tex->Release();
}
}
for (i=0; i<DepthBuffers.size(); ++i)
{
if(DepthBuffers[i]->Surface)
DepthBuffers[i]->Surface->Release();
}
// this does not require a restore in the reset method, it's updated
// automatically in the next render cycle.
removeAllHardwareBuffers();
DriverWasReset=true;
HRESULT hr = pID3DDevice->Reset(&present);
// restore RTTs
for (i=0; i<Textures.size(); ++i)
{
if (Textures[i].Surface->isRenderTarget())
((CD3D9Texture*)(Textures[i].Surface))->createRenderTarget();
}
// restore screen depthbuffer
pID3DDevice->GetDepthStencilSurface(&(DepthBuffers[0]->Surface));
D3DSURFACE_DESC desc;
// restore other depth buffers
- // dpeth format is taken from main depth buffer
+ // depth format is taken from main depth buffer
DepthBuffers[0]->Surface->GetDesc(&desc);
// multisampling is taken from rendertarget
D3DSURFACE_DESC desc2;
for (i=1; i<DepthBuffers.size(); ++i)
{
for (u32 j=0; j<Textures.size(); ++j)
{
// all textures sharing this depth buffer must have the same setting
// so take first one
if (((CD3D9Texture*)(Textures[j].Surface))->DepthSurface==DepthBuffers[i])
{
((CD3D9Texture*)(Textures[j].Surface))->Texture->GetLevelDesc(0,&desc2);
break;
}
}
pID3DDevice->CreateDepthStencilSurface(DepthBuffers[i]->Size.Width,
DepthBuffers[i]->Size.Height,
desc.Format,
desc2.MultiSampleType,
desc2.MultiSampleQuality,
TRUE,
&(DepthBuffers[i]->Surface),
NULL);
}
if (FAILED(hr))
{
if (hr == D3DERR_DEVICELOST)
{
DeviceLost = true;
os::Printer::log("Resetting failed due to device lost.", ELL_WARNING);
}
#ifdef D3DERR_DEVICEREMOVED
else if (hr == D3DERR_DEVICEREMOVED)
{
os::Printer::log("Resetting failed due to device removed.", ELL_WARNING);
}
#endif
else if (hr == D3DERR_DRIVERINTERNALERROR)
{
os::Printer::log("Resetting failed due to internal error.", ELL_WARNING);
}
else if (hr == D3DERR_OUTOFVIDEOMEMORY)
{
os::Printer::log("Resetting failed due to out of memory.", ELL_WARNING);
}
else if (hr == D3DERR_DEVICENOTRESET)
{
os::Printer::log("Resetting failed due to not reset.", ELL_WARNING);
}
else if (hr == D3DERR_INVALIDCALL)
{
os::Printer::log("Resetting failed due to invalid call", "You need to release some more surfaces.", ELL_WARNING);
}
else
{
os::Printer::log("Resetting failed due to unknown reason.", core::stringc((int)hr).c_str(), ELL_WARNING);
}
return false;
}
DeviceLost = false;
ResetRenderStates = true;
LastVertexType = (E_VERTEX_TYPE)-1;
for (u32 i=0; i<MATERIAL_MAX_TEXTURES; ++i)
CurrentTexture[i] = 0;
setVertexShader(EVT_STANDARD);
setRenderStates3DMode();
setFog(FogColor, FogType, FogStart, FogEnd, FogDensity, PixelFog, RangeFog);
setAmbientLight(AmbientLight);
return true;
}
void CD3D9Driver::OnResize(const core::dimension2d<u32>& size)
{
if (!pID3DDevice)
return;
CNullDriver::OnResize(size);
present.BackBufferWidth = size.Width;
present.BackBufferHeight = size.Height;
reset();
}
//! Returns type of video driver
E_DRIVER_TYPE CD3D9Driver::getDriverType() const
{
return EDT_DIRECT3D9;
}
//! Returns the transformation set by setTransform
const core::matrix4& CD3D9Driver::getTransform(E_TRANSFORMATION_STATE state) const
{
return Matrices[state];
}
//! Sets a vertex shader constant.
void CD3D9Driver::setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
{
if (data)
pID3DDevice->SetVertexShaderConstantF(startRegister, data, constantAmount);
}
//! Sets a pixel shader constant.
void CD3D9Driver::setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
{
if (data)
pID3DDevice->SetPixelShaderConstantF(startRegister, data, constantAmount);
}
//! Sets a constant for the vertex shader based on a name.
bool CD3D9Driver::setVertexShaderConstant(const c8* name, const f32* floats, int count)
{
if (Material.MaterialType >= 0 && Material.MaterialType < (s32)MaterialRenderers.size())
{
CD3D9MaterialRenderer* r = (CD3D9MaterialRenderer*)MaterialRenderers[Material.MaterialType].Renderer;
return r->setVariable(true, name, floats, count);
}
return false;
}
//! Sets a constant for the pixel shader based on a name.
bool CD3D9Driver::setPixelShaderConstant(const c8* name, const f32* floats, int count)
{
if (Material.MaterialType >= 0 && Material.MaterialType < (s32)MaterialRenderers.size())
{
CD3D9MaterialRenderer* r = (CD3D9MaterialRenderer*)MaterialRenderers[Material.MaterialType].Renderer;
return r->setVariable(false, name, floats, count);
}
return false;
}
//! Adds a new material renderer to the VideoDriver, using pixel and/or
//! vertex shaders to render geometry.
s32 CD3D9Driver::addShaderMaterial(const c8* vertexShaderProgram,
const c8* pixelShaderProgram,
IShaderConstantSetCallBack* callback,
E_MATERIAL_TYPE baseMaterial, s32 userData)
{
s32 nr = -1;
CD3D9ShaderMaterialRenderer* r = new CD3D9ShaderMaterialRenderer(
pID3DDevice, this, nr, vertexShaderProgram, pixelShaderProgram,
callback, getMaterialRenderer(baseMaterial), userData);
r->drop();
return nr;
}
//! Adds a new material renderer to the VideoDriver, based on a high level shading
//! language.
s32 CD3D9Driver::addHighLevelShaderMaterial(
const c8* vertexShaderProgram,
const c8* vertexShaderEntryPointName,
E_VERTEX_SHADER_TYPE vsCompileTarget,
const c8* pixelShaderProgram,
const c8* pixelShaderEntryPointName,
E_PIXEL_SHADER_TYPE psCompileTarget,
const c8* geometryShaderProgram,
const c8* geometryShaderEntryPointName,
E_GEOMETRY_SHADER_TYPE gsCompileTarget,
scene::E_PRIMITIVE_TYPE inType, scene::E_PRIMITIVE_TYPE outType,
u32 verticesOut,
IShaderConstantSetCallBack* callback,
E_MATERIAL_TYPE baseMaterial, s32 userData)
{
s32 nr = -1;
CD3D9HLSLMaterialRenderer* hlsl = new CD3D9HLSLMaterialRenderer(
pID3DDevice, this, nr,
vertexShaderProgram,
vertexShaderEntryPointName,
vsCompileTarget,
pixelShaderProgram,
pixelShaderEntryPointName,
psCompileTarget,
callback,
getMaterialRenderer(baseMaterial),
userData);
hlsl->drop();
return nr;
}
//! Returns a pointer to the IVideoDriver interface. (Implementation for
//! IMaterialRendererServices)
IVideoDriver* CD3D9Driver::getVideoDriver()
{
return this;
}
//! Creates a render target texture.
ITexture* CD3D9Driver::addRenderTargetTexture(const core::dimension2d<u32>& size,
const io::path& name,
const ECOLOR_FORMAT format)
{
ITexture* tex = new CD3D9Texture(this, size, name, format);
if (tex)
{
checkDepthBuffer(tex);
addTexture(tex);
tex->drop();
}
return tex;
}
//! Clears the ZBuffer.
void CD3D9Driver::clearZBuffer()
{
HRESULT hr = pID3DDevice->Clear( 0, NULL, D3DCLEAR_ZBUFFER, 0, 1.0, 0);
if (FAILED(hr))
os::Printer::log("CD3D9Driver clearZBuffer() failed.", ELL_WARNING);
}
//! Returns an image created from the last rendered frame.
IImage* CD3D9Driver::createScreenShot()
{
HRESULT hr;
// query the screen dimensions of the current adapter
D3DDISPLAYMODE displayMode;
pID3DDevice->GetDisplayMode(0, &displayMode);
// create the image surface to store the front buffer image [always A8R8G8B8]
LPDIRECT3DSURFACE9 lpSurface;
if (FAILED(hr = pID3DDevice->CreateOffscreenPlainSurface(displayMode.Width, displayMode.Height, D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &lpSurface, 0)))
return 0;
// read the front buffer into the image surface
if (FAILED(hr = pID3DDevice->GetFrontBufferData(0, lpSurface)))
{
lpSurface->Release();
return 0;
}
RECT clientRect;
{
POINT clientPoint;
clientPoint.x = 0;
clientPoint.y = 0;
ClientToScreen((HWND)getExposedVideoData().D3D9.HWnd, &clientPoint);
clientRect.left = clientPoint.x;
clientRect.top = clientPoint.y;
clientRect.right = clientRect.left + ScreenSize.Width;
clientRect.bottom = clientRect.top + ScreenSize.Height;
}
// lock our area of the surface
D3DLOCKED_RECT lockedRect;
if (FAILED(lpSurface->LockRect(&lockedRect, &clientRect, D3DLOCK_READONLY)))
{
lpSurface->Release();
return 0;
}
// this could throw, but we aren't going to worry about that case very much
IImage* newImage = new CImage(ECF_A8R8G8B8, ScreenSize);
// d3d pads the image, so we need to copy the correct number of bytes
u32* dP = (u32*)newImage->lock();
u8 * sP = (u8 *)lockedRect.pBits;
// If the display mode format doesn't promise anything about the Alpha value
// and it appears that it's not presenting 255, then we should manually
// set each pixel alpha value to 255.
if(D3DFMT_X8R8G8B8 == displayMode.Format && (0xFF000000 != (*dP & 0xFF000000)))
{
for (u32 y = 0; y < ScreenSize.Height; ++y)
{
for(u32 x = 0; x < ScreenSize.Width; ++x)
{
*dP = *((u32*)sP) | 0xFF000000;
dP++;
sP += 4;
}
sP += lockedRect.Pitch - (4 * ScreenSize.Width);
}
}
else
{
for (u32 y = 0; y < ScreenSize.Height; ++y)
{
memcpy(dP, sP, ScreenSize.Width * 4);
sP += lockedRect.Pitch;
dP += ScreenSize.Width;
}
}
newImage->unlock();
// we can unlock and release the surface
lpSurface->UnlockRect();
// release the image surface
lpSurface->Release();
// return status of save operation to caller
return newImage;
}
//! returns color format
ECOLOR_FORMAT CD3D9Driver::getColorFormat() const
{
return ColorFormat;
}
//! returns color format
D3DFORMAT CD3D9Driver::getD3DColorFormat() const
{
return D3DColorFormat;
}
// returns the current size of the screen or rendertarget
const core::dimension2d<u32>& CD3D9Driver::getCurrentRenderTargetSize() const
{
if ( CurrentRendertargetSize.Width == 0 )
return ScreenSize;
else
return CurrentRendertargetSize;
}
// Set/unset a clipping plane.
bool CD3D9Driver::setClipPlane(u32 index, const core::plane3df& plane, bool enable)
{
if (index >= MaxUserClipPlanes)
return false;
pID3DDevice->SetClipPlane(index, (const float*)&plane);
enableClipPlane(index, enable);
return true;
}
// Enable/disable a clipping plane.
void CD3D9Driver::enableClipPlane(u32 index, bool enable)
{
if (index >= MaxUserClipPlanes)
return;
DWORD renderstate;
pID3DDevice->GetRenderState(D3DRS_CLIPPLANEENABLE, &renderstate);
if (enable)
renderstate |= (1 << index);
else
renderstate &= ~(1 << index);
pID3DDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, renderstate);
}
D3DFORMAT CD3D9Driver::getD3DFormatFromColorFormat(ECOLOR_FORMAT format) const
{
switch(format)
{
case ECF_A1R5G5B5:
return D3DFMT_A1R5G5B5;
case ECF_R5G6B5:
return D3DFMT_R5G6B5;
case ECF_R8G8B8:
return D3DFMT_R8G8B8;
case ECF_A8R8G8B8:
return D3DFMT_A8R8G8B8;
// Floating Point formats. Thanks to Patryk "Nadro" Nadrowski.
case ECF_R16F:
return D3DFMT_R16F;
case ECF_G16R16F:
return D3DFMT_G16R16F;
case ECF_A16B16G16R16F:
return D3DFMT_A16B16G16R16F;
case ECF_R32F:
return D3DFMT_R32F;
case ECF_G32R32F:
return D3DFMT_G32R32F;
case ECF_A32B32G32R32F:
return D3DFMT_A32B32G32R32F;
}
return D3DFMT_UNKNOWN;
}
ECOLOR_FORMAT CD3D9Driver::getColorFormatFromD3DFormat(D3DFORMAT format) const
{
switch(format)
{
case D3DFMT_X1R5G5B5:
case D3DFMT_A1R5G5B5:
return ECF_A1R5G5B5;
case D3DFMT_A8B8G8R8:
case D3DFMT_A8R8G8B8:
case D3DFMT_X8R8G8B8:
return ECF_A8R8G8B8;
case D3DFMT_R5G6B5:
return ECF_R5G6B5;
case D3DFMT_R8G8B8:
return ECF_R8G8B8;
// Floating Point formats. Thanks to Patryk "Nadro" Nadrowski.
case D3DFMT_R16F:
return ECF_R16F;
case D3DFMT_G16R16F:
return ECF_G16R16F;
case D3DFMT_A16B16G16R16F:
return ECF_A16B16G16R16F;
case D3DFMT_R32F:
return ECF_R32F;
case D3DFMT_G32R32F:
return ECF_G32R32F;
case D3DFMT_A32B32G32R32F:
return ECF_A32B32G32R32F;
default:
return (ECOLOR_FORMAT)0;
};
}
void CD3D9Driver::checkDepthBuffer(ITexture* tex)
{
if (!tex)
return;
const core::dimension2du optSize = tex->getSize().getOptimalSize(
!queryFeature(EVDF_TEXTURE_NPOT),
!queryFeature(EVDF_TEXTURE_NSQUARE), true);
SDepthSurface* depth=0;
core::dimension2du destSize(0x7fffffff, 0x7fffffff);
for (u32 i=0; i<DepthBuffers.size(); ++i)
{
if ((DepthBuffers[i]->Size.Width>=optSize.Width) &&
(DepthBuffers[i]->Size.Height>=optSize.Height))
{
if ((DepthBuffers[i]->Size.Width<destSize.Width) &&
(DepthBuffers[i]->Size.Height<destSize.Height))
{
depth = DepthBuffers[i];
destSize=DepthBuffers[i]->Size;
}
}
}
if (!depth)
{
D3DSURFACE_DESC desc;
DepthBuffers[0]->Surface->GetDesc(&desc);
// the multisampling needs to match the RTT
D3DSURFACE_DESC desc2;
((CD3D9Texture*)tex)->Texture->GetLevelDesc(0,&desc2);
DepthBuffers.push_back(new SDepthSurface());
HRESULT hr=pID3DDevice->CreateDepthStencilSurface(optSize.Width,
optSize.Height,
desc.Format,
desc2.MultiSampleType,
desc2.MultiSampleQuality,
TRUE,
&(DepthBuffers.getLast()->Surface),
NULL);
if (SUCCEEDED(hr))
{
depth=DepthBuffers.getLast();
depth->Surface->GetDesc(&desc);
depth->Size.set(desc.Width, desc.Height);
}
else
{
if (hr == D3DERR_OUTOFVIDEOMEMORY)
os::Printer::log("Could not create DepthBuffer","out of video memory",ELL_ERROR);
else if( hr == E_OUTOFMEMORY )
os::Printer::log("Could not create DepthBuffer","out of memory",ELL_ERROR);
else
{
char buffer[128];
sprintf(buffer,"Could not create DepthBuffer of %ix%i",optSize.Width,optSize.Height);
os::Printer::log(buffer,ELL_ERROR);
}
DepthBuffers.erase(DepthBuffers.size()-1);
}
}
else
depth->grab();
static_cast<CD3D9Texture*>(tex)->DepthSurface=depth;
}
void CD3D9Driver::removeDepthSurface(SDepthSurface* depth)
{
for (u32 i=0; i<DepthBuffers.size(); ++i)
{
diff --git a/source/Irrlicht/Octree.h b/source/Irrlicht/Octree.h
index a22cf32..67f6100 100644
--- a/source/Irrlicht/Octree.h
+++ b/source/Irrlicht/Octree.h
@@ -1,388 +1,388 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_OCTREE_H_INCLUDED__
#define __C_OCTREE_H_INCLUDED__
#include "SViewFrustum.h"
#include "S3DVertex.h"
#include "aabbox3d.h"
#include "irrArray.h"
#include "CMeshBuffer.h"
/**
Flags for Octree
*/
//! use meshbuffer for drawing, enables VBO usage
#define OCTREE_USE_HARDWARE false
//! use visibility information together with VBOs
#define OCTREE_USE_VISIBILITY true
//! use bounding box or frustum for calculate polys
#define OCTREE_BOX_BASED true
//! bypass full invisible/visible test
#define OCTREE_PARENTTEST
namespace irr
{
//! template octree.
/** T must be a vertex type which has a member
called .Pos, which is a core::vertex3df position. */
template <class T>
class Octree
{
public:
struct SMeshChunk : public scene::CMeshBuffer<T>
{
SMeshChunk ()
: scene::CMeshBuffer<T>(), MaterialId(0)
{
scene::CMeshBuffer<T>::grab();
}
virtual ~SMeshChunk ()
{
//removeAllHardwareBuffers
}
s32 MaterialId;
};
struct SIndexChunk
{
core::array<u16> Indices;
s32 MaterialId;
};
struct SIndexData
{
u16* Indices;
s32 CurrentSize;
s32 MaxSize;
};
//! Constructor
Octree(const core::array<SMeshChunk>& meshes, s32 minimalPolysPerNode=128) :
IndexData(0), IndexDataCount(meshes.size()), NodeCount(0)
{
IndexData = new SIndexData[IndexDataCount];
// construct array of all indices
core::array<SIndexChunk>* indexChunks = new core::array<SIndexChunk>;
indexChunks->reallocate(meshes.size());
for (u32 i=0; i!=meshes.size(); ++i)
{
IndexData[i].CurrentSize = 0;
IndexData[i].MaxSize = meshes[i].Indices.size();
IndexData[i].Indices = new u16[IndexData[i].MaxSize];
indexChunks->push_back(SIndexChunk());
SIndexChunk& tic = indexChunks->getLast();
tic.MaterialId = meshes[i].MaterialId;
tic.Indices = meshes[i].Indices;
}
// create tree
Root = new OctreeNode(NodeCount, 0, meshes, indexChunks, minimalPolysPerNode);
}
//! returns all ids of polygons partially or fully enclosed
//! by this bounding box.
void calculatePolys(const core::aabbox3d<f32>& box)
{
for (u32 i=0; i!=IndexDataCount; ++i)
IndexData[i].CurrentSize = 0;
Root->getPolys(box, IndexData, 0);
}
//! returns all ids of polygons partially or fully enclosed
//! by a view frustum.
void calculatePolys(const scene::SViewFrustum& frustum)
{
for (u32 i=0; i!=IndexDataCount; ++i)
IndexData[i].CurrentSize = 0;
Root->getPolys(frustum, IndexData, 0);
}
const SIndexData* getIndexData() const
{
return IndexData;
}
u32 getIndexDataCount() const
{
return IndexDataCount;
}
u32 getNodeCount() const
{
return NodeCount;
}
//! for debug purposes only, collects the bounding boxes of the tree
void getBoundingBoxes(const core::aabbox3d<f32>& box,
core::array< const core::aabbox3d<f32>* >&outBoxes) const
{
Root->getBoundingBoxes(box, outBoxes);
}
//! destructor
~Octree()
{
for (u32 i=0; i<IndexDataCount; ++i)
delete [] IndexData[i].Indices;
delete [] IndexData;
delete Root;
}
private:
// private inner class
class OctreeNode
{
public:
// constructor
OctreeNode(u32& nodeCount, u32 currentdepth,
const core::array<SMeshChunk>& allmeshdata,
core::array<SIndexChunk>* indices,
s32 minimalPolysPerNode) : IndexData(0),
Depth(currentdepth+1)
{
++nodeCount;
u32 i; // new ISO for scoping problem with different compilers
for (i=0; i!=8; ++i)
Children[i] = 0;
if (indices->empty())
{
delete indices;
return;
}
bool found = false;
// find first point for bounding box
for (i=0; i<indices->size(); ++i)
{
if (!(*indices)[i].Indices.empty())
{
Box.reset(allmeshdata[i].Vertices[(*indices)[i].Indices[0]].Pos);
found = true;
break;
}
}
if (!found)
{
delete indices;
return;
}
s32 totalPrimitives = 0;
// now lets calculate our bounding box
for (i=0; i<indices->size(); ++i)
{
totalPrimitives += (*indices)[i].Indices.size();
for (u32 j=0; j<(*indices)[i].Indices.size(); ++j)
Box.addInternalPoint(allmeshdata[i].Vertices[(*indices)[i].Indices[j]].Pos);
}
core::vector3df middle = Box.getCenter();
core::vector3df edges[8];
Box.getEdges(edges);
// calculate all children
core::aabbox3d<f32> box;
core::array<u16> keepIndices;
if (totalPrimitives > minimalPolysPerNode && !Box.isEmpty())
for (u32 ch=0; ch!=8; ++ch)
{
box.reset(middle);
box.addInternalPoint(edges[ch]);
// create indices for child
bool added = false;
core::array<SIndexChunk>* cindexChunks = new core::array<SIndexChunk>;
cindexChunks->reallocate(allmeshdata.size());
for (i=0; i<allmeshdata.size(); ++i)
{
cindexChunks->push_back(SIndexChunk());
SIndexChunk& tic = cindexChunks->getLast();
tic.MaterialId = allmeshdata[i].MaterialId;
for (u32 t=0; t<(*indices)[i].Indices.size(); t+=3)
{
if (box.isPointInside(allmeshdata[i].Vertices[(*indices)[i].Indices[t]].Pos) &&
box.isPointInside(allmeshdata[i].Vertices[(*indices)[i].Indices[t+1]].Pos) &&
box.isPointInside(allmeshdata[i].Vertices[(*indices)[i].Indices[t+2]].Pos))
{
tic.Indices.push_back((*indices)[i].Indices[t]);
tic.Indices.push_back((*indices)[i].Indices[t+1]);
tic.Indices.push_back((*indices)[i].Indices[t+2]);
added = true;
}
else
{
keepIndices.push_back((*indices)[i].Indices[t]);
keepIndices.push_back((*indices)[i].Indices[t+1]);
keepIndices.push_back((*indices)[i].Indices[t+2]);
}
}
- memcpy( (*indices)[i].Indices.pointer(), keepIndices.pointer(), keepIndices.size()*sizeof(u16));
(*indices)[i].Indices.set_used(keepIndices.size());
+ memcpy( (*indices)[i].Indices.pointer(), keepIndices.pointer(), keepIndices.size()*sizeof(u16));
keepIndices.set_used(0);
}
if (added)
Children[ch] = new OctreeNode(nodeCount, Depth,
allmeshdata, cindexChunks, minimalPolysPerNode);
else
delete cindexChunks;
} // end for all possible children
IndexData = indices;
}
// destructor
~OctreeNode()
{
delete IndexData;
for (u32 i=0; i<8; ++i)
delete Children[i];
}
// returns all ids of polygons partially or full enclosed
// by this bounding box.
void getPolys(const core::aabbox3d<f32>& box, SIndexData* idxdata, u32 parentTest ) const
{
#if defined (OCTREE_PARENTTEST )
// if not full inside
if ( parentTest != 2 )
{
// partially inside ?
if (!Box.intersectsWithBox(box))
return;
// fully inside ?
parentTest = Box.isFullInside(box)?2:1;
}
#else
if (Box.intersectsWithBox(box))
#endif
{
const u32 cnt = IndexData->size();
u32 i; // new ISO for scoping problem in some compilers
for (i=0; i<cnt; ++i)
{
const s32 idxcnt = (*IndexData)[i].Indices.size();
if (idxcnt)
{
memcpy(&idxdata[i].Indices[idxdata[i].CurrentSize],
&(*IndexData)[i].Indices[0], idxcnt * sizeof(s16));
idxdata[i].CurrentSize += idxcnt;
}
}
for (i=0; i!=8; ++i)
if (Children[i])
Children[i]->getPolys(box, idxdata,parentTest);
}
}
// returns all ids of polygons partially or full enclosed
// by the view frustum.
void getPolys(const scene::SViewFrustum& frustum, SIndexData* idxdata,u32 parentTest) const
{
u32 i; // new ISO for scoping problem in some compilers
// if parent is fully inside, no further check for the children is needed
#if defined (OCTREE_PARENTTEST )
if ( parentTest != 2 )
#endif
{
#if defined (OCTREE_PARENTTEST )
parentTest = 2;
#endif
for (i=0; i!=scene::SViewFrustum::VF_PLANE_COUNT; ++i)
{
core::EIntersectionRelation3D r = Box.classifyPlaneRelation(frustum.planes[i]);
if ( r == core::ISREL3D_FRONT )
return;
#if defined (OCTREE_PARENTTEST )
if ( r == core::ISREL3D_CLIPPED )
parentTest = 1; // must still check childs
#endif
}
}
const u32 cnt = IndexData->size();
for (i=0; i!=cnt; ++i)
{
s32 idxcnt = (*IndexData)[i].Indices.size();
if (idxcnt)
{
memcpy(&idxdata[i].Indices[idxdata[i].CurrentSize],
&(*IndexData)[i].Indices[0], idxcnt * sizeof(s16));
idxdata[i].CurrentSize += idxcnt;
}
}
for (i=0; i!=8; ++i)
if (Children[i])
Children[i]->getPolys(frustum, idxdata,parentTest);
}
//! for debug purposes only, collects the bounding boxes of the node
void getBoundingBoxes(const core::aabbox3d<f32>& box,
core::array< const core::aabbox3d<f32>* >&outBoxes) const
{
if (Box.intersectsWithBox(box))
{
outBoxes.push_back(&Box);
for (u32 i=0; i!=8; ++i)
if (Children[i])
Children[i]->getBoundingBoxes(box, outBoxes);
}
}
private:
core::aabbox3df Box;
core::array<SIndexChunk>* IndexData;
OctreeNode* Children[8];
u32 Depth;
};
OctreeNode* Root;
SIndexData* IndexData;
u32 IndexDataCount;
u32 NodeCount;
};
} // end namespace
#endif
|
paupawsan/Irrlicht
|
d583856a5d55e436c7305e6f3788842c11496be8
|
Avoid crash on wrong bone ids.
|
diff --git a/source/Irrlicht/COgreMeshFileLoader.cpp b/source/Irrlicht/COgreMeshFileLoader.cpp
index 96c8064..b9cf716 100644
--- a/source/Irrlicht/COgreMeshFileLoader.cpp
+++ b/source/Irrlicht/COgreMeshFileLoader.cpp
@@ -269,1029 +269,1032 @@ bool COgreMeshFileLoader::readObjectChunk(io::IReadFile* file, ChunkData& parent
loadSkeleton(file, FileSystem->getFileBasename(file->getFileName(), false));
return true;
}
bool COgreMeshFileLoader::readGeometry(io::IReadFile* file, ChunkData& parent, OgreGeometry& geometry)
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Geometry");
#endif
readInt(file, parent, &geometry.NumVertex);
while(parent.read < parent.header.length)
{
ChunkData data;
readChunkData(file, data);
switch(data.header.id)
{
case COGRE_GEOMETRY_VERTEX_DECLARATION:
readVertexDeclaration(file, data, geometry);
break;
case COGRE_GEOMETRY_VERTEX_BUFFER:
readVertexBuffer(file, data, geometry);
break;
default:
// ignore chunk
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Skipping", core::stringc(data.header.id));
#endif
file->seek(data.header.length-data.read, true);
data.read += data.header.length-data.read;
}
parent.read += data.read;
}
return true;
}
bool COgreMeshFileLoader::readVertexDeclaration(io::IReadFile* file, ChunkData& parent, OgreGeometry& geometry)
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Vertex Declaration");
#endif
NumUV = 0;
while(parent.read < parent.header.length)
{
ChunkData data;
readChunkData(file, data);
switch(data.header.id)
{
case COGRE_GEOMETRY_VERTEX_ELEMENT:
{
geometry.Elements.push_back(OgreVertexElement());
OgreVertexElement& elem = geometry.Elements.getLast();
readShort(file, data, &elem.Source);
readShort(file, data, &elem.Type);
readShort(file, data, &elem.Semantic);
if (elem.Semantic == 7) //Tex coords
{
++NumUV;
}
readShort(file, data, &elem.Offset);
elem.Offset /= sizeof(f32);
readShort(file, data, &elem.Index);
}
break;
default:
// ignore chunk
file->seek(data.header.length-data.read, true);
data.read += data.header.length-data.read;
}
parent.read += data.read;
}
return true;
}
bool COgreMeshFileLoader::readVertexBuffer(io::IReadFile* file, ChunkData& parent, OgreGeometry& geometry)
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Vertex Buffer");
#endif
OgreVertexBuffer buf;
readShort(file, parent, &buf.BindIndex);
readShort(file, parent, &buf.VertexSize);
buf.VertexSize /= sizeof(f32);
ChunkData data;
readChunkData(file, data);
if (data.header.id == COGRE_GEOMETRY_VERTEX_BUFFER_DATA)
{
buf.Data.set_used(geometry.NumVertex*buf.VertexSize);
readFloat(file, data, buf.Data.pointer(), geometry.NumVertex*buf.VertexSize);
}
geometry.Buffers.push_back(buf);
parent.read += data.read;
return true;
}
bool COgreMeshFileLoader::readSubMesh(io::IReadFile* file, ChunkData& parent, OgreSubMesh& subMesh)
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Submesh");
#endif
readString(file, parent, subMesh.Material);
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("using material", subMesh.Material);
#endif
readBool(file, parent, subMesh.SharedVertices);
s32 numIndices;
readInt(file, parent, &numIndices);
subMesh.Indices.set_used(numIndices);
readBool(file, parent, subMesh.Indices32Bit);
if (subMesh.Indices32Bit)
readInt(file, parent, subMesh.Indices.pointer(), numIndices);
else
{
for (s32 i=0; i<numIndices; ++i)
{
u16 num;
readShort(file, parent, &num);
subMesh.Indices[i]=num;
}
}
while(parent.read < parent.header.length)
{
ChunkData data;
readChunkData(file, data);
switch(data.header.id)
{
case COGRE_GEOMETRY:
readGeometry(file, data, subMesh.Geometry);
break;
case COGRE_SUBMESH_OPERATION:
readShort(file, data, &subMesh.Operation);
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Submesh Operation",core::stringc(subMesh.Operation));
#endif
if (subMesh.Operation != 4)
os::Printer::log("Primitive type != trilist not yet implemented", ELL_WARNING);
break;
case COGRE_SUBMESH_TEXTURE_ALIAS:
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Submesh Texture Alias");
#endif
core::stringc texture, alias;
readString(file, data, texture);
readString(file, data, alias);
subMesh.TextureAliases.push_back(OgreTextureAlias(texture,alias));
}
break;
case COGRE_SUBMESH_BONE_ASSIGNMENT:
{
subMesh.BoneAssignments.push_back(OgreBoneAssignment());
readInt(file, data, &subMesh.BoneAssignments.getLast().VertexID);
readShort(file, data, &subMesh.BoneAssignments.getLast().BoneID);
readFloat(file, data, &subMesh.BoneAssignments.getLast().Weight);
}
break;
default:
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Skipping", core::stringc(data.header.id));
#endif
parent.read=parent.header.length;
file->seek(-(long)sizeof(ChunkHeader), true);
return true;
}
parent.read += data.read;
}
return true;
}
void COgreMeshFileLoader::composeMeshBufferMaterial(scene::IMeshBuffer* mb, const core::stringc& materialName)
{
video::SMaterial& material=mb->getMaterial();
for (u32 k=0; k<Materials.size(); ++k)
{
if ((materialName==Materials[k].Name)&&(Materials[k].Techniques.size())&&(Materials[k].Techniques[0].Passes.size()))
{
material=Materials[k].Techniques[0].Passes[0].Material;
if (Materials[k].Techniques[0].Passes[0].Texture.Filename.size())
{
if (FileSystem->existFile(Materials[k].Techniques[0].Passes[0].Texture.Filename))
material.setTexture(0, Driver->getTexture(Materials[k].Techniques[0].Passes[0].Texture.Filename));
else
material.setTexture(0, Driver->getTexture((CurrentlyLoadingFromPath+"/"+FileSystem->getFileBasename(Materials[k].Techniques[0].Passes[0].Texture.Filename))));
}
break;
}
}
}
scene::SMeshBuffer* COgreMeshFileLoader::composeMeshBuffer(const core::array<s32>& indices, const OgreGeometry& geom)
{
scene::SMeshBuffer *mb=new scene::SMeshBuffer();
u32 i;
mb->Indices.set_used(indices.size());
for (i=0; i<indices.size(); ++i)
mb->Indices[i]=indices[i];
mb->Vertices.set_used(geom.NumVertex);
for (i=0; i<geom.Elements.size(); ++i)
{
if (geom.Elements[i].Semantic==1) //Pos
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->Vertices[k].Color=mb->Material.DiffuseColor;
mb->Vertices[k].Pos.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]);
ePos += eSize;
}
}
}
}
if (geom.Elements[i].Semantic==4) //Normal
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->Vertices[k].Normal.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]);
ePos += eSize;
}
}
}
}
if (geom.Elements[i].Semantic==7) //TexCoord
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->Vertices[k].TCoords.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1]);
ePos += eSize;
}
}
}
}
}
return mb;
}
scene::SMeshBufferLightMap* COgreMeshFileLoader::composeMeshBufferLightMap(const core::array<s32>& indices, const OgreGeometry& geom)
{
scene::SMeshBufferLightMap *mb=new scene::SMeshBufferLightMap();
u32 i;
mb->Indices.set_used(indices.size());
for (i=0; i<indices.size(); ++i)
mb->Indices[i]=indices[i];
mb->Vertices.set_used(geom.NumVertex);
for (i=0; i<geom.Elements.size(); ++i)
{
if (geom.Elements[i].Semantic==1) //Pos
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->Vertices[k].Color=mb->Material.DiffuseColor;
mb->Vertices[k].Pos.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]);
ePos += eSize;
}
}
}
}
if (geom.Elements[i].Semantic==4) //Normal
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->Vertices[k].Normal.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]);
ePos += eSize;
}
}
}
}
if (geom.Elements[i].Semantic==7) //TexCoord
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->Vertices[k].TCoords.set(geom.Buffers[j].Data[ePos], geom.Buffers[j].Data[ePos+1]);
mb->Vertices[k].TCoords2.set(geom.Buffers[j].Data[ePos+2], geom.Buffers[j].Data[ePos+3]);
ePos += eSize;
}
}
}
}
}
return mb;
}
scene::IMeshBuffer* COgreMeshFileLoader::composeMeshBufferSkinned(scene::CSkinnedMesh& mesh, const core::array<s32>& indices, const OgreGeometry& geom)
{
scene::SSkinMeshBuffer *mb=mesh.addMeshBuffer();
if (NumUV>1)
{
mb->convertTo2TCoords();
mb->Vertices_2TCoords.set_used(geom.NumVertex);
}
else
mb->Vertices_Standard.set_used(geom.NumVertex);
u32 i;
mb->Indices.set_used(indices.size());
for (i=0; i<indices.size(); i+=3)
{
mb->Indices[i+0]=indices[i+2];
mb->Indices[i+1]=indices[i+1];
mb->Indices[i+2]=indices[i+0];
}
for (i=0; i<geom.Elements.size(); ++i)
{
if (geom.Elements[i].Semantic==1) //Pos
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
if (NumUV>1)
mb->Vertices_2TCoords[k].Color=mb->Material.DiffuseColor;
else
mb->Vertices_Standard[k].Color=mb->Material.DiffuseColor;
mb->getPosition(k).set(-geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]);
ePos += eSize;
}
}
}
}
if (geom.Elements[i].Semantic==4) //Normal
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->getNormal(k).set(-geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]);
ePos += eSize;
}
}
}
}
if (geom.Elements[i].Semantic==7) //TexCoord
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->getTCoords(k).set(geom.Buffers[j].Data[ePos], geom.Buffers[j].Data[ePos+1]);
if (NumUV>1)
mb->Vertices_2TCoords[k].TCoords2.set(geom.Buffers[j].Data[ePos+2], geom.Buffers[j].Data[ePos+3]);
ePos += eSize;
}
}
}
}
}
return mb;
}
void COgreMeshFileLoader::composeObject(void)
{
for (u32 i=0; i<Meshes.size(); ++i)
{
for (u32 j=0; j<Meshes[i].SubMeshes.size(); ++j)
{
IMeshBuffer* mb;
if (Meshes[i].SubMeshes[j].SharedVertices)
{
if (Skeleton.Bones.size())
{
mb = composeMeshBufferSkinned(*(CSkinnedMesh*)Mesh, Meshes[i].SubMeshes[j].Indices, Meshes[i].Geometry);
}
else if (NumUV < 2)
{
mb = composeMeshBuffer(Meshes[i].SubMeshes[j].Indices, Meshes[i].Geometry);
}
else
{
mb = composeMeshBufferLightMap(Meshes[i].SubMeshes[j].Indices, Meshes[i].Geometry);
}
}
else
{
if (Skeleton.Bones.size())
{
mb = composeMeshBufferSkinned(*(CSkinnedMesh*)Mesh, Meshes[i].SubMeshes[j].Indices, Meshes[i].SubMeshes[j].Geometry);
}
else if (NumUV < 2)
{
mb = composeMeshBuffer(Meshes[i].SubMeshes[j].Indices, Meshes[i].SubMeshes[j].Geometry);
}
else
{
mb = composeMeshBufferLightMap(Meshes[i].SubMeshes[j].Indices, Meshes[i].SubMeshes[j].Geometry);
}
}
if (mb != 0)
{
composeMeshBufferMaterial(mb, Meshes[i].SubMeshes[j].Material);
if (!Skeleton.Bones.size())
{
((SMesh*)Mesh)->addMeshBuffer(mb);
mb->drop();
}
}
}
}
if (Skeleton.Bones.size())
{
CSkinnedMesh* m = (CSkinnedMesh*)Mesh;
// Create Joints
for (u32 i=0; i<Skeleton.Bones.size(); ++i)
{
ISkinnedMesh::SJoint* joint = m->addJoint();
joint->Name=Skeleton.Bones[i].Name;
joint->LocalMatrix = Skeleton.Bones[i].Orientation.getMatrix();
if (Skeleton.Bones[i].Scale != core::vector3df(1,1,1))
{
core::matrix4 scaleMatrix;
scaleMatrix.setScale( Skeleton.Bones[i].Scale );
joint->LocalMatrix *= scaleMatrix;
}
joint->LocalMatrix.setTranslation( Skeleton.Bones[i].Position );
}
// Joints hierarchy
for (u32 i=0; i<Skeleton.Bones.size(); ++i)
{
if (Skeleton.Bones[i].Parent<m->getJointCount())
{
m->getAllJoints()[Skeleton.Bones[i].Parent]->Children.push_back(m->getAllJoints()[Skeleton.Bones[i].Handle]);
}
}
// Weights
u32 bufCount=0;
for (u32 i=0; i<Meshes.size(); ++i)
{
for (u32 j=0; j<Meshes[i].SubMeshes.size(); ++j)
{
for (u32 k=0; k<Meshes[i].SubMeshes[j].BoneAssignments.size(); ++k)
{
- OgreBoneAssignment& ba = Meshes[i].SubMeshes[j].BoneAssignments[k];
- ISkinnedMesh::SWeight* w = m->addWeight(m->getAllJoints()[ba.BoneID]);
- w->strength=ba.Weight;
- w->vertex_id=ba.VertexID;
- w->buffer_id=bufCount;
+ const OgreBoneAssignment& ba = Meshes[i].SubMeshes[j].BoneAssignments[k];
+ if (ba.BoneID<m->getJointCount())
+ {
+ ISkinnedMesh::SWeight* w = m->addWeight(m->getAllJoints()[ba.BoneID]);
+ w->strength=ba.Weight;
+ w->vertex_id=ba.VertexID;
+ w->buffer_id=bufCount;
+ }
}
++bufCount;
}
}
for (u32 i=0; i<Skeleton.Animations.size(); ++i)
{
for (u32 j=0; j<Skeleton.Animations[i].Keyframes.size(); ++j)
{
OgreKeyframe& frame = Skeleton.Animations[i].Keyframes[j];
ISkinnedMesh::SJoint* keyjoint = m->getAllJoints()[frame.BoneID];
ISkinnedMesh::SPositionKey* poskey = m->addPositionKey(keyjoint);
poskey->frame=frame.Time*25;
poskey->position=keyjoint->LocalMatrix.getTranslation()+frame.Position;
ISkinnedMesh::SRotationKey* rotkey = m->addRotationKey(keyjoint);
rotkey->frame=frame.Time*25;
rotkey->rotation=core::quaternion(keyjoint->LocalMatrix)*frame.Orientation;
ISkinnedMesh::SScaleKey* scalekey = m->addScaleKey(keyjoint);
scalekey->frame=frame.Time*25;
scalekey->scale=frame.Scale;
}
}
m->finalize();
}
}
void COgreMeshFileLoader::getMaterialToken(io::IReadFile* file, core::stringc& token, bool noNewLine)
{
bool parseString=false;
c8 c=0;
token = "";
if (file->getPos() >= file->getSize())
return;
file->read(&c, sizeof(c8));
// search for word beginning
while ( core::isspace(c) && (file->getPos() < file->getSize()))
{
if (noNewLine && c=='\n')
{
file->seek(-1, true);
return;
}
file->read(&c, sizeof(c8));
}
// check if we read a string
if (c=='"')
{
parseString = true;
file->read(&c, sizeof(c8));
}
do
{
if (c=='/')
{
file->read(&c, sizeof(c8));
// check for comments, cannot be part of strings
if (!parseString && (c=='/'))
{
// skip comments
while(c!='\n')
file->read(&c, sizeof(c8));
if (!token.size())
{
// if we start with a comment we need to skip
// following whitespaces, so restart
getMaterialToken(file, token, noNewLine);
return;
}
else
{
// else continue with next character
file->read(&c, sizeof(c8));
continue;
}
}
else
{
// else append first slash and check if second char
// ends this token
token.append('/');
if ((!parseString && core::isspace(c)) ||
(parseString && (c=='"')))
return;
}
}
token.append(c);
file->read(&c, sizeof(c8));
// read until a token delimiter is found
}
while (((!parseString && !core::isspace(c)) || (parseString && (c!='"'))) &&
(file->getPos() < file->getSize()));
// we want to skip the last quotes of a string , but other chars might be the next
// token already.
if (!parseString)
file->seek(-1, true);
}
bool COgreMeshFileLoader::readColor(io::IReadFile* file, video::SColor& col)
{
core::stringc token;
getMaterialToken(file, token);
if (token!="vertexcolour")
{
video::SColorf col_f;
col_f.r=core::fast_atof(token.c_str());
getMaterialToken(file, token);
col_f.g=core::fast_atof(token.c_str());
getMaterialToken(file, token);
col_f.b=core::fast_atof(token.c_str());
getMaterialToken(file, token, true);
if (token.size())
col_f.a=core::fast_atof(token.c_str());
else
col_f.a=1.0f;
if ((col_f.r==0.0f)&&(col_f.g==0.0f)&&(col_f.b==0.0f))
col.set(255,255,255,255);
else
col=col_f.toSColor();
return false;
}
return true;
}
void COgreMeshFileLoader::readPass(io::IReadFile* file, OgreTechnique& technique)
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Pass");
#endif
core::stringc token;
technique.Passes.push_back(OgrePass());
OgrePass& pass=technique.Passes.getLast();
getMaterialToken(file, token); //open brace or name
if (token != "{")
getMaterialToken(file, token); //open brace
getMaterialToken(file, token);
if (token == "}")
return;
u32 inBlocks=1;
u32 textureUnit=0;
while(inBlocks)
{
if (token=="ambient")
pass.AmbientTokenColor=readColor(file, pass.Material.AmbientColor);
else if (token=="diffuse")
pass.DiffuseTokenColor=readColor(file, pass.Material.DiffuseColor);
else if (token=="specular")
{
pass.SpecularTokenColor=readColor(file, pass.Material.SpecularColor);
getMaterialToken(file, token);
pass.Material.Shininess=core::fast_atof(token.c_str());
}
else if (token=="emissive")
pass.EmissiveTokenColor=readColor(file, pass.Material.EmissiveColor);
else if (token=="scene_blend")
{ // TODO: Choose correct values
getMaterialToken(file, token);
if (token=="add")
pass.Material.MaterialType=video::EMT_TRANSPARENT_ADD_COLOR;
else if (token=="modulate")
pass.Material.MaterialType=video::EMT_SOLID;
else if (token=="alpha_blend")
pass.Material.MaterialType=video::EMT_TRANSPARENT_ALPHA_CHANNEL;
else if (token=="colour_blend")
pass.Material.MaterialType=video::EMT_TRANSPARENT_VERTEX_ALPHA;
else
getMaterialToken(file, token);
}
else if (token=="depth_check")
{
getMaterialToken(file, token);
if (token!="on")
pass.Material.ZBuffer=video::ECFN_NEVER;
}
else if (token=="depth_write")
{
getMaterialToken(file, token);
pass.Material.ZWriteEnable=(token=="on");
}
else if (token=="depth_func")
{
getMaterialToken(file, token); // Function name
if (token=="always_fail")
pass.Material.ZBuffer=video::ECFN_NEVER;
else if (token=="always_pass")
pass.Material.ZBuffer=video::ECFN_ALWAYS;
else if (token=="equal")
pass.Material.ZBuffer=video::ECFN_EQUAL;
else if (token=="greater")
pass.Material.ZBuffer=video::ECFN_GREATER;
else if (token=="greater_equal")
pass.Material.ZBuffer=video::ECFN_GREATEREQUAL;
else if (token=="less")
pass.Material.ZBuffer=video::ECFN_LESS;
else if (token=="less_equal")
pass.Material.ZBuffer=video::ECFN_LESSEQUAL;
else if (token=="not_equal")
pass.Material.ZBuffer=video::ECFN_NOTEQUAL;
}
else if (token=="normalise_normals")
{
getMaterialToken(file, token);
pass.Material.NormalizeNormals=(token=="on");
}
else if (token=="depth_bias")
{
getMaterialToken(file, token); // bias value
}
else if (token=="alpha_rejection")
{
getMaterialToken(file, token); // function name
getMaterialToken(file, token); // value
pass.Material.MaterialTypeParam=core::fast_atof(token.c_str());
}
else if (token=="alpha_to_coverage")
{
getMaterialToken(file, token);
if (token=="on")
pass.Material.AntiAliasing |= video::EAAM_ALPHA_TO_COVERAGE;
}
else if (token=="colour_write")
{
getMaterialToken(file, token);
pass.Material.ColorMask = (token=="on")?video::ECP_ALL:video::ECP_NONE;
}
else if (token=="cull_hardware")
{
getMaterialToken(file, token); // rotation name
}
else if (token=="cull_software")
{
getMaterialToken(file, token); // culling side
}
else if (token=="lighting")
{
getMaterialToken(file, token);
pass.Material.Lighting=(token=="on");
}
else if (token=="shading")
{
getMaterialToken(file, token);
// We take phong as gouraud
pass.Material.GouraudShading=(token!="flat");
}
else if (token=="polygon_mode")
{
getMaterialToken(file, token);
pass.Material.Wireframe=(token=="wireframe");
pass.Material.PointCloud=(token=="points");
}
else if (token=="max_lights")
{
getMaterialToken(file, token);
pass.MaxLights=strtol(token.c_str(),NULL,10);
}
else if (token=="point_size")
{
getMaterialToken(file, token);
pass.PointSize=core::fast_atof(token.c_str());
}
else if (token=="point_sprites")
{
getMaterialToken(file, token);
pass.PointSprites=(token=="on");
}
else if (token=="point_size_min")
{
getMaterialToken(file, token);
pass.PointSizeMin=strtol(token.c_str(),NULL,10);
}
else if (token=="point_size_max")
{
getMaterialToken(file, token);
pass.PointSizeMax=strtol(token.c_str(),NULL,10);
}
else if (token=="texture_unit")
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Texture unit");
#endif
getMaterialToken(file, token); //open brace
getMaterialToken(file, token);
while(token != "}")
{
if (token=="texture")
{
getMaterialToken(file, pass.Texture.Filename);
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Texture", pass.Texture.Filename.c_str());
#endif
getMaterialToken(file, pass.Texture.CoordsType, true);
getMaterialToken(file, pass.Texture.MipMaps, true);
getMaterialToken(file, pass.Texture.Alpha, true);
}
else if (token=="filtering")
{
getMaterialToken(file, token);
pass.Material.TextureLayer[textureUnit].AnisotropicFilter=0;
if (token=="point")
{
pass.Material.TextureLayer[textureUnit].BilinearFilter=false;
pass.Material.TextureLayer[textureUnit].TrilinearFilter=false;
getMaterialToken(file, token);
getMaterialToken(file, token);
}
else if (token=="linear")
{
getMaterialToken(file, token);
if (token=="point")
{
pass.Material.TextureLayer[textureUnit].BilinearFilter=false;
pass.Material.TextureLayer[textureUnit].TrilinearFilter=false;
getMaterialToken(file, token);
}
else
{
pass.Material.TextureLayer[textureUnit].BilinearFilter=true;
getMaterialToken(file, token);
pass.Material.TextureLayer[textureUnit].TrilinearFilter=(token=="linear");
}
}
else
{
pass.Material.TextureLayer[textureUnit].BilinearFilter=(token=="bilinear");
pass.Material.TextureLayer[textureUnit].TrilinearFilter=(token=="trilinear");
pass.Material.TextureLayer[textureUnit].AnisotropicFilter=(token=="anisotropic")?2:1;
}
}
else if (token=="max_anisotropy")
{
getMaterialToken(file, token);
pass.Material.TextureLayer[textureUnit].AnisotropicFilter=(u8)core::strtol10(token.c_str());
}
else if (token=="texture_alias")
{
getMaterialToken(file, pass.Texture.Alias);
}
else if (token=="mipmap_bias")
{
getMaterialToken(file, token);
pass.Material.TextureLayer[textureUnit].LODBias=(s8)core::fast_atof(token.c_str());
}
else if (token=="colour_op")
{ // TODO: Choose correct values
getMaterialToken(file, token);
if (token=="add")
pass.Material.MaterialType=video::EMT_TRANSPARENT_ADD_COLOR;
else if (token=="modulate")
pass.Material.MaterialType=video::EMT_SOLID;
else if (token=="alpha_blend")
pass.Material.MaterialType=video::EMT_TRANSPARENT_ALPHA_CHANNEL;
else if (token=="colour_blend")
pass.Material.MaterialType=video::EMT_TRANSPARENT_VERTEX_ALPHA;
else
getMaterialToken(file, token);
}
getMaterialToken(file, token);
}
++textureUnit;
}
else if (token=="shadow_caster_program_ref")
{
do
{
getMaterialToken(file, token);
} while (token != "}");
}
else if (token=="shadow_caster_vertex_program_ref")
{
do
{
getMaterialToken(file, token);
} while (token != "}");
}
else if (token=="vertex_program_ref")
{
do
{
getMaterialToken(file, token);
} while (token != "}");
}
//fog_override, iteration, point_size_attenuation
//not considered yet!
getMaterialToken(file, token);
if (token=="{")
++inBlocks;
else if (token=="}")
--inBlocks;
}
}
void COgreMeshFileLoader::readTechnique(io::IReadFile* file, OgreMaterial& mat)
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Technique");
#endif
core::stringc token;
mat.Techniques.push_back(OgreTechnique());
OgreTechnique& technique=mat.Techniques.getLast();
getMaterialToken(file, technique.Name); //open brace or name
if (technique.Name != "{")
getMaterialToken(file, token); //open brace
else
technique.Name=core::stringc((int)mat.Techniques.size());
getMaterialToken(file, token);
while (token != "}")
{
if (token == "pass")
readPass(file, technique);
else if (token == "scheme")
getMaterialToken(file, token);
else if (token == "lod_index")
getMaterialToken(file, token);
getMaterialToken(file, token);
}
}
void COgreMeshFileLoader::loadMaterials(io::IReadFile* meshFile)
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Load Materials");
#endif
core::stringc token;
io::IReadFile* file = 0;
io::path filename = FileSystem->getFileBasename(meshFile->getFileName(), false) + ".material";
if (FileSystem->existFile(filename))
file = FileSystem->createAndOpenFile(filename);
else
file = FileSystem->createAndOpenFile(FileSystem->getFileDir(meshFile->getFileName())+"/"+filename);
if (!file)
{
os::Printer::log("Could not load OGRE material", filename);
return;
}
getMaterialToken(file, token);
while (file->getPos() < file->getSize())
{
if ((token == "fragment_program") || (token == "vertex_program"))
{
// skip whole block
u32 blocks=1;
do
{
getMaterialToken(file, token);
} while (token != "{");
do
{
getMaterialToken(file, token);
if (token == "{")
++blocks;
else if (token == "}")
--blocks;
} while (blocks);
getMaterialToken(file, token);
continue;
}
if (token != "material")
{
if (token.trim().size())
os::Printer::log("Unknown material group", token.c_str());
break;
}
Materials.push_back(OgreMaterial());
OgreMaterial& mat = Materials.getLast();
getMaterialToken(file, mat.Name);
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Load Material", mat.Name.c_str());
#endif
getMaterialToken(file, token); //open brace
getMaterialToken(file, token);
while(token != "}")
{
if (token=="lod_distances") // can have several items
getMaterialToken(file, token);
else if (token=="receive_shadows")
{
getMaterialToken(file, token);
mat.ReceiveShadows=(token=="on");
}
else if (token=="transparency_casts_shadows")
{
getMaterialToken(file, token);
mat.TransparencyCastsShadows=(token=="on");
}
else if (token=="set_texture_alias")
{
getMaterialToken(file, token);
getMaterialToken(file, token);
}
else if (token=="technique")
readTechnique(file, mat);
getMaterialToken(file, token);
}
getMaterialToken(file, token);
}
|
paupawsan/Irrlicht
|
a05d980685988fffc535e4780ed289ad8d10eb21
|
Fix several places where "used" in core::string was used wrongly.
|
diff --git a/include/irrString.h b/include/irrString.h
index ebf84dd..ea05f82 100644
--- a/include/irrString.h
+++ b/include/irrString.h
@@ -398,729 +398,729 @@ public:
/** \return Length of the string's content in characters, excluding
the trailing NUL. */
u32 size() const
{
return used-1;
}
//! Returns character string
/** \return pointer to C-style NUL terminated string. */
const T* c_str() const
{
return array;
}
//! Makes the string lower case.
void make_lower()
{
for (u32 i=0; i<used; ++i)
array[i] = locale_lower ( array[i] );
}
//! Makes the string upper case.
void make_upper()
{
for (u32 i=0; i<used; ++i)
array[i] = locale_upper ( array[i] );
}
//! Compares the strings ignoring case.
/** \param other: Other string to compare.
\return True if the strings are equal ignoring case. */
bool equals_ignore_case(const string<T,TAlloc>& other) const
{
for(u32 i=0; array[i] && other[i]; ++i)
if (locale_lower( array[i]) != locale_lower(other[i]))
return false;
return used == other.used;
}
//! Compares the strings ignoring case.
/** \param other: Other string to compare.
\param sourcePos: where to start to compare in the string
\return True if the strings are equal ignoring case. */
bool equals_substring_ignore_case(const string<T,TAlloc>&other, const s32 sourcePos = 0 ) const
{
if ( (u32) sourcePos > used )
return false;
u32 i;
for( i=0; array[sourcePos + i] && other[i]; ++i)
if (locale_lower( array[sourcePos + i]) != locale_lower(other[i]))
return false;
return array[sourcePos + i] == 0 && other[i] == 0;
}
//! Compares the strings ignoring case.
/** \param other: Other string to compare.
\return True if this string is smaller ignoring case. */
bool lower_ignore_case(const string<T,TAlloc>& other) const
{
for(u32 i=0; array[i] && other.array[i]; ++i)
{
s32 diff = (s32) locale_lower ( array[i] ) - (s32) locale_lower ( other.array[i] );
if ( diff )
return diff < 0;
}
return used < other.used;
}
//! compares the first n characters of the strings
/** \param other Other string to compare.
\param n Number of characters to compare
\return True if the n first characters of both strings are equal. */
bool equalsn(const string<T,TAlloc>& other, u32 n) const
{
u32 i;
for(i=0; array[i] && other[i] && i < n; ++i)
if (array[i] != other[i])
return false;
// if one (or both) of the strings was smaller then they
// are only equal if they have the same length
return (i == n) || (used == other.used);
}
//! compares the first n characters of the strings
/** \param str Other string to compare.
\param n Number of characters to compare
\return True if the n first characters of both strings are equal. */
bool equalsn(const T* const str, u32 n) const
{
if (!str)
return false;
u32 i;
for(i=0; array[i] && str[i] && i < n; ++i)
if (array[i] != str[i])
return false;
// if one (or both) of the strings was smaller then they
// are only equal if they have the same length
return (i == n) || (array[i] == 0 && str[i] == 0);
}
//! Appends a character to this string
/** \param character: Character to append. */
void append(T character)
{
if (used + 1 > allocated)
reallocate(used + 1);
++used;
array[used-2] = character;
array[used-1] = 0;
}
//! Appends a char string to this string
/** \param other: Char string to append. */
void append(const T* const other)
{
if (!other)
return;
u32 len = 0;
const T* p = other;
while(*p)
{
++len;
++p;
}
if (used + len > allocated)
reallocate(used + len);
--used;
++len;
for (u32 l=0; l<len; ++l)
array[l+used] = *(other+l);
used += len;
}
//! Appends a string to this string
/** \param other: String to append. */
void append(const string<T,TAlloc>& other)
{
--used;
u32 len = other.size()+1;
if (used + len > allocated)
reallocate(used + len);
for (u32 l=0; l<len; ++l)
array[used+l] = other[l];
used += len;
}
//! Appends a string of the length l to this string.
/** \param other: other String to append to this string.
\param length: How much characters of the other string to add to this one. */
void append(const string<T,TAlloc>& other, u32 length)
{
if (other.size() < length)
{
append(other);
return;
}
if (used + length > allocated)
reallocate(used + length);
--used;
for (u32 l=0; l<length; ++l)
array[l+used] = other[l];
used += length;
// ensure proper termination
array[used]=0;
++used;
}
//! Reserves some memory.
/** \param count: Amount of characters to reserve. */
void reserve(u32 count)
{
if (count < allocated)
return;
reallocate(count);
}
//! finds first occurrence of character in string
/** \param c: Character to search for.
\return Position where the character has been found,
or -1 if not found. */
s32 findFirst(T c) const
{
for (u32 i=0; i<used; ++i)
if (array[i] == c)
return i;
return -1;
}
//! finds first occurrence of a character of a list in string
/** \param c: List of characters to find. For example if the method
should find the first occurrence of 'a' or 'b', this parameter should be "ab".
\param count: Amount of characters in the list. Usually,
this should be strlen(c)
\return Position where one of the characters has been found,
or -1 if not found. */
s32 findFirstChar(const T* const c, u32 count) const
{
if (!c)
return -1;
for (u32 i=0; i<used; ++i)
for (u32 j=0; j<count; ++j)
if (array[i] == c[j])
return i;
return -1;
}
//! Finds first position of a character not in a given list.
/** \param c: List of characters not to find. For example if the method
should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab".
\param count: Amount of characters in the list. Usually,
this should be strlen(c)
\return Position where the character has been found,
or -1 if not found. */
template <class B>
s32 findFirstCharNotInList(const B* const c, u32 count) const
{
for (u32 i=0; i<used-1; ++i)
{
u32 j;
for (j=0; j<count; ++j)
if (array[i] == c[j])
break;
if (j==count)
return i;
}
return -1;
}
//! Finds last position of a character not in a given list.
/** \param c: List of characters not to find. For example if the method
should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab".
\param count: Amount of characters in the list. Usually,
this should be strlen(c)
\return Position where the character has been found,
or -1 if not found. */
template <class B>
s32 findLastCharNotInList(const B* const c, u32 count) const
{
for (s32 i=(s32)(used-2); i>=0; --i)
{
u32 j;
for (j=0; j<count; ++j)
if (array[i] == c[j])
break;
if (j==count)
return i;
}
return -1;
}
//! finds next occurrence of character in string
/** \param c: Character to search for.
\param startPos: Position in string to start searching.
\return Position where the character has been found,
or -1 if not found. */
s32 findNext(T c, u32 startPos) const
{
for (u32 i=startPos; i<used; ++i)
if (array[i] == c)
return i;
return -1;
}
//! finds last occurrence of character in string
/** \param c: Character to search for.
\param start: start to search reverse ( default = -1, on end )
\return Position where the character has been found,
or -1 if not found. */
s32 findLast(T c, s32 start = -1) const
{
start = core::clamp ( start < 0 ? (s32)(used) - 1 : start, 0, (s32)(used) - 1 );
for (s32 i=start; i>=0; --i)
if (array[i] == c)
return i;
return -1;
}
//! finds last occurrence of a character of a list in string
/** \param c: List of strings to find. For example if the method
should find the last occurrence of 'a' or 'b', this parameter should be "ab".
\param count: Amount of characters in the list. Usually,
this should be strlen(c)
\return Position where one of the characters has been found,
or -1 if not found. */
s32 findLastChar(const T* const c, u32 count) const
{
if (!c)
return -1;
for (s32 i=used-1; i>=0; --i)
for (u32 j=0; j<count; ++j)
if (array[i] == c[j])
return i;
return -1;
}
//! finds another string in this string
/** \param str: Another string
\param start: Start position of the search
\return Positions where the string has been found,
or -1 if not found. */
template <class B>
s32 find(const B* const str, const u32 start = 0) const
{
if (str && *str)
{
u32 len = 0;
while (str[len])
++len;
if (len > used-1)
return -1;
for (u32 i=start; i<used-len; ++i)
{
u32 j=0;
while(str[j] && array[i+j] == str[j])
++j;
if (!str[j])
return i;
}
}
return -1;
}
//! Returns a substring
/** \param begin: Start of substring.
\param length: Length of substring. */
string<T,TAlloc> subString(u32 begin, s32 length) const
{
// if start after string
// or no proper substring length
if ((length <= 0) || (begin>=size()))
return string<T,TAlloc>("");
// clamp length to maximal value
if ((length+begin) > size())
length = size()-begin;
string<T,TAlloc> o;
o.reserve(length+1);
for (s32 i=0; i<length; ++i)
o.array[i] = array[i+begin];
o.array[length] = 0;
o.used = o.allocated;
return o;
}
//! Appends a character to this string
/** \param c Character to append. */
string<T,TAlloc>& operator += (T c)
{
append(c);
return *this;
}
//! Appends a char string to this string
/** \param c Char string to append. */
string<T,TAlloc>& operator += (const T* const c)
{
append(c);
return *this;
}
//! Appends a string to this string
/** \param other String to append. */
string<T,TAlloc>& operator += (const string<T,TAlloc>& other)
{
append(other);
return *this;
}
//! Appends a string representation of a number to this string
/** \param i Number to append. */
string<T,TAlloc>& operator += (const int i)
{
append(string<T,TAlloc>(i));
return *this;
}
//! Appends a string representation of a number to this string
/** \param i Number to append. */
string<T,TAlloc>& operator += (const unsigned int i)
{
append(string<T,TAlloc>(i));
return *this;
}
//! Appends a string representation of a number to this string
/** \param i Number to append. */
string<T,TAlloc>& operator += (const long i)
{
append(string<T,TAlloc>(i));
return *this;
}
//! Appends a string representation of a number to this string
/** \param i Number to append. */
string<T,TAlloc>& operator += (const unsigned long& i)
{
append(string<T,TAlloc>(i));
return *this;
}
//! Appends a string representation of a number to this string
/** \param i Number to append. */
string<T,TAlloc>& operator += (const double i)
{
append(string<T,TAlloc>(i));
return *this;
}
//! Appends a string representation of a number to this string
/** \param i Number to append. */
string<T,TAlloc>& operator += (const float i)
{
append(string<T,TAlloc>(i));
return *this;
}
//! Replaces all characters of a special type with another one
/** \param toReplace Character to replace.
\param replaceWith Character replacing the old one. */
void replace(T toReplace, T replaceWith)
{
for (u32 i=0; i<used; ++i)
if (array[i] == toReplace)
array[i] = replaceWith;
}
//! Removes characters from a string.
/** \param c: Character to remove. */
void remove(T c)
{
u32 pos = 0;
u32 found = 0;
for (u32 i=0; i<used; ++i)
{
if (array[i] == c)
{
++found;
continue;
}
array[pos++] = array[i];
}
used -= found;
- array[used] = 0;
+ array[used-1] = 0;
}
//! Removes a string from the string.
/** \param toRemove: String to remove. */
void remove(const string<T,TAlloc> toRemove)
{
u32 size = toRemove.size();
if ( size == 0 )
return;
u32 pos = 0;
u32 found = 0;
for (u32 i=0; i<used; ++i)
{
u32 j = 0;
while (j < size)
{
if (array[i + j] != toRemove[j])
break;
++j;
}
if (j == size)
{
found += size;
i += size - 1;
continue;
}
array[pos++] = array[i];
}
used -= found;
- array[used] = 0;
+ array[used-1] = 0;
}
//! Removes characters from a string.
/** \param characters: Characters to remove. */
void removeChars(const string<T,TAlloc> & characters)
{
u32 pos = 0;
u32 found = 0;
for (u32 i=0; i<used; ++i)
{
// Don't use characters.findFirst as it finds the \0,
// causing used to become incorrect.
bool docontinue = false;
for (u32 j=0; j<characters.size(); ++j)
{
if (characters[j] == array[i])
{
++found;
docontinue = true;
break;
}
}
if (docontinue)
continue;
array[pos++] = array[i];
}
used -= found;
- array[used] = 0;
+ array[used-1] = 0;
}
//! Trims the string.
/** Removes the specified characters (by default, Latin-1 whitespace)
from the begining and the end of the string. */
string<T,TAlloc>& trim(const string<T,TAlloc> & whitespace = " \t\n\r")
{
// find start and end of the substring without the specified characters
const s32 begin = findFirstCharNotInList(whitespace.c_str(), whitespace.used);
if (begin == -1)
return (*this="");
const s32 end = findLastCharNotInList(whitespace.c_str(), whitespace.used);
return (*this = subString(begin, (end +1) - begin));
}
//! Erases a character from the string.
/** May be slow, because all elements
following after the erased element have to be copied.
\param index: Index of element to be erased. */
void erase(u32 index)
{
_IRR_DEBUG_BREAK_IF(index>=used) // access violation
for (u32 i=index+1; i<used; ++i)
array[i-1] = array[i];
--used;
}
//! verify the existing string.
void validate()
{
// terminate on existing null
for (u32 i=0; i<allocated; ++i)
{
if (array[i] == 0)
{
used = i + 1;
return;
}
}
// terminate
if ( allocated > 0 )
{
- used = allocated - 1;
- array[used] = 0;
+ used = allocated;
+ array[used-1] = 0;
}
else
{
used = 0;
}
}
//! gets the last char of a string or null
T lastChar() const
{
return used > 1 ? array[used-2] : 0;
}
//! split string into parts.
/** This method will split a string at certain delimiter characters
into the container passed in as reference. The type of the container
has to be given as template parameter. It must provide a push_back and
a size method.
\param ret The result container
\param c C-style string of delimiter characters
\param count Number of delimiter characters
\param ignoreEmptyTokens Flag to avoid empty substrings in the result
container. If two delimiters occur without a character in between, an
empty substring would be placed in the result. If this flag is set,
only non-empty strings are stored.
\param keepSeparators Flag which allows to add the separator to the
result string. If this flag is true, the concatenation of the
substrings results in the original string. Otherwise, only the
characters between the delimiters are returned.
\return The number of resulting substrings
*/
template<class container>
u32 split(container& ret, const T* const c, u32 count=1, bool ignoreEmptyTokens=true, bool keepSeparators=false) const
{
if (!c)
return 0;
const u32 oldSize=ret.size();
u32 lastpos = 0;
bool lastWasSeparator = false;
for (u32 i=0; i<used; ++i)
{
bool foundSeparator = false;
for (u32 j=0; j<count; ++j)
{
if (array[i] == c[j])
{
if ((!ignoreEmptyTokens || i - lastpos != 0) &&
!lastWasSeparator)
ret.push_back(string<T,TAlloc>(&array[lastpos], i - lastpos));
foundSeparator = true;
lastpos = (keepSeparators ? i : i + 1);
break;
}
}
lastWasSeparator = foundSeparator;
}
if ((used - 1) > lastpos)
ret.push_back(string<T,TAlloc>(&array[lastpos], (used - 1) - lastpos));
return ret.size()-oldSize;
}
private:
//! Reallocate the array, make it bigger or smaller
void reallocate(u32 new_size)
{
T* old_array = array;
array = allocator.allocate(new_size); //new T[new_size];
allocated = new_size;
u32 amount = used < new_size ? used : new_size;
for (u32 i=0; i<amount; ++i)
array[i] = old_array[i];
if (allocated < used)
used = allocated;
allocator.deallocate(old_array); // delete [] old_array;
}
//--- member variables
T* array;
u32 allocated;
u32 used;
TAlloc allocator;
};
//! Typedef for character strings
typedef string<c8> stringc;
//! Typedef for wide character strings
typedef string<wchar_t> stringw;
} // end namespace core
} // end namespace irr
#endif
diff --git a/tests/tests-last-passed-at.txt b/tests/tests-last-passed-at.txt
index c43456d..2948117 100644
--- a/tests/tests-last-passed-at.txt
+++ b/tests/tests-last-passed-at.txt
@@ -1,4 +1,4 @@
-Tests finished. 52 tests of 52 passed.
-Compiled as DEBUG
-Test suite pass at GMT Sun Mar 28 16:24:25 2010
-
+Tests finished. 52 tests of 52 passed.
+Compiled as DEBUG
+Test suite pass at GMT Wed May 05 11:49:07 2010
+
diff --git a/tests/tests_vc9.vcproj b/tests/tests_vc9.vcproj
index d354132..1e874ba 100644
--- a/tests/tests_vc9.vcproj
+++ b/tests/tests_vc9.vcproj
@@ -1,400 +1,404 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9,00"
Name="tests"
ProjectGUID="{2A1DE18B-F678-4A94-A996-E848E20B2983}"
RootNamespace="tests"
TargetFrameworkVersion="131072"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="..\include"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
WarningLevel="3"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="..\lib\Win32-visualstudio\Irrlicht.lib"
OutputFile="..\bin\Win32-VisualStudio\$(ProjectName).exe"
GenerateDebugInformation="true"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
EnableIntrinsicFunctions="true"
AdditionalIncludeDirectories="..\include"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
WarningLevel="3"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="..\lib\Win32-visualstudio\Irrlicht.lib"
OutputFile="..\bin\Win32-VisualStudio\$(ProjectName).exe"
GenerateDebugInformation="true"
OptimizeReferences="2"
EnableCOMDATFolding="2"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\anti-aliasing.cpp"
>
</File>
<File
RelativePath=".\archiveReader.cpp"
>
</File>
<File
RelativePath=".\b3dAnimation.cpp"
>
</File>
<File
RelativePath=".\burningsVideo.cpp"
>
</File>
<File
RelativePath=".\collisionResponseAnimator.cpp"
>
</File>
+ <File
+ RelativePath=".\color.cpp"
+ >
+ </File>
<File
RelativePath=".\cursorSetVisible.cpp"
>
</File>
<File
RelativePath=".\disambiguateTextures.cpp"
>
</File>
<File
RelativePath=".\draw2DImage.cpp"
>
</File>
<File
RelativePath=".\drawPixel.cpp"
>
</File>
<File
RelativePath=".\drawRectOutline.cpp"
>
</File>
<File
RelativePath=".\enumerateImageManipulators.cpp"
>
</File>
<File
RelativePath=".\exports.cpp"
>
</File>
<File
RelativePath=".\fast_atof.cpp"
>
</File>
<File
RelativePath=".\filesystem.cpp"
>
</File>
<File
RelativePath=".\flyCircleAnimator.cpp"
>
</File>
<File
RelativePath=".\guiDisabledMenu.cpp"
>
</File>
<File
RelativePath=".\irrArray.cpp"
>
</File>
<File
RelativePath=".\irrCoreEquals.cpp"
>
</File>
<File
RelativePath=".\irrList.cpp"
>
</File>
<File
RelativePath=".\irrMap.cpp"
>
</File>
<File
RelativePath=".\irrString.cpp"
>
</File>
<File
RelativePath=".\lightMaps.cpp"
>
</File>
<File
RelativePath=".\line2dIntersectWith.cpp"
>
</File>
<File
RelativePath=".\loadTextures.cpp"
>
</File>
<File
RelativePath=".\main.cpp"
>
</File>
<File
RelativePath=".\makeColorKeyTexture.cpp"
>
</File>
<File
RelativePath=".\matrixOps.cpp"
>
</File>
<File
RelativePath=".\md2Animation.cpp"
>
</File>
<File
RelativePath=".\meshLoaders.cpp"
>
</File>
<File
RelativePath=".\meshTransform.cpp"
>
</File>
<File
RelativePath=".\planeMatrix.cpp"
>
</File>
<File
RelativePath=".\removeCustomAnimator.cpp"
>
</File>
<File
RelativePath=".\renderTargetTexture.cpp"
>
</File>
<File
RelativePath=".\sceneCollisionManager.cpp"
>
</File>
<File
RelativePath=".\sceneNodeAnimator.cpp"
>
</File>
<File
RelativePath=".\serializeAttributes.cpp"
>
</File>
<File
RelativePath=".\softwareDevice.cpp"
>
</File>
<File
RelativePath=".\terrainSceneNode.cpp"
>
</File>
<File
RelativePath=".\testaabbox.cpp"
>
</File>
<File
RelativePath=".\testDimension2d.cpp"
>
</File>
<File
RelativePath=".\testGeometryCreator.cpp"
>
</File>
<File
RelativePath=".\testQuaternion.cpp"
>
</File>
<File
RelativePath=".\testS3DVertex.cpp"
>
</File>
<File
RelativePath=".\testUtils.cpp"
>
</File>
<File
RelativePath=".\testVector2d.cpp"
>
</File>
<File
RelativePath=".\testVector3d.cpp"
>
</File>
<File
RelativePath=".\testXML.cpp"
>
</File>
<File
RelativePath=".\textureFeatures.cpp"
>
</File>
<File
RelativePath=".\textureRenderStates.cpp"
>
</File>
<File
RelativePath=".\timer.cpp"
>
</File>
<File
RelativePath=".\transparentAlphaChannelRef.cpp"
>
</File>
<File
RelativePath=".\vectorPositionDimension2d.cpp"
>
</File>
<File
RelativePath=".\writeImageToFile.cpp"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File
RelativePath=".\testUtils.h"
>
</File>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
|
paupawsan/Irrlicht
|
023857a1d2719dc03362c27f39b34d4ef47f98b6
|
Fix c::b project files on Win32 for examples 04 and 11 (thx to freetimecoder for finding)
|
diff --git a/examples/04.Movement/Movement.cbp b/examples/04.Movement/Movement.cbp
index fa322a0..4d3a517 100644
--- a/examples/04.Movement/Movement.cbp
+++ b/examples/04.Movement/Movement.cbp
@@ -1,56 +1,57 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_project_file>
<FileVersion major="1" minor="6" />
<Project>
<Option title="Irrlicht Example 04 Movement" />
<Option pch_mode="0" />
<Option compiler="gcc" />
<Build>
<Target title="Windows">
- <Option output="../../bin/gcc/Movement" prefix_auto="0" extension_auto="1" />
+ <Option output="..\..\bin\Win32-gcc\Movement" prefix_auto="0" extension_auto="1" />
<Option type="1" />
<Option compiler="gcc" />
<Option projectResourceIncludeDirsRelation="1" />
<Compiler>
<Add option="-W" />
<Add option="-g" />
<Add option="-D_IRR_STATIC_LIB_" />
</Compiler>
<Linker>
- <Add directory="../../lib/Win32-gcc" />
+ <Add directory="..\..\lib\Win32-gcc" />
</Linker>
</Target>
<Target title="Linux">
<Option platforms="Unix;" />
- <Option output="../../bin/Linux/Movement" prefix_auto="0" extension_auto="0" />
+ <Option output="..\..\bin\Linux\Movement" prefix_auto="0" extension_auto="0" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-W" />
<Add option="-g" />
</Compiler>
<Linker>
<Add library="Xxf86vm" />
<Add library="GL" />
- <Add directory="../../lib/Linux" />
+ <Add directory="..\..\lib\Linux" />
</Linker>
</Target>
</Build>
<VirtualTargets>
<Add alias="All" targets="Windows;" />
</VirtualTargets>
<Compiler>
<Add option="-W" />
<Add option="-g" />
- <Add directory="../../include" />
+ <Add directory="..\..\include" />
</Compiler>
<Linker>
<Add library="Irrlicht" />
</Linker>
<Unit filename="main.cpp" />
<Extensions>
<code_completion />
<debugger />
+ <envvars />
</Extensions>
</Project>
</CodeBlocks_project_file>
diff --git a/examples/11.PerPixelLighting/PerPixelLighting.cbp b/examples/11.PerPixelLighting/PerPixelLighting.cbp
index 955c126..29c18f4 100644
--- a/examples/11.PerPixelLighting/PerPixelLighting.cbp
+++ b/examples/11.PerPixelLighting/PerPixelLighting.cbp
@@ -1,55 +1,56 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_project_file>
<FileVersion major="1" minor="6" />
<Project>
<Option title="Irrlicht Example 11 Per-Pixel Lighting" />
<Option pch_mode="0" />
<Option compiler="gcc" />
<Build>
<Target title="Windows">
<Option platforms="Windows;" />
- <Option output="../../bin/gcc/PerPixelLighting" prefix_auto="0" extension_auto="1" />
+ <Option output="..\..\bin\Win32-gcc\PerPixelLighting" prefix_auto="0" extension_auto="1" />
<Option type="1" />
<Option compiler="gcc" />
<Option projectResourceIncludeDirsRelation="1" />
<Compiler>
- <Add option="-W" />
<Add option="-g" />
+ <Add option="-W" />
</Compiler>
+ <Linker>
+ <Add directory="..\..\lib\Win32-gcc" />
+ </Linker>
</Target>
<Target title="Linux">
<Option platforms="Unix;" />
- <Option output="../../bin/Linux/PerPixelLighting" prefix_auto="0" extension_auto="0" />
+ <Option output="..\..\bin\Linux\PerPixelLighting" prefix_auto="0" extension_auto="0" />
<Option type="1" />
<Option compiler="gcc" />
+ <Option projectResourceIncludeDirsRelation="1" />
<Compiler>
- <Add option="-W" />
<Add option="-g" />
- <Add option="-D_IRR_STATIC_LIB_" />
+ <Add option="-W" />
</Compiler>
<Linker>
- <Add library="Xxf86vm" />
- <Add library="GL" />
- <Add directory="../../lib/Linux" />
+ <Add directory="..\..\lib\Linux" />
</Linker>
</Target>
</Build>
<VirtualTargets>
<Add alias="All" targets="Windows;" />
</VirtualTargets>
<Compiler>
- <Add option="-W" />
<Add option="-g" />
- <Add directory="../../include" />
+ <Add option="-W" />
+ <Add directory="..\..\include" />
</Compiler>
<Linker>
<Add library="Irrlicht" />
- <Add directory="../../lib/gcc" />
</Linker>
<Unit filename="main.cpp" />
<Extensions>
<code_completion />
<debugger />
+ <envvars />
</Extensions>
</Project>
</CodeBlocks_project_file>
|
paupawsan/Irrlicht
|
e6ac6e838e803f7a802e4d0243bc8785d2cda497
|
Remove additional slash in pathnames in X-Loader (rev.2147 and rev.2074 both had independently fixed the same problem but in different ways, so we had one slash too much afterwards).
|
diff --git a/source/Irrlicht/CXMeshFileLoader.cpp b/source/Irrlicht/CXMeshFileLoader.cpp
index 23b5411..f87ff00 100644
--- a/source/Irrlicht/CXMeshFileLoader.cpp
+++ b/source/Irrlicht/CXMeshFileLoader.cpp
@@ -1,964 +1,963 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_X_LOADER_
#include "CXMeshFileLoader.h"
#include "os.h"
#include "fast_atof.h"
#include "coreutil.h"
#include "ISceneManager.h"
#include "IVideoDriver.h"
#include "IFileSystem.h"
#include "IReadFile.h"
#ifdef _DEBUG
#define _XREADER_DEBUG
#endif
//#define BETTER_MESHBUFFER_SPLITTING_FOR_X
namespace irr
{
namespace scene
{
//! Constructor
CXMeshFileLoader::CXMeshFileLoader(scene::ISceneManager* smgr, io::IFileSystem* fs)
: SceneManager(smgr), FileSystem(fs), AllJoints(0), AnimatedMesh(0),
Buffer(0), P(0), End(0), BinaryNumCount(0), Line(0),
CurFrame(0), MajorVersion(0), MinorVersion(0), BinaryFormat(false), FloatSize(0)
{
#ifdef _DEBUG
setDebugName("CXMeshFileLoader");
#endif
}
//! returns true if the file maybe is able to be loaded by this class
//! based on the file extension (e.g. ".bsp")
bool CXMeshFileLoader::isALoadableFileExtension(const io::path& filename) const
{
return core::hasFileExtension ( filename, "x" );
}
//! creates/loads an animated mesh from the file.
//! \return Pointer to the created mesh. Returns 0 if loading failed.
//! If you no longer need the mesh, you should call IAnimatedMesh::drop().
//! See IReferenceCounted::drop() for more information.
IAnimatedMesh* CXMeshFileLoader::createMesh(io::IReadFile* f)
{
if (!f)
return 0;
#ifdef _XREADER_DEBUG
u32 time = os::Timer::getRealTime();
#endif
AnimatedMesh = new CSkinnedMesh();
if (load(f))
{
AnimatedMesh->finalize();
}
else
{
AnimatedMesh->drop();
AnimatedMesh = 0;
}
#ifdef _XREADER_DEBUG
time = os::Timer::getRealTime() - time;
core::stringc tmpString = "Time to load ";
tmpString += BinaryFormat ? "binary" : "ascii";
tmpString += " X file: ";
tmpString += time;
tmpString += "ms";
os::Printer::log(tmpString.c_str());
#endif
//Clear up
MajorVersion=0;
MinorVersion=0;
BinaryFormat=0;
BinaryNumCount=0;
FloatSize=0;
P=0;
End=0;
CurFrame=0;
TemplateMaterials.clear();
delete [] Buffer;
Buffer = 0;
for (u32 i=0; i<Meshes.size(); ++i)
delete Meshes[i];
Meshes.clear();
return AnimatedMesh;
}
bool CXMeshFileLoader::load(io::IReadFile* file)
{
if (!readFileIntoMemory(file))
return false;
if (!parseFile())
return false;
for (u32 n=0; n<Meshes.size(); ++n)
{
SXMesh *mesh=Meshes[n];
// default material if nothing loaded
if (!mesh->Materials.size())
{
mesh->Materials.push_back(video::SMaterial());
mesh->Materials[0].DiffuseColor.set(0xff777777);
mesh->Materials[0].Shininess=0.f;
mesh->Materials[0].SpecularColor.set(0xff777777);
mesh->Materials[0].EmissiveColor.set(0xff000000);
}
u32 i;
mesh->Buffers.reallocate(mesh->Materials.size());
#ifndef BETTER_MESHBUFFER_SPLITTING_FOR_X
const u32 bufferOffset = AnimatedMesh->getMeshBufferCount();
#endif
for (i=0; i<mesh->Materials.size(); ++i)
{
mesh->Buffers.push_back( AnimatedMesh->addMeshBuffer() );
mesh->Buffers.getLast()->Material = mesh->Materials[i];
if (!mesh->HasSkinning)
{
//Set up rigid animation
if (mesh->AttachedJointID!=-1)
{
AnimatedMesh->getAllJoints()[mesh->AttachedJointID]->AttachedMeshes.push_back( AnimatedMesh->getMeshBuffers().size()-1 );
}
}
}
if (!mesh->FaceMaterialIndices.size())
{
mesh->FaceMaterialIndices.set_used(mesh->Indices.size() / 3);
for (i=0; i<mesh->FaceMaterialIndices.size(); ++i)
mesh->FaceMaterialIndices[i]=0;
}
if (!mesh->HasVertexColors)
{
for (u32 j=0;j<mesh->FaceMaterialIndices.size();++j)
{
for (u32 id=j*3+0;id<=j*3+2;++id)
{
mesh->Vertices[ mesh->Indices[id] ].Color = mesh->Buffers[mesh->FaceMaterialIndices[j]]->Material.DiffuseColor;
}
}
}
#ifdef BETTER_MESHBUFFER_SPLITTING_FOR_X
{
//the same vertex can be used in many different meshbuffers, but it's slow to work out
core::array< core::array< u32 > > verticesLinkIndex;
verticesLinkIndex.reallocate(mesh->Vertices.size());
core::array< core::array< u16 > > verticesLinkBuffer;
verticesLinkBuffer.reallocate(mesh->Vertices.size());
for (i=0;i<mesh->Vertices.size();++i)
{
verticesLinkIndex.push_back( core::array< u32 >() );
verticesLinkBuffer.push_back( core::array< u16 >() );
}
for (i=0;i<mesh->FaceMaterialIndices.size();++i)
{
for (u32 id=i*3+0;id<=i*3+2;++id)
{
core::array< u16 > &Array=verticesLinkBuffer[ mesh->Indices[id] ];
bool found=false;
for (u32 j=0; j < Array.size(); ++j)
{
if (Array[j]==mesh->FaceMaterialIndices[i])
{
found=true;
break;
}
}
if (!found)
Array.push_back( mesh->FaceMaterialIndices[i] );
}
}
for (i=0;i<verticesLinkBuffer.size();++i)
{
if (!verticesLinkBuffer[i].size())
verticesLinkBuffer[i].push_back(0);
}
for (i=0;i<mesh->Vertices.size();++i)
{
core::array< u16 > &Array = verticesLinkBuffer[i];
verticesLinkIndex[i].reallocate(Array.size());
for (u32 j=0; j < Array.size(); ++j)
{
scene::SSkinMeshBuffer *buffer = mesh->Buffers[ Array[j] ];
verticesLinkIndex[i].push_back( buffer->Vertices_Standard.size() );
buffer->Vertices_Standard.push_back( mesh->Vertices[i] );
}
}
for (i=0;i<mesh->FaceMaterialIndices.size();++i)
{
scene::SSkinMeshBuffer *buffer=mesh->Buffers[ mesh->FaceMaterialIndices[i] ];
for (u32 id=i*3+0;id<=i*3+2;++id)
{
core::array< u16 > &Array=verticesLinkBuffer[ mesh->Indices[id] ];
for (u32 j=0;j< Array.size() ;++j)
{
if ( Array[j]== mesh->FaceMaterialIndices[i] )
buffer->Indices.push_back( verticesLinkIndex[ mesh->Indices[id] ][j] );
}
}
}
for (u32 j=0;j<mesh->WeightJoint.size();++j)
{
ISkinnedMesh::SJoint* joint = AnimatedMesh->getAllJoints()[mesh->WeightJoint[j]];
ISkinnedMesh::SWeight& weight = joint->Weights[mesh->WeightNum[j]];
u32 id = weight.vertex_id;
if (id>=verticesLinkIndex.size())
{
os::Printer::log("X loader: Weight id out of range", ELL_WARNING);
id=0;
weight.strength=0.f;
}
if (verticesLinkBuffer[id].size()==1)
{
weight.vertex_id=verticesLinkIndex[id][0];
weight.buffer_id=verticesLinkBuffer[id][0];
}
else if (verticesLinkBuffer[id].size() != 0)
{
for (u32 k=1; k < verticesLinkBuffer[id].size(); ++k)
{
ISkinnedMesh::SWeight* WeightClone = AnimatedMesh->addWeight(joint);
WeightClone->strength = weight.strength;
WeightClone->vertex_id = verticesLinkIndex[id][k];
WeightClone->buffer_id = verticesLinkBuffer[id][k];
}
}
}
}
#else
{
core::array< u32 > verticesLinkIndex;
core::array< s16 > verticesLinkBuffer;
verticesLinkBuffer.set_used(mesh->Vertices.size());
// init with 0
for (i=0;i<mesh->Vertices.size();++i)
{
verticesLinkBuffer[i]=-1;
}
bool warned = false;
// store meshbuffer number per vertex
for (i=0;i<mesh->FaceMaterialIndices.size();++i)
{
for (u32 id=i*3+0;id<=i*3+2;++id)
{
if ((verticesLinkBuffer[mesh->Indices[id]] != -1) && (verticesLinkBuffer[mesh->Indices[id]] != (s16)mesh->FaceMaterialIndices[i]))
{
if (!warned)
{
os::Printer::log("X loader", "Duplicated vertex, animation might be corrupted.", ELL_WARNING);
warned=true;
}
const u32 tmp = mesh->Vertices.size();
mesh->Vertices.push_back(mesh->Vertices[ mesh->Indices[id] ]);
mesh->Indices[id] = tmp;
verticesLinkBuffer.set_used(mesh->Vertices.size());
}
verticesLinkBuffer[ mesh->Indices[id] ] = mesh->FaceMaterialIndices[i];
}
}
if (mesh->FaceMaterialIndices.size() != 0)
{
// store vertices in buffers and remember relation in verticesLinkIndex
u32* vCountArray = new u32[mesh->Buffers.size()];
memset(vCountArray, 0, mesh->Buffers.size()*sizeof(u32));
// count vertices in each buffer and reallocate
for (i=0; i<mesh->Vertices.size(); ++i)
++vCountArray[verticesLinkBuffer[i]];
if (mesh->TCoords2.size())
{
for (i=0; i!=mesh->Buffers.size(); ++i)
{
mesh->Buffers[i]->Vertices_2TCoords.reallocate(vCountArray[i]);
mesh->Buffers[i]->VertexType=video::EVT_2TCOORDS;
}
}
else
{
for (i=0; i!=mesh->Buffers.size(); ++i)
mesh->Buffers[i]->Vertices_Standard.reallocate(vCountArray[i]);
}
verticesLinkIndex.set_used(mesh->Vertices.size());
// actually store vertices
for (i=0; i<mesh->Vertices.size(); ++i)
{
scene::SSkinMeshBuffer *buffer = mesh->Buffers[ verticesLinkBuffer[i] ];
if (mesh->TCoords2.size())
{
verticesLinkIndex[i] = buffer->Vertices_2TCoords.size();
buffer->Vertices_2TCoords.push_back( mesh->Vertices[i] );
buffer->Vertices_2TCoords.getLast().TCoords2=mesh->TCoords2[i];
}
else
{
verticesLinkIndex[i] = buffer->Vertices_Standard.size();
buffer->Vertices_Standard.push_back( mesh->Vertices[i] );
}
}
// count indices per buffer and reallocate
memset(vCountArray, 0, mesh->Buffers.size()*sizeof(u32));
for (i=0; i<mesh->FaceMaterialIndices.size(); ++i)
++vCountArray[ mesh->FaceMaterialIndices[i] ];
for (i=0; i!=mesh->Buffers.size(); ++i)
mesh->Buffers[i]->Indices.reallocate(vCountArray[i]);
delete [] vCountArray;
// create indices per buffer
for (i=0; i<mesh->FaceMaterialIndices.size(); ++i)
{
scene::SSkinMeshBuffer *buffer = mesh->Buffers[ mesh->FaceMaterialIndices[i] ];
for (u32 id=i*3+0; id!=i*3+3; ++id)
{
buffer->Indices.push_back( verticesLinkIndex[ mesh->Indices[id] ] );
}
}
}
for (u32 j=0; j<mesh->WeightJoint.size(); ++j)
{
ISkinnedMesh::SWeight& weight = (AnimatedMesh->getAllJoints()[mesh->WeightJoint[j]]->Weights[mesh->WeightNum[j]]);
u32 id = weight.vertex_id;
if (id>=verticesLinkIndex.size())
{
os::Printer::log("X loader: Weight id out of range", ELL_WARNING);
id=0;
weight.strength=0.f;
}
weight.vertex_id=verticesLinkIndex[id];
weight.buffer_id=verticesLinkBuffer[id] + bufferOffset;
}
}
#endif
}
return true;
}
//! Reads file into memory
bool CXMeshFileLoader::readFileIntoMemory(io::IReadFile* file)
{
const long size = file->getSize();
if (size < 12)
{
os::Printer::log("X File is too small.", ELL_WARNING);
return false;
}
Buffer = new c8[size];
//! read all into memory
if (file->read(Buffer, size) != size)
{
os::Printer::log("Could not read from x file.", ELL_WARNING);
return false;
}
Line = 1;
End = Buffer + size;
//! check header "xof "
if (strncmp(Buffer, "xof ", 4)!=0)
{
os::Printer::log("Not an x file, wrong header.", ELL_WARNING);
return false;
}
//! read minor and major version, e.g. 0302 or 0303
c8 tmp[3];
tmp[2] = 0x0;
tmp[0] = Buffer[4];
tmp[1] = Buffer[5];
MajorVersion = core::strtol10(tmp);
tmp[0] = Buffer[6];
tmp[1] = Buffer[7];
MinorVersion = core::strtol10(tmp);
//! read format
if (strncmp(&Buffer[8], "txt ", 4) ==0)
BinaryFormat = false;
else if (strncmp(&Buffer[8], "bin ", 4) ==0)
BinaryFormat = true;
else
{
os::Printer::log("Only uncompressed x files currently supported.", ELL_WARNING);
return false;
}
BinaryNumCount=0;
//! read float size
if (strncmp(&Buffer[12], "0032", 4) ==0)
FloatSize = 4;
else if (strncmp(&Buffer[12], "0064", 4) ==0)
FloatSize = 8;
else
{
os::Printer::log("Float size not supported.", ELL_WARNING);
return false;
}
P = &Buffer[16];
readUntilEndOfLine();
FilePath = FileSystem->getFileDir(file->getFileName()) + "/";
- FilePath += '/';
return true;
}
//! Parses the file
bool CXMeshFileLoader::parseFile()
{
while(parseDataObject())
{
// loop
}
return true;
}
//! Parses the next Data object in the file
bool CXMeshFileLoader::parseDataObject()
{
core::stringc objectName = getNextToken();
if (objectName.size() == 0)
return false;
// parse specific object
#ifdef _XREADER_DEBUG
os::Printer::log("debug DataObject:", objectName.c_str() );
#endif
if (objectName == "template")
return parseDataObjectTemplate();
else
if (objectName == "Frame")
{
return parseDataObjectFrame( 0 );
}
else
if (objectName == "Mesh")
{
// some meshes have no frames at all
//CurFrame = AnimatedMesh->addJoint(0);
SXMesh *mesh=new SXMesh;
//mesh->Buffer=AnimatedMesh->addMeshBuffer();
Meshes.push_back(mesh);
return parseDataObjectMesh(*mesh);
}
else
if (objectName == "AnimationSet")
{
return parseDataObjectAnimationSet();
}
else
if (objectName == "Material")
{
// template materials now available thanks to joeWright
TemplateMaterials.push_back(SXTemplateMaterial());
TemplateMaterials.getLast().Name = getNextToken();
return parseDataObjectMaterial(TemplateMaterials.getLast().Material);
}
else
if (objectName == "}")
{
os::Printer::log("} found in dataObject", ELL_WARNING);
return true;
}
os::Printer::log("Unknown data object in animation of .x file", objectName.c_str(), ELL_WARNING);
return parseUnknownDataObject();
}
bool CXMeshFileLoader::parseDataObjectTemplate()
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading template");
#endif
// parse a template data object. Currently not stored.
core::stringc name;
if (!readHeadOfDataObject(&name))
{
os::Printer::log("Left delimiter in template data object missing.",
name.c_str(), ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
// read GUID
getNextToken();
// read and ignore data members
while(true)
{
core::stringc s = getNextToken();
if (s == "}")
break;
if (s.size() == 0)
return false;
}
return true;
}
bool CXMeshFileLoader::parseDataObjectFrame(CSkinnedMesh::SJoint *Parent)
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading frame");
#endif
// A coordinate frame, or "frame of reference." The Frame template
// is open and can contain any object. The Direct3D extensions (D3DX)
// mesh-loading functions recognize Mesh, FrameTransformMatrix, and
// Frame template instances as child objects when loading a Frame
// instance.
u32 JointID=0;
core::stringc name;
if (!readHeadOfDataObject(&name))
{
os::Printer::log("No opening brace in Frame found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
CSkinnedMesh::SJoint *joint=0;
if (name.size())
{
for (u32 n=0; n < AnimatedMesh->getAllJoints().size(); ++n)
{
if (AnimatedMesh->getAllJoints()[n]->Name==name)
{
joint=AnimatedMesh->getAllJoints()[n];
JointID=n;
break;
}
}
}
if (!joint)
{
#ifdef _XREADER_DEBUG
os::Printer::log("creating joint ", name.c_str());
#endif
joint=AnimatedMesh->addJoint(Parent);
joint->Name=name;
JointID=AnimatedMesh->getAllJoints().size()-1;
}
else
{
#ifdef _XREADER_DEBUG
os::Printer::log("using joint ", name.c_str());
#endif
if (Parent)
Parent->Children.push_back(joint);
}
// Now inside a frame.
// read tokens until closing brace is reached.
while(true)
{
core::stringc objectName = getNextToken();
#ifdef _XREADER_DEBUG
os::Printer::log("debug DataObject in frame:", objectName.c_str() );
#endif
if (objectName.size() == 0)
{
os::Printer::log("Unexpected ending found in Frame in x file.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
else
if (objectName == "}")
{
break; // frame finished
}
else
if (objectName == "Frame")
{
if (!parseDataObjectFrame(joint))
return false;
}
else
if (objectName == "FrameTransformMatrix")
{
if (!parseDataObjectTransformationMatrix(joint->LocalMatrix))
return false;
//joint->LocalAnimatedMatrix
//joint->LocalAnimatedMatrix.makeInverse();
//joint->LocalMatrix=tmp*joint->LocalAnimatedMatrix;
}
else
if (objectName == "Mesh")
{
/*
frame.Meshes.push_back(SXMesh());
if (!parseDataObjectMesh(frame.Meshes.getLast()))
return false;
*/
SXMesh *mesh=new SXMesh;
mesh->AttachedJointID=JointID;
Meshes.push_back(mesh);
if (!parseDataObjectMesh(*mesh))
return false;
}
else
{
os::Printer::log("Unknown data object in frame in x file", objectName.c_str(), ELL_WARNING);
if (!parseUnknownDataObject())
return false;
}
}
return true;
}
bool CXMeshFileLoader::parseDataObjectTransformationMatrix(core::matrix4 &mat)
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading Transformation Matrix");
#endif
if (!readHeadOfDataObject())
{
os::Printer::log("No opening brace in Transformation Matrix found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
readMatrix(mat);
if (!checkForOneFollowingSemicolons())
{
os::Printer::log("No finishing semicolon in Transformation Matrix found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
if (!checkForClosingBrace())
{
os::Printer::log("No closing brace in Transformation Matrix found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
return true;
}
bool CXMeshFileLoader::parseDataObjectMesh(SXMesh &mesh)
{
core::stringc name;
if (!readHeadOfDataObject(&name))
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading mesh");
#endif
os::Printer::log("No opening brace in Mesh found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading mesh", name.c_str());
#endif
// read vertex count
const u32 nVertices = readInt();
// read vertices
mesh.Vertices.set_used(nVertices);
for (u32 n=0; n<nVertices; ++n)
{
readVector3(mesh.Vertices[n].Pos);
mesh.Vertices[n].Color=0xFFFFFFFF;
}
if (!checkForTwoFollowingSemicolons())
{
os::Printer::log("No finishing semicolon in Mesh Vertex Array found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
// read faces
const u32 nFaces = readInt();
mesh.Indices.set_used(nFaces * 3);
mesh.IndexCountPerFace.set_used(nFaces);
core::array<u32> polygonfaces;
u32 currentIndex = 0;
for (u32 k=0; k<nFaces; ++k)
{
const u32 fcnt = readInt();
if (fcnt != 3)
{
if (fcnt < 3)
{
os::Printer::log("Invalid face count (<3) found in Mesh x file reader.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
// read face indices
polygonfaces.set_used(fcnt);
u32 triangles = (fcnt-2);
mesh.Indices.set_used(mesh.Indices.size() + ((triangles-1)*3));
mesh.IndexCountPerFace[k] = (u16)(triangles * 3);
for (u32 f=0; f<fcnt; ++f)
polygonfaces[f] = readInt();
for (u32 jk=0; jk<triangles; ++jk)
{
mesh.Indices[currentIndex++] = polygonfaces[0];
mesh.Indices[currentIndex++] = polygonfaces[jk+1];
mesh.Indices[currentIndex++] = polygonfaces[jk+2];
}
// TODO: change face indices in material list
}
else
{
mesh.Indices[currentIndex++] = readInt();
mesh.Indices[currentIndex++] = readInt();
mesh.Indices[currentIndex++] = readInt();
mesh.IndexCountPerFace[k] = 3;
}
}
if (!checkForTwoFollowingSemicolons())
{
os::Printer::log("No finishing semicolon in Mesh Face Array found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
// here, other data objects may follow
while(true)
{
core::stringc objectName = getNextToken();
if (objectName.size() == 0)
{
os::Printer::log("Unexpected ending found in Mesh in x file.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
else
if (objectName == "}")
{
break; // mesh finished
}
#ifdef _XREADER_DEBUG
os::Printer::log("debug DataObject in mesh:", objectName.c_str() );
#endif
if (objectName == "MeshNormals")
{
if (!parseDataObjectMeshNormals(mesh))
return false;
}
else
if (objectName == "MeshTextureCoords")
{
if (!parseDataObjectMeshTextureCoords(mesh))
return false;
}
else
if (objectName == "MeshVertexColors")
{
if (!parseDataObjectMeshVertexColors(mesh))
return false;
}
else
if (objectName == "MeshMaterialList")
{
if (!parseDataObjectMeshMaterialList(mesh))
return false;
}
else
if (objectName == "VertexDuplicationIndices")
{
// we'll ignore vertex duplication indices
// TODO: read them
if (!parseUnknownDataObject())
return false;
}
else
if (objectName == "DeclData")
{
// arbitrary vertex attributes
// first comes the number of element definitions
// then the vertex element type definitions
// with format type;tesselator;semantics;usageindex
// we want to support 2;0;6;0 == tangent
// 2;0;7;0 == binormal
// 2;0;3;0 == normal
// 1/2;0;5;0 == 1st uv coord
// and 1/2;0;5;1 == 2nd uv coord
// type==2 is 3xf32, type==1 is 2xf32
u32 j;
const u32 dcnt = readInt();
u16 size = 0;
s16 normalpos = -1;
s16 uvpos = -1;
s16 uv2pos = -1;
s16 tangentpos = -1;
s16 binormalpos = -1;
s16 normaltype = -1;
s16 uvtype = -1;
s16 uv2type = -1;
s16 tangenttype = -1;
s16 binormaltype = -1;
for (j=0; j<dcnt; ++j)
{
const u32 type = readInt();
//const u32 tesselator = readInt();
readInt();
const u32 semantics = readInt();
const u32 index = readInt();
switch (semantics)
{
case 3:
normalpos = size;
normaltype = type;
break;
case 5:
if (index==0)
{
uvpos = size;
uvtype = type;
}
else if (index==1)
{
uv2pos = size;
uv2type = type;
}
break;
case 6:
tangentpos = size;
tangenttype = type;
break;
case 7:
binormalpos = size;
binormaltype = type;
break;
default:
break;
}
switch (type)
{
case 0:
size += 4;
break;
case 1:
size += 8;
break;
case 2:
size += 12;
break;
case 3:
size += 16;
break;
case 4:
case 5:
case 6:
size += 4;
break;
case 7:
size += 8;
break;
case 8:
case 9:
size += 4;
break;
case 10:
size += 8;
break;
case 11:
size += 4;
break;
case 12:
size += 8;
break;
case 13:
size += 4;
break;
case 14:
|
paupawsan/Irrlicht
|
a1674b3f225659a8dbbbb062df615c86532d5700
|
Fix crash in CGUIListBox when environment was cleared on events (found by Auria).
|
diff --git a/source/Irrlicht/CGUIListBox.cpp b/source/Irrlicht/CGUIListBox.cpp
index 37a9937..ac5f3e7 100644
--- a/source/Irrlicht/CGUIListBox.cpp
+++ b/source/Irrlicht/CGUIListBox.cpp
@@ -1,898 +1,899 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CGUIListBox.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include "CGUIListBox.h"
#include "IGUISkin.h"
#include "IGUIEnvironment.h"
#include "IVideoDriver.h"
#include "IGUIFont.h"
#include "IGUISpriteBank.h"
#include "CGUIScrollBar.h"
#include "os.h"
namespace irr
{
namespace gui
{
//! constructor
CGUIListBox::CGUIListBox(IGUIEnvironment* environment, IGUIElement* parent,
s32 id, core::rect<s32> rectangle, bool clip,
bool drawBack, bool moveOverSelect)
: IGUIListBox(environment, parent, id, rectangle), Selected(-1),
ItemHeight(0),ItemHeightOverride(0),
TotalItemHeight(0), ItemsIconWidth(0), Font(0), IconBank(0),
ScrollBar(0), selectTime(0), LastKeyTime(0), Selecting(false), DrawBack(drawBack),
MoveOverSelect(moveOverSelect), AutoScroll(true), HighlightWhenNotFocused(true)
{
#ifdef _DEBUG
setDebugName("CGUIListBox");
#endif
IGUISkin* skin = Environment->getSkin();
const s32 s = skin->getSize(EGDS_SCROLLBAR_SIZE);
ScrollBar = new CGUIScrollBar(false, Environment, this, -1,
core::rect<s32>(RelativeRect.getWidth() - s, 0, RelativeRect.getWidth(), RelativeRect.getHeight()),
!clip);
ScrollBar->setSubElement(true);
ScrollBar->setTabStop(false);
ScrollBar->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT);
ScrollBar->setVisible(false);
ScrollBar->setPos(0);
setNotClipped(!clip);
// this element can be tabbed to
setTabStop(true);
setTabOrder(-1);
updateAbsolutePosition();
}
//! destructor
CGUIListBox::~CGUIListBox()
{
if (ScrollBar)
ScrollBar->drop();
if (Font)
Font->drop();
if (IconBank)
IconBank->drop();
}
//! returns amount of list items
u32 CGUIListBox::getItemCount() const
{
return Items.size();
}
//! returns string of a list item. the may be a value from 0 to itemCount-1
const wchar_t* CGUIListBox::getListItem(u32 id) const
{
if (id>=Items.size())
return 0;
return Items[id].text.c_str();
}
//! Returns the icon of an item
s32 CGUIListBox::getIcon(u32 id) const
{
if (id>=Items.size())
return -1;
return Items[id].icon;
}
//! adds a list item, returns id of item
u32 CGUIListBox::addItem(const wchar_t* text)
{
return addItem(text, -1);
}
//! adds a list item, returns id of item
void CGUIListBox::removeItem(u32 id)
{
if (id >= Items.size())
return;
if ((u32)Selected==id)
{
Selected = -1;
}
else if ((u32)Selected > id)
{
Selected -= 1;
selectTime = os::Timer::getTime();
}
Items.erase(id);
recalculateItemHeight();
}
//! clears the list
void CGUIListBox::clear()
{
Items.clear();
ItemsIconWidth = 0;
Selected = -1;
if (ScrollBar)
ScrollBar->setPos(0);
recalculateItemHeight();
}
void CGUIListBox::recalculateItemHeight()
{
IGUISkin* skin = Environment->getSkin();
if (Font != skin->getFont())
{
if (Font)
Font->drop();
Font = skin->getFont();
if ( 0 == ItemHeightOverride )
ItemHeight = 0;
if (Font)
{
if ( 0 == ItemHeightOverride )
ItemHeight = Font->getDimension(L"A").Height + 4;
Font->grab();
}
}
TotalItemHeight = ItemHeight * Items.size();
ScrollBar->setMax(TotalItemHeight - AbsoluteRect.getHeight());
s32 minItemHeight = ItemHeight > 0 ? ItemHeight : 1;
ScrollBar->setSmallStep ( minItemHeight );
ScrollBar->setLargeStep ( 2*minItemHeight );
if ( TotalItemHeight <= AbsoluteRect.getHeight() )
ScrollBar->setVisible(false);
else
ScrollBar->setVisible(true);
}
//! returns id of selected item. returns -1 if no item is selected.
s32 CGUIListBox::getSelected() const
{
return Selected;
}
//! sets the selected item. Set this to -1 if no item should be selected
void CGUIListBox::setSelected(s32 id)
{
if ((u32)id>=Items.size())
Selected = -1;
else
Selected = id;
selectTime = os::Timer::getTime();
recalculateScrollPos();
}
//! sets the selected item. Set this to -1 if no item should be selected
void CGUIListBox::setSelected(const wchar_t *item)
{
s32 index = -1;
if ( item )
{
for ( index = 0; index < (s32) Items.size(); ++index )
{
if ( Items[index].text == item )
break;
}
}
setSelected ( index );
}
//! called if an event happened.
bool CGUIListBox::OnEvent(const SEvent& event)
{
if (IsEnabled)
{
switch(event.EventType)
{
case EET_KEY_INPUT_EVENT:
if (event.KeyInput.PressedDown &&
(event.KeyInput.Key == KEY_DOWN ||
event.KeyInput.Key == KEY_UP ||
event.KeyInput.Key == KEY_HOME ||
event.KeyInput.Key == KEY_END ||
event.KeyInput.Key == KEY_NEXT ||
event.KeyInput.Key == KEY_PRIOR ) )
{
s32 oldSelected = Selected;
switch (event.KeyInput.Key)
{
case KEY_DOWN:
Selected += 1;
break;
case KEY_UP:
Selected -= 1;
break;
case KEY_HOME:
Selected = 0;
break;
case KEY_END:
Selected = (s32)Items.size()-1;
break;
case KEY_NEXT:
Selected += AbsoluteRect.getHeight() / ItemHeight;
break;
case KEY_PRIOR:
Selected -= AbsoluteRect.getHeight() / ItemHeight;
break;
default:
break;
}
if (Selected >= (s32)Items.size())
Selected = Items.size() - 1;
else
if (Selected<0)
Selected = 0;
recalculateScrollPos();
// post the news
if (oldSelected != Selected && Parent && !Selecting && !MoveOverSelect)
{
SEvent e;
e.EventType = EET_GUI_EVENT;
e.GUIEvent.Caller = this;
e.GUIEvent.Element = 0;
e.GUIEvent.EventType = EGET_LISTBOX_CHANGED;
Parent->OnEvent(e);
}
return true;
}
else
if (!event.KeyInput.PressedDown && ( event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE ) )
{
if (Parent)
{
SEvent e;
e.EventType = EET_GUI_EVENT;
e.GUIEvent.Caller = this;
e.GUIEvent.Element = 0;
e.GUIEvent.EventType = EGET_LISTBOX_SELECTED_AGAIN;
Parent->OnEvent(e);
}
return true;
}
else if (event.KeyInput.PressedDown && event.KeyInput.Char)
{
// change selection based on text as it is typed.
u32 now = os::Timer::getTime();
if (now - LastKeyTime < 500)
{
// add to key buffer if it isn't a key repeat
if (!(KeyBuffer.size() == 1 && KeyBuffer[0] == event.KeyInput.Char))
{
KeyBuffer += L" ";
KeyBuffer[KeyBuffer.size()-1] = event.KeyInput.Char;
}
}
else
{
KeyBuffer = L" ";
KeyBuffer[0] = event.KeyInput.Char;
}
LastKeyTime = now;
// find the selected item, starting at the current selection
s32 start = Selected;
// dont change selection if the key buffer matches the current item
if (Selected > -1 && KeyBuffer.size() > 1)
{
if (Items[Selected].text.size() >= KeyBuffer.size() &&
KeyBuffer.equals_ignore_case(Items[Selected].text.subString(0,KeyBuffer.size())))
return true;
}
s32 current;
for (current = start+1; current < (s32)Items.size(); ++current)
{
if (Items[current].text.size() >= KeyBuffer.size())
{
if (KeyBuffer.equals_ignore_case(Items[current].text.subString(0,KeyBuffer.size())))
{
if (Parent && Selected != current && !Selecting && !MoveOverSelect)
{
SEvent e;
e.EventType = EET_GUI_EVENT;
e.GUIEvent.Caller = this;
e.GUIEvent.Element = 0;
e.GUIEvent.EventType = EGET_LISTBOX_CHANGED;
Parent->OnEvent(e);
}
setSelected(current);
return true;
}
}
}
for (current = 0; current <= start; ++current)
{
if (Items[current].text.size() >= KeyBuffer.size())
{
if (KeyBuffer.equals_ignore_case(Items[current].text.subString(0,KeyBuffer.size())))
{
if (Parent && Selected != current && !Selecting && !MoveOverSelect)
{
Selected = current;
SEvent e;
e.EventType = EET_GUI_EVENT;
e.GUIEvent.Caller = this;
e.GUIEvent.Element = 0;
e.GUIEvent.EventType = EGET_LISTBOX_CHANGED;
Parent->OnEvent(e);
}
setSelected(current);
return true;
}
}
}
return true;
}
break;
case EET_GUI_EVENT:
switch(event.GUIEvent.EventType)
{
case gui::EGET_SCROLL_BAR_CHANGED:
if (event.GUIEvent.Caller == ScrollBar)
return true;
break;
case gui::EGET_ELEMENT_FOCUS_LOST:
{
if (event.GUIEvent.Caller == this)
Selecting = false;
}
default:
break;
}
break;
case EET_MOUSE_INPUT_EVENT:
{
core::position2d<s32> p(event.MouseInput.X, event.MouseInput.Y);
switch(event.MouseInput.Event)
{
case EMIE_MOUSE_WHEEL:
ScrollBar->setPos(ScrollBar->getPos() + (s32)event.MouseInput.Wheel*-ItemHeight/2);
return true;
case EMIE_LMOUSE_PRESSED_DOWN:
{
Selecting = true;
return true;
}
case EMIE_LMOUSE_LEFT_UP:
{
Selecting = false;
if (isPointInside(p))
selectNew(event.MouseInput.Y);
return true;
}
case EMIE_MOUSE_MOVED:
if (Selecting || MoveOverSelect)
{
if (isPointInside(p))
{
selectNew(event.MouseInput.Y, true);
return true;
}
}
default:
break;
}
}
break;
case EET_LOG_TEXT_EVENT:
case EET_USER_EVENT:
case EET_JOYSTICK_INPUT_EVENT:
case EGUIET_FORCE_32_BIT:
break;
}
}
return IGUIElement::OnEvent(event);
}
void CGUIListBox::selectNew(s32 ypos, bool onlyHover)
{
u32 now = os::Timer::getTime();
s32 oldSelected = Selected;
// find new selected item.
if (ItemHeight!=0)
Selected = ((ypos - AbsoluteRect.UpperLeftCorner.Y - 1) + ScrollBar->getPos()) / ItemHeight;
if (Selected<0)
Selected = 0;
else
if ((u32)Selected >= Items.size())
Selected = Items.size() - 1;
recalculateScrollPos();
+ gui::EGUI_EVENT_TYPE eventType = (Selected == oldSelected && now < selectTime + 500) ? EGET_LISTBOX_SELECTED_AGAIN : EGET_LISTBOX_CHANGED;
+ selectTime = now;
// post the news
if (Parent && !onlyHover)
{
SEvent event;
event.EventType = EET_GUI_EVENT;
event.GUIEvent.Caller = this;
event.GUIEvent.Element = 0;
- event.GUIEvent.EventType = (Selected == oldSelected && now < selectTime + 500) ? EGET_LISTBOX_SELECTED_AGAIN : EGET_LISTBOX_CHANGED;
+ event.GUIEvent.EventType = eventType;
Parent->OnEvent(event);
}
- selectTime = now;
}
//! Update the position and size of the listbox, and update the scrollbar
void CGUIListBox::updateAbsolutePosition()
{
IGUIElement::updateAbsolutePosition();
recalculateItemHeight();
}
//! draws the element and its children
void CGUIListBox::draw()
{
if (!IsVisible)
return;
recalculateItemHeight(); // if the font changed
IGUISkin* skin = Environment->getSkin();
core::rect<s32>* clipRect = 0;
// draw background
core::rect<s32> frameRect(AbsoluteRect);
// draw items
core::rect<s32> clientClip(AbsoluteRect);
clientClip.UpperLeftCorner.Y += 1;
clientClip.UpperLeftCorner.X += 1;
if (ScrollBar->isVisible())
clientClip.LowerRightCorner.X = AbsoluteRect.LowerRightCorner.X - skin->getSize(EGDS_SCROLLBAR_SIZE);
clientClip.LowerRightCorner.Y -= 1;
clientClip.clipAgainst(AbsoluteClippingRect);
skin->draw3DSunkenPane(this, skin->getColor(EGDC_3D_HIGH_LIGHT), true,
DrawBack, frameRect, &clientClip);
if (clipRect)
clientClip.clipAgainst(*clipRect);
frameRect = AbsoluteRect;
frameRect.UpperLeftCorner.X += 1;
if (ScrollBar->isVisible())
frameRect.LowerRightCorner.X = AbsoluteRect.LowerRightCorner.X - skin->getSize(EGDS_SCROLLBAR_SIZE);
frameRect.LowerRightCorner.Y = AbsoluteRect.UpperLeftCorner.Y + ItemHeight;
frameRect.UpperLeftCorner.Y -= ScrollBar->getPos();
frameRect.LowerRightCorner.Y -= ScrollBar->getPos();
bool hl = (HighlightWhenNotFocused || Environment->hasFocus(this) || Environment->hasFocus(ScrollBar));
for (s32 i=0; i<(s32)Items.size(); ++i)
{
if (frameRect.LowerRightCorner.Y >= AbsoluteRect.UpperLeftCorner.Y &&
frameRect.UpperLeftCorner.Y <= AbsoluteRect.LowerRightCorner.Y)
{
if (i == Selected && hl)
skin->draw2DRectangle(this, skin->getColor(EGDC_HIGH_LIGHT), frameRect, &clientClip);
core::rect<s32> textRect = frameRect;
textRect.UpperLeftCorner.X += 3;
if (Font)
{
if (IconBank && (Items[i].icon > -1))
{
core::position2di iconPos = textRect.UpperLeftCorner;
iconPos.Y += textRect.getHeight() / 2;
iconPos.X += ItemsIconWidth/2;
if ( i==Selected && hl )
{
IconBank->draw2DSprite( (u32)Items[i].icon, iconPos, &clientClip,
hasItemOverrideColor(i, EGUI_LBC_ICON_HIGHLIGHT) ?
getItemOverrideColor(i, EGUI_LBC_ICON_HIGHLIGHT) : getItemDefaultColor(EGUI_LBC_ICON_HIGHLIGHT),
selectTime, os::Timer::getTime(), false, true);
}
else
{
IconBank->draw2DSprite( (u32)Items[i].icon, iconPos, &clientClip,
hasItemOverrideColor(i, EGUI_LBC_ICON) ? getItemOverrideColor(i, EGUI_LBC_ICON) : getItemDefaultColor(EGUI_LBC_ICON),
0 , (i==Selected) ? os::Timer::getTime() : 0, false, true);
}
}
textRect.UpperLeftCorner.X += ItemsIconWidth+3;
if ( i==Selected && hl )
{
Font->draw(Items[i].text.c_str(), textRect,
hasItemOverrideColor(i, EGUI_LBC_TEXT_HIGHLIGHT) ?
getItemOverrideColor(i, EGUI_LBC_TEXT_HIGHLIGHT) : getItemDefaultColor(EGUI_LBC_TEXT_HIGHLIGHT),
false, true, &clientClip);
}
else
{
Font->draw(Items[i].text.c_str(), textRect,
hasItemOverrideColor(i, EGUI_LBC_TEXT) ? getItemOverrideColor(i, EGUI_LBC_TEXT) : getItemDefaultColor(EGUI_LBC_TEXT),
false, true, &clientClip);
}
textRect.UpperLeftCorner.X -= ItemsIconWidth+3;
}
}
frameRect.UpperLeftCorner.Y += ItemHeight;
frameRect.LowerRightCorner.Y += ItemHeight;
}
IGUIElement::draw();
}
//! adds an list item with an icon
u32 CGUIListBox::addItem(const wchar_t* text, s32 icon)
{
ListItem i;
i.text = text;
i.icon = icon;
Items.push_back(i);
recalculateItemHeight();
recalculateItemWidth(icon);
return Items.size() - 1;
}
void CGUIListBox::setSpriteBank(IGUISpriteBank* bank)
{
if ( bank == IconBank )
return;
if (IconBank)
IconBank->drop();
IconBank = bank;
if (IconBank)
IconBank->grab();
}
void CGUIListBox::recalculateScrollPos()
{
if (!AutoScroll)
return;
const s32 selPos = (Selected == -1 ? TotalItemHeight : Selected * ItemHeight) - ScrollBar->getPos();
if (selPos < 0)
{
ScrollBar->setPos(ScrollBar->getPos() + selPos);
}
else
if (selPos > AbsoluteRect.getHeight() - ItemHeight)
{
ScrollBar->setPos(ScrollBar->getPos() + selPos - AbsoluteRect.getHeight() + ItemHeight);
}
}
void CGUIListBox::setAutoScrollEnabled(bool scroll)
{
AutoScroll = scroll;
}
bool CGUIListBox::isAutoScrollEnabled() const
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return AutoScroll;
}
bool CGUIListBox::getSerializationLabels(EGUI_LISTBOX_COLOR colorType, core::stringc & useColorLabel, core::stringc & colorLabel) const
{
switch ( colorType )
{
case EGUI_LBC_TEXT:
useColorLabel = "UseColText";
colorLabel = "ColText";
break;
case EGUI_LBC_TEXT_HIGHLIGHT:
useColorLabel = "UseColTextHl";
colorLabel = "ColTextHl";
break;
case EGUI_LBC_ICON:
useColorLabel = "UseColIcon";
colorLabel = "ColIcon";
break;
case EGUI_LBC_ICON_HIGHLIGHT:
useColorLabel = "UseColIconHl";
colorLabel = "ColIconHl";
break;
default:
return false;
}
return true;
}
//! Writes attributes of the element.
void CGUIListBox::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const
{
IGUIListBox::serializeAttributes(out,options);
// todo: out->addString ("IconBank", IconBank->getName?);
out->addBool ("DrawBack", DrawBack);
out->addBool ("MoveOverSelect", MoveOverSelect);
out->addBool ("AutoScroll", AutoScroll);
out->addInt("ItemCount", Items.size());
for (u32 i=0;i<Items.size(); ++i)
{
core::stringc label("text");
label += i;
out->addString(label.c_str(), Items[i].text.c_str() );
for ( s32 c=0; c < (s32)EGUI_LBC_COUNT; ++c )
{
core::stringc useColorLabel, colorLabel;
if ( !getSerializationLabels((EGUI_LISTBOX_COLOR)c, useColorLabel, colorLabel) )
return;
label = useColorLabel; label += i;
if ( Items[i].OverrideColors[c].Use )
{
out->addBool(label.c_str(), true );
label = colorLabel; label += i;
out->addColor(label.c_str(), Items[i].OverrideColors[c].Color);
}
else
{
out->addBool(label.c_str(), false );
}
}
}
}
//! Reads attributes of the element
void CGUIListBox::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0)
{
clear();
DrawBack = in->getAttributeAsBool("DrawBack");
MoveOverSelect = in->getAttributeAsBool("MoveOverSelect");
AutoScroll = in->getAttributeAsBool("AutoScroll");
IGUIListBox::deserializeAttributes(in,options);
const s32 count = in->getAttributeAsInt("ItemCount");
for (s32 i=0; i<count; ++i)
{
core::stringc label("text");
ListItem item;
label += i;
item.text = in->getAttributeAsStringW(label.c_str());
addItem(item.text.c_str(), item.icon);
for ( u32 c=0; c < EGUI_LBC_COUNT; ++c )
{
core::stringc useColorLabel, colorLabel;
if ( !getSerializationLabels((EGUI_LISTBOX_COLOR)c, useColorLabel, colorLabel) )
return;
label = useColorLabel; label += i;
Items[i].OverrideColors[c].Use = in->getAttributeAsBool(label.c_str());
if ( Items[i].OverrideColors[c].Use )
{
label = colorLabel; label += i;
Items[i].OverrideColors[c].Color = in->getAttributeAsColor(label.c_str());
}
}
}
}
void CGUIListBox::recalculateItemWidth(s32 icon)
{
if (IconBank && icon > -1 &&
IconBank->getSprites().size() > (u32)icon &&
IconBank->getSprites()[(u32)icon].Frames.size())
{
u32 rno = IconBank->getSprites()[(u32)icon].Frames[0].rectNumber;
if (IconBank->getPositions().size() > rno)
{
const s32 w = IconBank->getPositions()[rno].getWidth();
if (w > ItemsIconWidth)
ItemsIconWidth = w;
}
}
}
void CGUIListBox::setItem(u32 index, const wchar_t* text, s32 icon)
{
if ( index >= Items.size() )
return;
Items[index].text = text;
Items[index].icon = icon;
recalculateItemHeight();
recalculateItemWidth(icon);
}
//! Insert the item at the given index
//! Return the index on success or -1 on failure.
s32 CGUIListBox::insertItem(u32 index, const wchar_t* text, s32 icon)
{
ListItem i;
i.text = text;
i.icon = icon;
Items.insert(i, index);
recalculateItemHeight();
recalculateItemWidth(icon);
return index;
}
void CGUIListBox::swapItems(u32 index1, u32 index2)
{
if ( index1 >= Items.size() || index2 >= Items.size() )
return;
ListItem dummmy = Items[index1];
Items[index1] = Items[index2];
Items[index2] = dummmy;
}
void CGUIListBox::setItemOverrideColor(u32 index, const video::SColor &color)
{
for ( u32 c=0; c < EGUI_LBC_COUNT; ++c )
{
Items[index].OverrideColors[c].Use = true;
Items[index].OverrideColors[c].Color = color;
}
}
void CGUIListBox::setItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType, const video::SColor &color)
{
if ( index >= Items.size() || colorType < 0 || colorType >= EGUI_LBC_COUNT )
return;
Items[index].OverrideColors[colorType].Use = true;
Items[index].OverrideColors[colorType].Color = color;
}
void CGUIListBox::clearItemOverrideColor(u32 index)
{
for (u32 c=0; c < (u32)EGUI_LBC_COUNT; ++c )
{
Items[index].OverrideColors[c].Use = false;
}
}
void CGUIListBox::clearItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType)
{
if ( index >= Items.size() || colorType < 0 || colorType >= EGUI_LBC_COUNT )
return;
Items[index].OverrideColors[colorType].Use = false;
}
bool CGUIListBox::hasItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const
{
if ( index >= Items.size() || colorType < 0 || colorType >= EGUI_LBC_COUNT )
return false;
return Items[index].OverrideColors[colorType].Use;
}
video::SColor CGUIListBox::getItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const
{
if ( (u32)index >= Items.size() || colorType < 0 || colorType >= EGUI_LBC_COUNT )
return video::SColor();
return Items[index].OverrideColors[colorType].Color;
}
video::SColor CGUIListBox::getItemDefaultColor(EGUI_LISTBOX_COLOR colorType) const
{
IGUISkin* skin = Environment->getSkin();
if ( !skin )
return video::SColor();
switch ( colorType )
{
case EGUI_LBC_TEXT:
return skin->getColor(EGDC_BUTTON_TEXT);
case EGUI_LBC_TEXT_HIGHLIGHT:
return skin->getColor(EGDC_HIGH_LIGHT_TEXT);
case EGUI_LBC_ICON:
return skin->getColor(EGDC_ICON);
case EGUI_LBC_ICON_HIGHLIGHT:
return skin->getColor(EGDC_ICON_HIGH_LIGHT);
default:
return video::SColor();
}
}
//! set global itemHeight
void CGUIListBox::setItemHeight( s32 height )
{
ItemHeight = height;
ItemHeightOverride = 1;
}
//! Sets whether to draw the background
void CGUIListBox::setDrawBackground(bool draw)
{
DrawBack = draw;
}
} // end namespace gui
} // end namespace irr
#endif // _IRR_COMPILE_WITH_GUI_
|
paupawsan/Irrlicht
|
3edb72179a6b503f2d885789957e18d7b81b5f4a
|
Documentation and parameter names fixed (min was called max, thx to kingdutch for noticing).
|
diff --git a/include/IGUIScrollBar.h b/include/IGUIScrollBar.h
index 2348df2..3470108 100644
--- a/include/IGUIScrollBar.h
+++ b/include/IGUIScrollBar.h
@@ -1,62 +1,62 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __I_GUI_SCROLL_BAR_H_INCLUDED__
#define __I_GUI_SCROLL_BAR_H_INCLUDED__
#include "IGUIElement.h"
namespace irr
{
namespace gui
{
//! Default scroll bar GUI element.
class IGUIScrollBar : public IGUIElement
{
public:
//! constructor
IGUIScrollBar(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect<s32> rectangle)
: IGUIElement(EGUIET_SCROLL_BAR, environment, parent, id, rectangle) {}
//! sets the maximum value of the scrollbar.
virtual void setMax(s32 max) = 0;
//! gets the maximum value of the scrollbar.
virtual s32 getMax() const = 0;
- //! sets the maximum value of the scrollbar.
- virtual void setMin(s32 max) = 0;
- //! gets the maximum value of the scrollbar.
+ //! sets the minimum value of the scrollbar.
+ virtual void setMin(s32 min) = 0;
+ //! gets the minimum value of the scrollbar.
virtual s32 getMin() const = 0;
//! gets the small step value
virtual s32 getSmallStep() const = 0;
//! Sets the small step
/** That is the amount that the value changes by when clicking
on the buttons or using the cursor keys. */
virtual void setSmallStep(s32 step) = 0;
//! gets the large step value
virtual s32 getLargeStep() const = 0;
//! Sets the large step
/** That is the amount that the value changes by when clicking
in the tray, or using the page up and page down keys. */
virtual void setLargeStep(s32 step) = 0;
//! gets the current position of the scrollbar
virtual s32 getPos() const = 0;
//! sets the current position of the scrollbar
virtual void setPos(s32 pos) = 0;
};
} // end namespace gui
} // end namespace irr
#endif
diff --git a/source/Irrlicht/CGUIScrollBar.cpp b/source/Irrlicht/CGUIScrollBar.cpp
index 0f023b2..50110f7 100644
--- a/source/Irrlicht/CGUIScrollBar.cpp
+++ b/source/Irrlicht/CGUIScrollBar.cpp
@@ -1,551 +1,551 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CGUIScrollBar.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include "IGUISkin.h"
#include "IGUIEnvironment.h"
#include "IVideoDriver.h"
#include "CGUIButton.h"
#include "IGUIFont.h"
#include "IGUIFontBitmap.h"
#include "os.h"
namespace irr
{
namespace gui
{
//! constructor
CGUIScrollBar::CGUIScrollBar(bool horizontal, IGUIEnvironment* environment,
IGUIElement* parent, s32 id,
core::rect<s32> rectangle, bool noclip)
: IGUIScrollBar(environment, parent, id, rectangle), UpButton(0),
DownButton(0), Dragging(false), Horizontal(horizontal),
DraggedBySlider(false), TrayClick(false), Pos(0), DrawPos(0),
DrawHeight(0), Min(0), Max(100), SmallStep(10), LargeStep(50), DesiredPos(0),
LastChange(0)
{
#ifdef _DEBUG
setDebugName("CGUIScrollBar");
#endif
refreshControls();
setNotClipped(noclip);
// this element can be tabbed to
setTabStop(true);
setTabOrder(-1);
setPos(0);
}
//! destructor
CGUIScrollBar::~CGUIScrollBar()
{
if (UpButton)
UpButton->drop();
if (DownButton)
DownButton->drop();
}
//! called if an event happened.
bool CGUIScrollBar::OnEvent(const SEvent& event)
{
if (IsEnabled)
{
switch(event.EventType)
{
case EET_KEY_INPUT_EVENT:
if (event.KeyInput.PressedDown)
{
const s32 oldPos = Pos;
bool absorb = true;
switch (event.KeyInput.Key)
{
case KEY_LEFT:
case KEY_UP:
setPos(Pos-SmallStep);
break;
case KEY_RIGHT:
case KEY_DOWN:
setPos(Pos+SmallStep);
break;
case KEY_HOME:
setPos(Min);
break;
case KEY_PRIOR:
setPos(Pos-LargeStep);
break;
case KEY_END:
setPos(Max);
break;
case KEY_NEXT:
setPos(Pos+LargeStep);
break;
default:
absorb = false;
}
if (Pos != oldPos)
{
SEvent newEvent;
newEvent.EventType = EET_GUI_EVENT;
newEvent.GUIEvent.Caller = this;
newEvent.GUIEvent.Element = 0;
newEvent.GUIEvent.EventType = EGET_SCROLL_BAR_CHANGED;
Parent->OnEvent(newEvent);
}
if (absorb)
return true;
}
break;
case EET_GUI_EVENT:
if (event.GUIEvent.EventType == EGET_BUTTON_CLICKED)
{
if (event.GUIEvent.Caller == UpButton)
setPos(Pos-SmallStep);
else
if (event.GUIEvent.Caller == DownButton)
setPos(Pos+SmallStep);
SEvent newEvent;
newEvent.EventType = EET_GUI_EVENT;
newEvent.GUIEvent.Caller = this;
newEvent.GUIEvent.Element = 0;
newEvent.GUIEvent.EventType = EGET_SCROLL_BAR_CHANGED;
Parent->OnEvent(newEvent);
return true;
}
else
if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST)
{
if (event.GUIEvent.Caller == this)
Dragging = false;
}
break;
case EET_MOUSE_INPUT_EVENT:
{
const core::position2di p(event.MouseInput.X, event.MouseInput.Y);
bool isInside = isPointInside ( p );
switch(event.MouseInput.Event)
{
case EMIE_MOUSE_WHEEL:
if (Environment->hasFocus(this))
- {
+ {
// thanks to a bug report by REAPER
// thanks to tommi by tommi for another bugfix
// everybody needs a little thanking. hallo niko!;-)
- setPos( getPos() +
+ setPos( getPos() +
( (s32)event.MouseInput.Wheel * SmallStep * (Horizontal ? 1 : -1 ) )
);
SEvent newEvent;
newEvent.EventType = EET_GUI_EVENT;
newEvent.GUIEvent.Caller = this;
newEvent.GUIEvent.Element = 0;
newEvent.GUIEvent.EventType = EGET_SCROLL_BAR_CHANGED;
Parent->OnEvent(newEvent);
return true;
}
break;
case EMIE_LMOUSE_PRESSED_DOWN:
{
if (isInside)
{
Dragging = true;
DraggedBySlider = SliderRect.isPointInside(p);
TrayClick = !DraggedBySlider;
DesiredPos = getPosFromMousePos(p);
Environment->setFocus ( this );
return true;
}
break;
}
case EMIE_LMOUSE_LEFT_UP:
case EMIE_MOUSE_MOVED:
{
if ( !event.MouseInput.isLeftPressed () )
Dragging = false;
if ( !Dragging )
return isInside;
if ( event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP )
Dragging = false;
const s32 newPos = getPosFromMousePos(p);
const s32 oldPos = Pos;
if (!DraggedBySlider)
{
if ( isInside )
{
DraggedBySlider = SliderRect.isPointInside(p);
TrayClick = !DraggedBySlider;
}
if (DraggedBySlider)
{
setPos(newPos);
}
else
{
TrayClick = false;
if (event.MouseInput.Event == EMIE_MOUSE_MOVED)
return isInside;
}
}
-
+
if (DraggedBySlider)
{
setPos(newPos);
}
else
{
DesiredPos = newPos;
}
if (Pos != oldPos && Parent)
{
SEvent newEvent;
newEvent.EventType = EET_GUI_EVENT;
newEvent.GUIEvent.Caller = this;
newEvent.GUIEvent.Element = 0;
newEvent.GUIEvent.EventType = EGET_SCROLL_BAR_CHANGED;
Parent->OnEvent(newEvent);
}
return isInside;
} break;
default:
break;
}
} break;
default:
break;
}
}
return IGUIElement::OnEvent(event);
}
void CGUIScrollBar::OnPostRender(u32 timeMs)
{
if (Dragging && !DraggedBySlider && TrayClick && timeMs > LastChange + 200)
{
LastChange = timeMs;
const s32 oldPos = Pos;
if (DesiredPos >= Pos + LargeStep)
setPos(Pos + LargeStep);
else
if (DesiredPos <= Pos - LargeStep)
setPos(Pos - LargeStep);
else
if (DesiredPos >= Pos - LargeStep && DesiredPos <= Pos + LargeStep)
setPos(DesiredPos);
if (Pos != oldPos && Parent)
{
SEvent newEvent;
newEvent.EventType = EET_GUI_EVENT;
newEvent.GUIEvent.Caller = this;
newEvent.GUIEvent.Element = 0;
newEvent.GUIEvent.EventType = EGET_SCROLL_BAR_CHANGED;
Parent->OnEvent(newEvent);
}
}
}
//! draws the element and its children
void CGUIScrollBar::draw()
{
if (!IsVisible)
return;
IGUISkin* skin = Environment->getSkin();
if (!skin)
return;
SliderRect = AbsoluteRect;
// draws the background
skin->draw2DRectangle(this, skin->getColor(EGDC_SCROLLBAR), SliderRect, &AbsoluteClippingRect);
if ( core::isnotzero ( range() ) )
{
// recalculate slider rectangle
if (Horizontal)
{
SliderRect.UpperLeftCorner.X = AbsoluteRect.UpperLeftCorner.X + DrawPos + RelativeRect.getHeight() - DrawHeight/2;
SliderRect.LowerRightCorner.X = SliderRect.UpperLeftCorner.X + DrawHeight;
}
else
{
SliderRect.UpperLeftCorner.Y = AbsoluteRect.UpperLeftCorner.Y + DrawPos + RelativeRect.getWidth() - DrawHeight/2;
SliderRect.LowerRightCorner.Y = SliderRect.UpperLeftCorner.Y + DrawHeight;
}
skin->draw3DButtonPaneStandard(this, SliderRect, &AbsoluteClippingRect);
}
// draw buttons
IGUIElement::draw();
}
void CGUIScrollBar::updateAbsolutePosition()
{
IGUIElement::updateAbsolutePosition();
// todo: properly resize
refreshControls();
setPos ( Pos );
}
//!
s32 CGUIScrollBar::getPosFromMousePos(const core::position2di &pos) const
{
f32 w, p;
if (Horizontal)
{
w = RelativeRect.getWidth() - f32(RelativeRect.getHeight())*3.0f;
p = pos.X - AbsoluteRect.UpperLeftCorner.X - RelativeRect.getHeight()*1.5f;
}
else
{
w = RelativeRect.getHeight() - f32(RelativeRect.getWidth())*3.0f;
p = pos.Y - AbsoluteRect.UpperLeftCorner.Y - RelativeRect.getWidth()*1.5f;
}
return (s32) ( p/w * range() ) + Min;
}
//! sets the position of the scrollbar
void CGUIScrollBar::setPos(s32 pos)
{
Pos = core::s32_clamp ( pos, Min, Max );
if (Horizontal)
{
f32 f = (RelativeRect.getWidth() - ((f32)RelativeRect.getHeight()*3.0f)) / range();
DrawPos = (s32)( ( ( Pos - Min ) * f) + ((f32)RelativeRect.getHeight() * 0.5f));
DrawHeight = RelativeRect.getHeight();
}
else
{
f32 f = (RelativeRect.getHeight() - ((f32)RelativeRect.getWidth()*3.0f)) / range();
DrawPos = (s32)( ( ( Pos - Min ) * f) + ((f32)RelativeRect.getWidth() * 0.5f));
DrawHeight = RelativeRect.getWidth();
}
}
//! gets the small step value
s32 CGUIScrollBar::getSmallStep() const
{
return SmallStep;
}
//! sets the small step value
void CGUIScrollBar::setSmallStep(s32 step)
{
if (step > 0)
SmallStep = step;
else
SmallStep = 10;
}
//! gets the small step value
s32 CGUIScrollBar::getLargeStep() const
{
return LargeStep;
}
//! sets the small step value
void CGUIScrollBar::setLargeStep(s32 step)
{
if (step > 0)
LargeStep = step;
else
LargeStep = 50;
}
//! gets the maximum value of the scrollbar.
s32 CGUIScrollBar::getMax() const
{
return Max;
}
//! sets the maximum value of the scrollbar.
void CGUIScrollBar::setMax(s32 max)
{
Max = core::max_ ( max, Min );
bool enable = core::isnotzero ( range() );
UpButton->setEnabled(enable);
DownButton->setEnabled(enable);
setPos(Pos);
}
-//! gets the maximum value of the scrollbar.
+//! gets the minimum value of the scrollbar.
s32 CGUIScrollBar::getMin() const
{
return Min;
}
//! sets the minimum value of the scrollbar.
void CGUIScrollBar::setMin(s32 min)
{
Min = core::min_ ( min, Max );
bool enable = core::isnotzero ( range() );
UpButton->setEnabled(enable);
DownButton->setEnabled(enable);
setPos(Pos);
}
//! gets the current position of the scrollbar
s32 CGUIScrollBar::getPos() const
{
return Pos;
}
//! refreshes the position and text on child buttons
void CGUIScrollBar::refreshControls()
{
video::SColor color(255,255,255,255);
IGUISkin* skin = Environment->getSkin();
IGUISpriteBank* sprites = 0;
if (skin)
{
sprites = skin->getSpriteBank();
color = skin->getColor(EGDC_WINDOW_SYMBOL);
}
if (Horizontal)
{
s32 h = RelativeRect.getHeight();
if (!UpButton)
{
UpButton = new CGUIButton(Environment, this, -1, core::rect<s32>(0,0, h, h), NoClip);
UpButton->setSubElement(true);
UpButton->setTabStop(false);
}
if (sprites)
{
UpButton->setSpriteBank(sprites);
UpButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_CURSOR_LEFT), color);
UpButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_CURSOR_LEFT), color);
}
UpButton->setRelativePosition(core::rect<s32>(0,0, h, h));
UpButton->setAlignment(EGUIA_UPPERLEFT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT);
if (!DownButton)
{
DownButton = new CGUIButton(Environment, this, -1, core::rect<s32>(RelativeRect.getWidth()-h, 0, RelativeRect.getWidth(), h), NoClip);
DownButton->setSubElement(true);
DownButton->setTabStop(false);
}
if (sprites)
{
DownButton->setSpriteBank(sprites);
DownButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_CURSOR_RIGHT), color);
DownButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_CURSOR_RIGHT), color);
}
DownButton->setRelativePosition(core::rect<s32>(RelativeRect.getWidth()-h, 0, RelativeRect.getWidth(), h));
DownButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT);
}
else
{
s32 w = RelativeRect.getWidth();
if (!UpButton)
{
UpButton = new CGUIButton(Environment, this, -1, core::rect<s32>(0,0, w, w), NoClip);
UpButton->setSubElement(true);
UpButton->setTabStop(false);
}
if (sprites)
{
UpButton->setSpriteBank(sprites);
UpButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_CURSOR_UP), color);
UpButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_CURSOR_UP), color);
}
UpButton->setRelativePosition(core::rect<s32>(0,0, w, w));
UpButton->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
if (!DownButton)
{
DownButton = new CGUIButton(Environment, this, -1, core::rect<s32>(0,RelativeRect.getHeight()-w, w, RelativeRect.getHeight()), NoClip);
DownButton->setSubElement(true);
DownButton->setTabStop(false);
}
if (sprites)
{
DownButton->setSpriteBank(sprites);
DownButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_CURSOR_DOWN), color);
DownButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_CURSOR_DOWN), color);
}
DownButton->setRelativePosition(core::rect<s32>(0,RelativeRect.getHeight()-w, w, RelativeRect.getHeight()));
DownButton->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT);
}
}
//! Writes attributes of the element.
void CGUIScrollBar::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const
{
IGUIScrollBar::serializeAttributes(out,options);
out->addBool("Horizontal", Horizontal);
out->addInt ("Value", Pos);
out->addInt ("Min", Min);
out->addInt ("Max", Max);
out->addInt ("SmallStep", SmallStep);
out->addInt ("LargeStep", LargeStep);
}
//! Reads attributes of the element
void CGUIScrollBar::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0)
{
IGUIScrollBar::deserializeAttributes(in,options);
Horizontal = in->getAttributeAsBool("Horizontal");
setMin(in->getAttributeAsInt("Min"));
setMax(in->getAttributeAsInt("Max"));
setPos(in->getAttributeAsInt("Value"));
setSmallStep(in->getAttributeAsInt("SmallStep"));
setLargeStep(in->getAttributeAsInt("LargeStep"));
refreshControls();
}
} // end namespace gui
} // end namespace irr
#endif // _IRR_COMPILE_WITH_GUI_
diff --git a/source/Irrlicht/CGUIScrollBar.h b/source/Irrlicht/CGUIScrollBar.h
index 6077e98..2e65695 100644
--- a/source/Irrlicht/CGUIScrollBar.h
+++ b/source/Irrlicht/CGUIScrollBar.h
@@ -1,112 +1,112 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_GUI_SCROLL_BAR_H_INCLUDED__
#define __C_GUI_SCROLL_BAR_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include "IGUIScrollBar.h"
#include "IGUIButton.h"
namespace irr
{
namespace gui
{
class CGUIScrollBar : public IGUIScrollBar
{
public:
//! constructor
CGUIScrollBar(bool horizontal, IGUIEnvironment* environment,
IGUIElement* parent, s32 id, core::rect<s32> rectangle,
bool noclip=false);
//! destructor
virtual ~CGUIScrollBar();
//! called if an event happened.
virtual bool OnEvent(const SEvent& event);
//! draws the element and its children
virtual void draw();
virtual void OnPostRender(u32 timeMs);
//! gets the maximum value of the scrollbar.
virtual s32 getMax() const;
//! sets the maximum value of the scrollbar.
virtual void setMax(s32 max);
//! gets the minimum value of the scrollbar.
virtual s32 getMin() const;
//! sets the minimum value of the scrollbar.
- virtual void setMin(s32 max);
+ virtual void setMin(s32 min);
//! gets the small step value
virtual s32 getSmallStep() const;
//! sets the small step value
virtual void setSmallStep(s32 step);
//! gets the large step value
virtual s32 getLargeStep() const;
//! sets the large step value
virtual void setLargeStep(s32 step);
//! gets the current position of the scrollbar
virtual s32 getPos() const;
//! sets the position of the scrollbar
virtual void setPos(s32 pos);
//! updates the rectangle
virtual void updateAbsolutePosition();
//! Writes attributes of the element.
virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const;
//! Reads attributes of the element
virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options);
private:
void refreshControls();
s32 getPosFromMousePos(const core::position2di &p) const;
IGUIButton* UpButton;
IGUIButton* DownButton;
core::rect<s32> SliderRect;
bool Dragging;
bool Horizontal;
bool DraggedBySlider;
bool TrayClick;
s32 Pos;
s32 DrawPos;
s32 DrawHeight;
s32 Min;
s32 Max;
s32 SmallStep;
s32 LargeStep;
s32 DesiredPos;
u32 LastChange;
f32 range () const { return (f32) ( Max - Min ); }
};
} // end namespace gui
} // end namespace irr
#endif // _IRR_COMPILE_WITH_GUI_
#endif
|
paupawsan/Irrlicht
|
99b0e4881eed60f35df067d545a659a8ae354681
|
Bugfix: Clear up depth-textures which could not be attached in OpenGL to prevent crashes.
|
diff --git a/source/Irrlicht/COpenGLDriver.cpp b/source/Irrlicht/COpenGLDriver.cpp
index dc424c6..810e320 100644
--- a/source/Irrlicht/COpenGLDriver.cpp
+++ b/source/Irrlicht/COpenGLDriver.cpp
@@ -3033,1024 +3033,1028 @@ void COpenGLDriver::assignHardwareLight(u32 lightIndex)
glLightf(lidx, GL_SPOT_EXPONENT, 0.0f);
glLightf(lidx, GL_SPOT_CUTOFF, 180.0f);
break;
}
// set diffuse color
data[0] = light.DiffuseColor.r;
data[1] = light.DiffuseColor.g;
data[2] = light.DiffuseColor.b;
data[3] = light.DiffuseColor.a;
glLightfv(lidx, GL_DIFFUSE, data);
// set specular color
data[0] = light.SpecularColor.r;
data[1] = light.SpecularColor.g;
data[2] = light.SpecularColor.b;
data[3] = light.SpecularColor.a;
glLightfv(lidx, GL_SPECULAR, data);
// set ambient color
data[0] = light.AmbientColor.r;
data[1] = light.AmbientColor.g;
data[2] = light.AmbientColor.b;
data[3] = light.AmbientColor.a;
glLightfv(lidx, GL_AMBIENT, data);
// 1.0f / (constant + linear * d + quadratic*(d*d);
// set attenuation
glLightf(lidx, GL_CONSTANT_ATTENUATION, light.Attenuation.X);
glLightf(lidx, GL_LINEAR_ATTENUATION, light.Attenuation.Y);
glLightf(lidx, GL_QUADRATIC_ATTENUATION, light.Attenuation.Z);
glEnable(lidx);
}
//! Turns a dynamic light on or off
//! \param lightIndex: the index returned by addDynamicLight
//! \param turnOn: true to turn the light on, false to turn it off
void COpenGLDriver::turnLightOn(s32 lightIndex, bool turnOn)
{
if(lightIndex < 0 || lightIndex >= (s32)RequestedLights.size())
return;
RequestedLight & requestedLight = RequestedLights[lightIndex];
requestedLight.DesireToBeOn = turnOn;
if(turnOn)
{
if(-1 == requestedLight.HardwareLightIndex)
assignHardwareLight(lightIndex);
}
else
{
if(-1 != requestedLight.HardwareLightIndex)
{
// It's currently assigned, so free up the hardware light
glDisable(requestedLight.HardwareLightIndex);
requestedLight.HardwareLightIndex = -1;
// Now let the first light that's waiting on a free hardware light grab it
for(u32 requested = 0; requested < RequestedLights.size(); ++requested)
if(RequestedLights[requested].DesireToBeOn
&&
-1 == RequestedLights[requested].HardwareLightIndex)
{
assignHardwareLight(requested);
break;
}
}
}
}
//! returns the maximal amount of dynamic lights the device can handle
u32 COpenGLDriver::getMaximalDynamicLightAmount() const
{
return MaxLights;
}
//! Sets the dynamic ambient light color. The default color is
//! (0,0,0,0) which means it is dark.
//! \param color: New color of the ambient light.
void COpenGLDriver::setAmbientLight(const SColorf& color)
{
GLfloat data[4] = {color.r, color.g, color.b, color.a};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, data);
}
// this code was sent in by Oliver Klems, thank you! (I modified the glViewport
// method just a bit.
void COpenGLDriver::setViewPort(const core::rect<s32>& area)
{
core::rect<s32> vp = area;
core::rect<s32> rendert(0,0, getCurrentRenderTargetSize().Width, getCurrentRenderTargetSize().Height);
vp.clipAgainst(rendert);
if (vp.getHeight()>0 && vp.getWidth()>0)
glViewport(vp.UpperLeftCorner.X,
getCurrentRenderTargetSize().Height - vp.UpperLeftCorner.Y - vp.getHeight(),
vp.getWidth(), vp.getHeight());
ViewPort = vp;
}
//! Draws a shadow volume into the stencil buffer. To draw a stencil shadow, do
//! this: First, draw all geometry. Then use this method, to draw the shadow
//! volume. Next use IVideoDriver::drawStencilShadow() to visualize the shadow.
void COpenGLDriver::drawStencilShadowVolume(const core::vector3df* triangles, s32 count, bool zfail)
{
if (!StencilBuffer || !count)
return;
// unset last 3d material
if (CurrentRenderMode == ERM_3D &&
static_cast<u32>(Material.MaterialType) < MaterialRenderers.size())
{
MaterialRenderers[Material.MaterialType].Renderer->OnUnsetMaterial();
ResetRenderStates = true;
}
// store current OpenGL state
glPushAttrib(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT |
GL_POLYGON_BIT | GL_STENCIL_BUFFER_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_FOG);
glDepthFunc(GL_LEQUAL);
glDepthMask(GL_FALSE); // no depth buffer writing
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // no color buffer drawing
glEnable(GL_STENCIL_TEST);
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(0.0f, 1.0f);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3,GL_FLOAT,sizeof(core::vector3df),&triangles[0]);
glStencilMask(~0);
glStencilFunc(GL_ALWAYS, 0, ~0);
GLenum incr = GL_INCR;
GLenum decr = GL_DECR;
#ifdef GL_EXT_stencil_wrap
if (FeatureAvailable[IRR_EXT_stencil_wrap])
{
incr = GL_INCR_WRAP_EXT;
decr = GL_DECR_WRAP_EXT;
}
#endif
// The first parts are not correctly working, yet.
#if 0
#ifdef GL_EXT_stencil_two_side
if (FeatureAvailable[IRR_EXT_stencil_two_side])
{
glEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);
#ifdef GL_NV_depth_clamp
if (FeatureAvailable[IRR_NV_depth_clamp])
glEnable(GL_DEPTH_CLAMP_NV);
#endif
glDisable(GL_CULL_FACE);
if (!zfail)
{
// ZPASS Method
extGlActiveStencilFace(GL_BACK);
glStencilOp(GL_KEEP, GL_KEEP, decr);
glStencilMask(~0);
glStencilFunc(GL_ALWAYS, 0, ~0);
extGlActiveStencilFace(GL_FRONT);
glStencilOp(GL_KEEP, GL_KEEP, incr);
glStencilMask(~0);
glStencilFunc(GL_ALWAYS, 0, ~0);
glDrawArrays(GL_TRIANGLES,0,count);
}
else
{
// ZFAIL Method
extGlActiveStencilFace(GL_BACK);
glStencilOp(GL_KEEP, incr, GL_KEEP);
glStencilMask(~0);
glStencilFunc(GL_ALWAYS, 0, ~0);
extGlActiveStencilFace(GL_FRONT);
glStencilOp(GL_KEEP, decr, GL_KEEP);
glStencilMask(~0);
glStencilFunc(GL_ALWAYS, 0, ~0);
glDrawArrays(GL_TRIANGLES,0,count);
}
}
else
#endif
if (FeatureAvailable[IRR_ATI_separate_stencil])
{
glDisable(GL_CULL_FACE);
if (!zfail)
{
// ZPASS Method
extGlStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, decr);
extGlStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, incr);
extGlStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, 0, ~0);
glStencilMask(~0);
glDrawArrays(GL_TRIANGLES,0,count);
}
else
{
// ZFAIL Method
extGlStencilOpSeparate(GL_BACK, GL_KEEP, incr, GL_KEEP);
extGlStencilOpSeparate(GL_FRONT, GL_KEEP, decr, GL_KEEP);
extGlStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, 0, ~0);
glDrawArrays(GL_TRIANGLES,0,count);
}
}
else
#endif
{
glEnable(GL_CULL_FACE);
if (!zfail)
{
// ZPASS Method
glCullFace(GL_BACK);
glStencilOp(GL_KEEP, GL_KEEP, incr);
glDrawArrays(GL_TRIANGLES,0,count);
glCullFace(GL_FRONT);
glStencilOp(GL_KEEP, GL_KEEP, decr);
glDrawArrays(GL_TRIANGLES,0,count);
}
else
{
// ZFAIL Method
glStencilOp(GL_KEEP, incr, GL_KEEP);
glCullFace(GL_FRONT);
glDrawArrays(GL_TRIANGLES,0,count);
glStencilOp(GL_KEEP, decr, GL_KEEP);
glCullFace(GL_BACK);
glDrawArrays(GL_TRIANGLES,0,count);
}
}
glDisableClientState(GL_VERTEX_ARRAY); //not stored on stack
glPopAttrib();
}
void COpenGLDriver::drawStencilShadow(bool clearStencilBuffer, video::SColor leftUpEdge,
video::SColor rightUpEdge, video::SColor leftDownEdge, video::SColor rightDownEdge)
{
if (!StencilBuffer)
return;
disableTextures();
// store attributes
glPushAttrib(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT | GL_POLYGON_BIT | GL_STENCIL_BUFFER_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_FOG);
glDepthMask(GL_FALSE);
glShadeModel(GL_FLAT);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_NOTEQUAL, 0, ~0);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
// draw a shadow rectangle covering the entire screen using stencil buffer
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glBegin(GL_QUADS);
glColor4ub(leftDownEdge.getRed(), leftDownEdge.getGreen(), leftDownEdge.getBlue(), leftDownEdge.getAlpha());
glVertex3f(-1.f,-1.f,-0.9f);
glColor4ub(leftUpEdge.getRed(), leftUpEdge.getGreen(), leftUpEdge.getBlue(), leftUpEdge.getAlpha());
glVertex3f(-1.f, 1.f,-0.9f);
glColor4ub(rightUpEdge.getRed(), rightUpEdge.getGreen(), rightUpEdge.getBlue(), rightUpEdge.getAlpha());
glVertex3f(1.f, 1.f,-0.9f);
glColor4ub(rightDownEdge.getRed(), rightDownEdge.getGreen(), rightDownEdge.getBlue(), rightDownEdge.getAlpha());
glVertex3f(1.f,-1.f,-0.9f);
glEnd();
clearBuffers(false, false, clearStencilBuffer, 0x0);
// restore settings
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();
}
//! Sets the fog mode.
void COpenGLDriver::setFog(SColor c, E_FOG_TYPE fogType, f32 start,
f32 end, f32 density, bool pixelFog, bool rangeFog)
{
CNullDriver::setFog(c, fogType, start, end, density, pixelFog, rangeFog);
glFogf(GL_FOG_MODE, GLfloat((fogType==EFT_FOG_LINEAR)? GL_LINEAR : (fogType==EFT_FOG_EXP)?GL_EXP:GL_EXP2));
#ifdef GL_EXT_fog_coord
if (FeatureAvailable[IRR_EXT_fog_coord])
glFogi(GL_FOG_COORDINATE_SOURCE, GL_FRAGMENT_DEPTH);
#endif
#ifdef GL_NV_fog_distance
if (FeatureAvailable[IRR_NV_fog_distance])
{
if (rangeFog)
glFogi(GL_FOG_DISTANCE_MODE_NV, GL_EYE_RADIAL_NV);
else
glFogi(GL_FOG_DISTANCE_MODE_NV, GL_EYE_PLANE_ABSOLUTE_NV);
}
#endif
if (fogType==EFT_FOG_LINEAR)
{
glFogf(GL_FOG_START, start);
glFogf(GL_FOG_END, end);
}
else
glFogf(GL_FOG_DENSITY, density);
if (pixelFog)
glHint(GL_FOG_HINT, GL_NICEST);
else
glHint(GL_FOG_HINT, GL_FASTEST);
SColorf color(c);
GLfloat data[4] = {color.r, color.g, color.b, color.a};
glFogfv(GL_FOG_COLOR, data);
}
//! Draws a 3d line.
void COpenGLDriver::draw3DLine(const core::vector3df& start,
const core::vector3df& end, SColor color)
{
setRenderStates3DMode();
glBegin(GL_LINES);
glColor4ub(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
glVertex3f(start.X, start.Y, start.Z);
glVertex3f(end.X, end.Y, end.Z);
glEnd();
}
//! Only used by the internal engine. Used to notify the driver that
//! the window was resized.
void COpenGLDriver::OnResize(const core::dimension2d<u32>& size)
{
CNullDriver::OnResize(size);
glViewport(0, 0, size.Width, size.Height);
Transformation3DChanged = true;
}
//! Returns type of video driver
E_DRIVER_TYPE COpenGLDriver::getDriverType() const
{
return EDT_OPENGL;
}
//! returns color format
ECOLOR_FORMAT COpenGLDriver::getColorFormat() const
{
return ColorFormat;
}
//! Sets a vertex shader constant.
void COpenGLDriver::setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
{
#ifdef GL_ARB_vertex_program
for (s32 i=0; i<constantAmount; ++i)
extGlProgramLocalParameter4fv(GL_VERTEX_PROGRAM_ARB, startRegister+i, &data[i*4]);
#endif
}
//! Sets a pixel shader constant.
void COpenGLDriver::setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
{
#ifdef GL_ARB_fragment_program
for (s32 i=0; i<constantAmount; ++i)
extGlProgramLocalParameter4fv(GL_FRAGMENT_PROGRAM_ARB, startRegister+i, &data[i*4]);
#endif
}
//! Sets a constant for the vertex shader based on a name.
bool COpenGLDriver::setVertexShaderConstant(const c8* name, const f32* floats, int count)
{
//pass this along, as in GLSL the same routine is used for both vertex and fragment shaders
return setPixelShaderConstant(name, floats, count);
}
//! Sets a constant for the pixel shader based on a name.
bool COpenGLDriver::setPixelShaderConstant(const c8* name, const f32* floats, int count)
{
os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
return false;
}
//! Adds a new material renderer to the VideoDriver, using pixel and/or
//! vertex shaders to render geometry.
s32 COpenGLDriver::addShaderMaterial(const c8* vertexShaderProgram,
const c8* pixelShaderProgram,
IShaderConstantSetCallBack* callback,
E_MATERIAL_TYPE baseMaterial, s32 userData)
{
s32 nr = -1;
COpenGLShaderMaterialRenderer* r = new COpenGLShaderMaterialRenderer(
this, nr, vertexShaderProgram, pixelShaderProgram,
callback, getMaterialRenderer(baseMaterial), userData);
r->drop();
return nr;
}
//! Adds a new material renderer to the VideoDriver, using GLSL to render geometry.
s32 COpenGLDriver::addHighLevelShaderMaterial(
const c8* vertexShaderProgram,
const c8* vertexShaderEntryPointName,
E_VERTEX_SHADER_TYPE vsCompileTarget,
const c8* pixelShaderProgram,
const c8* pixelShaderEntryPointName,
E_PIXEL_SHADER_TYPE psCompileTarget,
const c8* geometryShaderProgram,
const c8* geometryShaderEntryPointName,
E_GEOMETRY_SHADER_TYPE gsCompileTarget,
scene::E_PRIMITIVE_TYPE inType,
scene::E_PRIMITIVE_TYPE outType,
u32 verticesOut,
IShaderConstantSetCallBack* callback,
E_MATERIAL_TYPE baseMaterial,
s32 userData)
{
s32 nr = -1;
COpenGLSLMaterialRenderer* r = new COpenGLSLMaterialRenderer(
this, nr,
vertexShaderProgram, vertexShaderEntryPointName, vsCompileTarget,
pixelShaderProgram, pixelShaderEntryPointName, psCompileTarget,
geometryShaderProgram, geometryShaderEntryPointName, gsCompileTarget,
inType, outType, verticesOut,
callback,getMaterialRenderer(baseMaterial), userData);
r->drop();
return nr;
}
//! Returns a pointer to the IVideoDriver interface. (Implementation for
//! IMaterialRendererServices)
IVideoDriver* COpenGLDriver::getVideoDriver()
{
return this;
}
ITexture* COpenGLDriver::addRenderTargetTexture(const core::dimension2d<u32>& size,
const io::path& name,
const ECOLOR_FORMAT format)
{
//disable mip-mapping
bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS);
setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false);
video::ITexture* rtt = 0;
#if defined(GL_EXT_framebuffer_object)
// if driver supports FrameBufferObjects, use them
if (queryFeature(EVDF_FRAMEBUFFER_OBJECT))
{
rtt = new COpenGLFBOTexture(size, name, this, format);
if (rtt)
{
bool success = false;
addTexture(rtt);
ITexture* tex = createDepthTexture(rtt);
if (tex)
{
success = static_cast<video::COpenGLFBODepthTexture*>(tex)->attach(rtt);
+ if ( !success )
+ {
+ removeDepthTexture(tex);
+ }
tex->drop();
}
rtt->drop();
if (!success)
{
removeTexture(rtt);
rtt=0;
}
}
}
else
#endif
{
// the simple texture is only possible for size <= screensize
// we try to find an optimal size with the original constraints
core::dimension2du destSize(core::min_(size.Width,ScreenSize.Width), core::min_(size.Height,ScreenSize.Height));
destSize = destSize.getOptimalSize((size==size.getOptimalSize()), false, false);
rtt = addTexture(destSize, name, ECF_A8R8G8B8);
if (rtt)
{
static_cast<video::COpenGLTexture*>(rtt)->setIsRenderTarget(true);
}
}
//restore mip-mapping
setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels);
return rtt;
}
//! Returns the maximum amount of primitives (mostly vertices) which
//! the device is able to render with one drawIndexedTriangleList
//! call.
u32 COpenGLDriver::getMaximalPrimitiveCount() const
{
return 0x7fffffff;
}
//! set or reset render target
bool COpenGLDriver::setRenderTarget(video::E_RENDER_TARGET target, bool clearTarget,
bool clearZBuffer, SColor color)
{
if (target != CurrentTarget)
setRenderTarget(0, false, false, 0x0);
if (ERT_RENDER_TEXTURE == target)
{
os::Printer::log("Fatal Error: For render textures call setRenderTarget with the actual texture as first parameter.", ELL_ERROR);
return false;
}
if (Stereo && (ERT_STEREO_RIGHT_BUFFER == target))
{
if (Doublebuffer)
glDrawBuffer(GL_BACK_RIGHT);
else
glDrawBuffer(GL_FRONT_RIGHT);
}
else if (Stereo && ERT_STEREO_BOTH_BUFFERS == target)
{
if (Doublebuffer)
glDrawBuffer(GL_BACK);
else
glDrawBuffer(GL_FRONT);
}
else if ((target >= ERT_AUX_BUFFER0) && (target-ERT_AUX_BUFFER0 < MaxAuxBuffers))
{
glDrawBuffer(GL_AUX0+target-ERT_AUX_BUFFER0);
}
else
{
if (Doublebuffer)
glDrawBuffer(GL_BACK_LEFT);
else
glDrawBuffer(GL_FRONT_LEFT);
// exit with false, but also with working color buffer
if (target != ERT_FRAME_BUFFER)
return false;
}
CurrentTarget=target;
clearBuffers(clearTarget, clearZBuffer, false, color);
return true;
}
//! set or reset render target
bool COpenGLDriver::setRenderTarget(video::ITexture* texture, bool clearBackBuffer,
bool clearZBuffer, SColor color)
{
// check for right driver type
if (texture && texture->getDriverType() != EDT_OPENGL)
{
os::Printer::log("Fatal Error: Tried to set a texture not owned by this driver.", ELL_ERROR);
return false;
}
// check if we should set the previous RT back
setActiveTexture(0, 0);
ResetRenderStates=true;
if (RenderTargetTexture!=0)
{
RenderTargetTexture->unbindRTT();
}
if (texture)
{
// we want to set a new target. so do this.
glViewport(0, 0, texture->getSize().Width, texture->getSize().Height);
RenderTargetTexture = static_cast<COpenGLTexture*>(texture);
RenderTargetTexture->bindRTT();
CurrentRendertargetSize = texture->getSize();
CurrentTarget=ERT_RENDER_TEXTURE;
}
else
{
glViewport(0,0,ScreenSize.Width,ScreenSize.Height);
RenderTargetTexture = 0;
CurrentRendertargetSize = core::dimension2d<u32>(0,0);
CurrentTarget=ERT_FRAME_BUFFER;
glDrawBuffer(Doublebuffer?GL_BACK_LEFT:GL_FRONT_LEFT);
}
clearBuffers(clearBackBuffer, clearZBuffer, false, color);
return true;
}
//! Sets multiple render targets
bool COpenGLDriver::setRenderTarget(const core::array<video::IRenderTarget>& targets,
bool clearBackBuffer, bool clearZBuffer, SColor color)
{
if (targets.size()==0)
return setRenderTarget(0, clearBackBuffer, clearZBuffer, color);
u32 maxMultipleRTTs = core::min_(static_cast<u32>(MaxMultipleRenderTargets), targets.size());
// determine common size
core::dimension2du rttSize = CurrentRendertargetSize;
if (targets[0].TargetType==ERT_RENDER_TEXTURE)
{
if (!targets[0].RenderTexture)
{
os::Printer::log("Missing render texture for MRT.", ELL_ERROR);
return false;
}
rttSize=targets[0].RenderTexture->getSize();
}
for (u32 i = 0; i < maxMultipleRTTs; ++i)
{
// check for right driver type
if (targets[i].TargetType==ERT_RENDER_TEXTURE)
{
if (!targets[i].RenderTexture)
{
maxMultipleRTTs=i;
os::Printer::log("Missing render texture for MRT.", ELL_WARNING);
break;
}
if (targets[i].RenderTexture->getDriverType() != EDT_OPENGL)
{
maxMultipleRTTs=i;
os::Printer::log("Tried to set a texture not owned by this driver.", ELL_WARNING);
break;
}
// check for valid render target
if (!targets[i].RenderTexture->isRenderTarget() || !static_cast<COpenGLTexture*>(targets[i].RenderTexture)->isFrameBufferObject())
{
maxMultipleRTTs=i;
os::Printer::log("Tried to set a non FBO-RTT as render target.", ELL_WARNING);
break;
}
// check for valid size
if (rttSize != targets[i].RenderTexture->getSize())
{
maxMultipleRTTs=i;
os::Printer::log("Render target texture has wrong size.", ELL_WARNING);
break;
}
}
}
if (maxMultipleRTTs==0)
{
os::Printer::log("No valid MRTs.", ELL_ERROR);
return false;
}
// init FBO, if any
for (u32 i=0; i<maxMultipleRTTs; ++i)
{
if (targets[i].TargetType==ERT_RENDER_TEXTURE)
{
setRenderTarget(targets[i].RenderTexture, false, false, 0x0);
break;
}
}
// init other main buffer, if necessary
if (targets[0].TargetType!=ERT_RENDER_TEXTURE)
setRenderTarget(targets[0].TargetType, false, false, 0x0);
// attach other textures and store buffers into array
if (maxMultipleRTTs > 1)
{
CurrentTarget=ERT_MULTI_RENDER_TEXTURES;
core::array<GLenum> MRTs;
MRTs.set_used(maxMultipleRTTs);
for(u32 i = 0; i < maxMultipleRTTs; i++)
{
if (FeatureAvailable[IRR_EXT_draw_buffers2])
{
extGlColorMaskIndexed(i,
(targets[i].ColorMask & ECP_RED)?GL_TRUE:GL_FALSE,
(targets[i].ColorMask & ECP_GREEN)?GL_TRUE:GL_FALSE,
(targets[i].ColorMask & ECP_BLUE)?GL_TRUE:GL_FALSE,
(targets[i].ColorMask & ECP_ALPHA)?GL_TRUE:GL_FALSE);
if (targets[i].BlendEnable)
extGlEnableIndexed(GL_BLEND, i);
else
extGlDisableIndexed(GL_BLEND, i);
}
if (FeatureAvailable[IRR_AMD_draw_buffers_blend] || FeatureAvailable[IRR_ARB_draw_buffers_blend])
{
extGlBlendFuncIndexed(i, targets[i].BlendFuncSrc, targets[i].BlendFuncDst);
}
if (targets[i].TargetType==ERT_RENDER_TEXTURE)
{
GLenum attachment = GL_NONE;
#ifdef GL_EXT_framebuffer_object
// attach texture to FrameBuffer Object on Color [i]
attachment = GL_COLOR_ATTACHMENT0_EXT+i;
extGlFramebufferTexture2D(GL_FRAMEBUFFER_EXT, attachment, GL_TEXTURE_2D, static_cast<COpenGLTexture*>(targets[i].RenderTexture)->getOpenGLTextureName(), 0);
#endif
MRTs[i]=attachment;
}
else
{
switch(targets[i].TargetType)
{
case ERT_FRAME_BUFFER:
MRTs[i]=GL_BACK_LEFT;
break;
case ERT_STEREO_BOTH_BUFFERS:
MRTs[i]=GL_BACK;
break;
case ERT_STEREO_RIGHT_BUFFER:
MRTs[i]=GL_BACK_RIGHT;
break;
case ERT_STEREO_LEFT_BUFFER:
MRTs[i]=GL_BACK_LEFT;
break;
default:
MRTs[i]=GL_AUX0+(targets[i].TargetType-ERT_AUX_BUFFER0);
break;
}
}
}
extGlDrawBuffers(maxMultipleRTTs, MRTs.const_pointer());
}
clearBuffers(clearBackBuffer, clearZBuffer, false, color);
return true;
}
// returns the current size of the screen or rendertarget
const core::dimension2d<u32>& COpenGLDriver::getCurrentRenderTargetSize() const
{
if (CurrentRendertargetSize.Width == 0)
return ScreenSize;
else
return CurrentRendertargetSize;
}
//! Clears the ZBuffer.
void COpenGLDriver::clearZBuffer()
{
clearBuffers(false, true, false, 0x0);
}
//! Returns an image created from the last rendered frame.
IImage* COpenGLDriver::createScreenShot()
{
IImage* newImage = new CImage(ECF_R8G8B8, ScreenSize);
u8* pixels = static_cast<u8*>(newImage->lock());
if (!pixels)
{
newImage->drop();
return 0;
}
// allows to read pixels in top-to-bottom order
#ifdef GL_MESA_pack_invert
if (FeatureAvailable[IRR_MESA_pack_invert])
glPixelStorei(GL_PACK_INVERT_MESA, GL_TRUE);
#endif
// We want to read the front buffer to get the latest render finished.
glReadBuffer(GL_FRONT);
glReadPixels(0, 0, ScreenSize.Width, ScreenSize.Height, GL_RGB, GL_UNSIGNED_BYTE, pixels);
glReadBuffer(GL_BACK);
#ifdef GL_MESA_pack_invert
if (FeatureAvailable[IRR_MESA_pack_invert])
glPixelStorei(GL_PACK_INVERT_MESA, GL_FALSE);
else
#endif
{
// opengl images are horizontally flipped, so we have to fix that here.
const s32 pitch=newImage->getPitch();
u8* p2 = pixels + (ScreenSize.Height - 1) * pitch;
u8* tmpBuffer = new u8[pitch];
for (u32 i=0; i < ScreenSize.Height; i += 2)
{
memcpy(tmpBuffer, pixels, pitch);
memcpy(pixels, p2, pitch);
memcpy(p2, tmpBuffer, pitch);
pixels += pitch;
p2 -= pitch;
}
delete [] tmpBuffer;
}
newImage->unlock();
if (testGLError())
{
newImage->drop();
return 0;
}
return newImage;
}
//! get depth texture for the given render target texture
ITexture* COpenGLDriver::createDepthTexture(ITexture* texture, bool shared)
{
if ((texture->getDriverType() != EDT_OPENGL) || (!texture->isRenderTarget()))
return 0;
COpenGLTexture* tex = static_cast<COpenGLTexture*>(texture);
if (!tex->isFrameBufferObject())
return 0;
if (shared)
{
for (u32 i=0; i<DepthTextures.size(); ++i)
{
if (DepthTextures[i]->getSize()==texture->getSize())
{
DepthTextures[i]->grab();
return DepthTextures[i];
}
}
DepthTextures.push_back(new COpenGLFBODepthTexture(texture->getSize(), "depth1", this));
return DepthTextures.getLast();
}
return (new COpenGLFBODepthTexture(texture->getSize(), "depth1", this));
}
void COpenGLDriver::removeDepthTexture(ITexture* texture)
{
for (u32 i=0; i<DepthTextures.size(); ++i)
{
if (texture==DepthTextures[i])
{
DepthTextures.erase(i);
return;
}
}
}
//! Set/unset a clipping plane.
bool COpenGLDriver::setClipPlane(u32 index, const core::plane3df& plane, bool enable)
{
if (index >= MaxUserClipPlanes)
return false;
UserClipPlanes[index].Plane=plane;
enableClipPlane(index, enable);
return true;
}
void COpenGLDriver::uploadClipPlane(u32 index)
{
// opengl needs an array of doubles for the plane equation
double clip_plane[4];
clip_plane[0] = UserClipPlanes[index].Plane.Normal.X;
clip_plane[1] = UserClipPlanes[index].Plane.Normal.Y;
clip_plane[2] = UserClipPlanes[index].Plane.Normal.Z;
clip_plane[3] = UserClipPlanes[index].Plane.D;
glClipPlane(GL_CLIP_PLANE0 + index, clip_plane);
}
//! Enable/disable a clipping plane.
void COpenGLDriver::enableClipPlane(u32 index, bool enable)
{
if (index >= MaxUserClipPlanes)
return;
if (enable)
{
if (!UserClipPlanes[index].Enabled)
{
uploadClipPlane(index);
glEnable(GL_CLIP_PLANE0 + index);
}
}
else
glDisable(GL_CLIP_PLANE0 + index);
UserClipPlanes[index].Enabled=enable;
}
core::dimension2du COpenGLDriver::getMaxTextureSize() const
{
return core::dimension2du(MaxTextureSize, MaxTextureSize);
}
//! Convert E_PRIMITIVE_TYPE to OpenGL equivalent
GLenum COpenGLDriver::primitiveTypeToGL(scene::E_PRIMITIVE_TYPE type) const
{
switch (type)
{
case scene::EPT_POINTS:
return GL_POINTS;
case scene::EPT_LINE_STRIP:
return GL_LINE_STRIP;
case scene::EPT_LINE_LOOP:
return GL_LINE_LOOP;
case scene::EPT_LINES:
return GL_LINES;
case scene::EPT_TRIANGLE_STRIP:
return GL_TRIANGLE_STRIP;
case scene::EPT_TRIANGLE_FAN:
return GL_TRIANGLE_FAN;
case scene::EPT_TRIANGLES:
return GL_TRIANGLES;
case scene::EPT_QUAD_STRIP:
return GL_QUAD_STRIP;
case scene::EPT_QUADS:
return GL_QUADS;
case scene::EPT_POLYGON:
return GL_POLYGON;
case scene::EPT_POINT_SPRITES:
#ifdef GL_ARB_point_sprite
return GL_POINT_SPRITE_ARB;
#else
return GL_POINTS;
#endif
}
return GL_TRIANGLES;
}
} // end namespace
} // end namespace
#endif // _IRR_COMPILE_WITH_OPENGL_
namespace irr
{
namespace video
{
// -----------------------------------
// WINDOWS VERSION
// -----------------------------------
#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_
IVideoDriver* createOpenGLDriver(const SIrrlichtCreationParameters& params,
io::IFileSystem* io, CIrrDeviceWin32* device)
{
#ifdef _IRR_COMPILE_WITH_OPENGL_
COpenGLDriver* ogl = new COpenGLDriver(params, io, device);
if (!ogl->initDriver(params, device))
{
ogl->drop();
ogl = 0;
}
return ogl;
#else
return 0;
#endif // _IRR_COMPILE_WITH_OPENGL_
}
#endif // _IRR_COMPILE_WITH_WINDOWS_DEVICE_
// -----------------------------------
// MACOSX VERSION
// -----------------------------------
#if defined(_IRR_COMPILE_WITH_OSX_DEVICE_)
IVideoDriver* createOpenGLDriver(const SIrrlichtCreationParameters& params,
io::IFileSystem* io, CIrrDeviceMacOSX *device)
{
#ifdef _IRR_COMPILE_WITH_OPENGL_
return new COpenGLDriver(params, io, device);
#else
return 0;
#endif // _IRR_COMPILE_WITH_OPENGL_
|
paupawsan/Irrlicht
|
87f40e5f5374d9a40e0f17190932d899cd8b4d90
|
Fix arrowMesh boundingbox.
|
diff --git a/source/Irrlicht/CGeometryCreator.cpp b/source/Irrlicht/CGeometryCreator.cpp
index 5843df5..251d613 100644
--- a/source/Irrlicht/CGeometryCreator.cpp
+++ b/source/Irrlicht/CGeometryCreator.cpp
@@ -1,848 +1,850 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CGeometryCreator.h"
#include "SAnimatedMesh.h"
#include "SMeshBuffer.h"
#include "SMesh.h"
#include "IMesh.h"
#include "IVideoDriver.h"
#include "CImage.h"
#include "os.h"
namespace irr
{
namespace scene
{
IMesh* CGeometryCreator::createCubeMesh(const core::vector3df& size) const
{
SMeshBuffer* buffer = new SMeshBuffer();
// Create indices
const u16 u[36] = { 0,2,1, 0,3,2, 1,5,4, 1,2,5, 4,6,7, 4,5,6,
7,3,0, 7,6,3, 9,5,2, 9,8,5, 0,11,10, 0,10,7};
buffer->Indices.set_used(36);
for (u32 i=0; i<36; ++i)
buffer->Indices[i] = u[i];
// Create vertices
video::SColor clr(255,255,255,255);
buffer->Vertices.reallocate(12);
buffer->Vertices.push_back(video::S3DVertex(0,0,0, -1,-1,-1, clr, 0, 1));
buffer->Vertices.push_back(video::S3DVertex(1,0,0, 1,-1,-1, clr, 1, 1));
buffer->Vertices.push_back(video::S3DVertex(1,1,0, 1, 1,-1, clr, 1, 0));
buffer->Vertices.push_back(video::S3DVertex(0,1,0, -1, 1,-1, clr, 0, 0));
buffer->Vertices.push_back(video::S3DVertex(1,0,1, 1,-1, 1, clr, 0, 1));
buffer->Vertices.push_back(video::S3DVertex(1,1,1, 1, 1, 1, clr, 0, 0));
buffer->Vertices.push_back(video::S3DVertex(0,1,1, -1, 1, 1, clr, 1, 0));
buffer->Vertices.push_back(video::S3DVertex(0,0,1, -1,-1, 1, clr, 1, 1));
buffer->Vertices.push_back(video::S3DVertex(0,1,1, -1, 1, 1, clr, 0, 1));
buffer->Vertices.push_back(video::S3DVertex(0,1,0, -1, 1,-1, clr, 1, 1));
buffer->Vertices.push_back(video::S3DVertex(1,0,1, 1,-1, 1, clr, 1, 0));
buffer->Vertices.push_back(video::S3DVertex(1,0,0, 1,-1,-1, clr, 0, 0));
// Recalculate bounding box
buffer->BoundingBox.reset(0,0,0);
for (u32 i=0; i<12; ++i)
{
buffer->Vertices[i].Pos -= core::vector3df(0.5f, 0.5f, 0.5f);
buffer->Vertices[i].Pos *= size;
buffer->BoundingBox.addInternalPoint(buffer->Vertices[i].Pos);
}
SMesh* mesh = new SMesh;
mesh->addMeshBuffer(buffer);
buffer->drop();
mesh->recalculateBoundingBox();
return mesh;
}
// creates a hill plane
IMesh* CGeometryCreator::createHillPlaneMesh(
const core::dimension2d<f32>& tileSize,
const core::dimension2d<u32>& tc, video::SMaterial* material,
f32 hillHeight, const core::dimension2d<f32>& ch,
const core::dimension2d<f32>& textureRepeatCount) const
{
core::dimension2d<u32> tileCount = tc;
core::dimension2d<f32> countHills = ch;
if (countHills.Width < 0.01f)
countHills.Width = 1.f;
if (countHills.Height < 0.01f)
countHills.Height = 1.f;
// center
const core::position2d<f32> center((tileSize.Width * tileCount.Width) * 0.5f, (tileSize.Height * tileCount.Height) * 0.5f);
// texture coord step
const core::dimension2d<f32> tx(
textureRepeatCount.Width / tileCount.Width,
textureRepeatCount.Height / tileCount.Height);
// add one more point in each direction for proper tile count
++tileCount.Height;
++tileCount.Width;
SMeshBuffer* buffer = new SMeshBuffer();
video::S3DVertex vtx;
vtx.Color.set(255,255,255,255);
// create vertices from left-front to right-back
u32 x;
f32 sx=0.f, tsx=0.f;
for (x=0; x<tileCount.Width; ++x)
{
f32 sy=0.f, tsy=0.f;
for (u32 y=0; y<tileCount.Height; ++y)
{
vtx.Pos.set(sx - center.X, 0, sy - center.Y);
vtx.TCoords.set(tsx, 1.0f - tsy);
if (core::isnotzero(hillHeight))
vtx.Pos.Y = sinf(vtx.Pos.X * countHills.Width * core::PI / center.X) *
cosf(vtx.Pos.Z * countHills.Height * core::PI / center.Y) *
hillHeight;
buffer->Vertices.push_back(vtx);
sy += tileSize.Height;
tsy += tx.Height;
}
sx += tileSize.Width;
tsx += tx.Width;
}
// create indices
for (x=0; x<tileCount.Width-1; ++x)
{
for (u32 y=0; y<tileCount.Height-1; ++y)
{
const s32 current = x*tileCount.Height + y;
buffer->Indices.push_back(current);
buffer->Indices.push_back(current + 1);
buffer->Indices.push_back(current + tileCount.Height);
buffer->Indices.push_back(current + 1);
buffer->Indices.push_back(current + 1 + tileCount.Height);
buffer->Indices.push_back(current + tileCount.Height);
}
}
// recalculate normals
for (u32 i=0; i<buffer->Indices.size(); i+=3)
{
const core::vector3df normal = core::plane3d<f32>(
buffer->Vertices[buffer->Indices[i+0]].Pos,
buffer->Vertices[buffer->Indices[i+1]].Pos,
buffer->Vertices[buffer->Indices[i+2]].Pos).Normal;
buffer->Vertices[buffer->Indices[i+0]].Normal = normal;
buffer->Vertices[buffer->Indices[i+1]].Normal = normal;
buffer->Vertices[buffer->Indices[i+2]].Normal = normal;
}
if (material)
buffer->Material = *material;
buffer->recalculateBoundingBox();
buffer->setHardwareMappingHint(EHM_STATIC);
SMesh* mesh = new SMesh();
mesh->addMeshBuffer(buffer);
mesh->recalculateBoundingBox();
buffer->drop();
return mesh;
}
IMesh* CGeometryCreator::createTerrainMesh(video::IImage* texture,
video::IImage* heightmap, const core::dimension2d<f32>& stretchSize,
f32 maxHeight, video::IVideoDriver* driver,
const core::dimension2d<u32>& maxVtxBlockSize,
bool debugBorders) const
{
if (!texture || !heightmap)
return 0;
// debug border
const s32 borderSkip = debugBorders ? 0 : 1;
video::S3DVertex vtx;
vtx.Color.set(255,255,255,255);
SMesh* mesh = new SMesh();
const u32 tm = os::Timer::getRealTime()/1000;
const core::dimension2d<u32> hMapSize= heightmap->getDimension();
const core::dimension2d<u32> tMapSize= texture->getDimension();
const core::position2d<f32> thRel(static_cast<f32>(tMapSize.Width) / hMapSize.Width, static_cast<f32>(tMapSize.Height) / hMapSize.Height);
maxHeight /= 255.0f; // height step per color value
core::position2d<u32> processed(0,0);
while (processed.Y<hMapSize.Height)
{
while(processed.X<hMapSize.Width)
{
core::dimension2d<u32> blockSize = maxVtxBlockSize;
if (processed.X + blockSize.Width > hMapSize.Width)
blockSize.Width = hMapSize.Width - processed.X;
if (processed.Y + blockSize.Height > hMapSize.Height)
blockSize.Height = hMapSize.Height - processed.Y;
SMeshBuffer* buffer = new SMeshBuffer();
buffer->setHardwareMappingHint(scene::EHM_STATIC);
buffer->Vertices.reallocate(blockSize.getArea());
// add vertices of vertex block
u32 y;
core::vector2df pos(0.f, processed.Y*stretchSize.Height);
const core::vector2df bs(1.f/blockSize.Width, 1.f/blockSize.Height);
core::vector2df tc(0.f, 0.5f*bs.Y);
for (y=0; y<blockSize.Height; ++y)
{
pos.X=processed.X*stretchSize.Width;
tc.X=0.5f*bs.X;
for (u32 x=0; x<blockSize.Width; ++x)
{
const f32 height = heightmap->getPixel(x+processed.X, y+processed.Y).getAverage() * maxHeight;
vtx.Pos.set(pos.X, height, pos.Y);
vtx.TCoords.set(tc);
buffer->Vertices.push_back(vtx);
pos.X += stretchSize.Width;
tc.X += bs.X;
}
pos.Y += stretchSize.Height;
tc.Y += bs.Y;
}
buffer->Indices.reallocate((blockSize.Height-1)*(blockSize.Width-1)*6);
// add indices of vertex block
s32 c1 = 0;
for (y=0; y<blockSize.Height-1; ++y)
{
for (u32 x=0; x<blockSize.Width-1; ++x)
{
const s32 c = c1 + x;
buffer->Indices.push_back(c);
buffer->Indices.push_back(c + blockSize.Width);
buffer->Indices.push_back(c + 1);
buffer->Indices.push_back(c + 1);
buffer->Indices.push_back(c + blockSize.Width);
buffer->Indices.push_back(c + 1 + blockSize.Width);
}
c1 += blockSize.Width;
}
// recalculate normals
for (u32 i=0; i<buffer->Indices.size(); i+=3)
{
const core::vector3df normal = core::plane3d<f32>(
buffer->Vertices[buffer->Indices[i+0]].Pos,
buffer->Vertices[buffer->Indices[i+1]].Pos,
buffer->Vertices[buffer->Indices[i+2]].Pos).Normal;
buffer->Vertices[buffer->Indices[i+0]].Normal = normal;
buffer->Vertices[buffer->Indices[i+1]].Normal = normal;
buffer->Vertices[buffer->Indices[i+2]].Normal = normal;
}
if (buffer->Vertices.size())
{
c8 textureName[64];
// create texture for this block
video::IImage* img = new video::CImage(texture->getColorFormat(), texture->getDimension());
texture->copyTo(img, core::position2di(0,0), core::recti(
core::position2d<s32>(core::floor32(processed.X*thRel.X), core::floor32(processed.Y*thRel.Y)),
core::dimension2d<u32>(core::floor32(blockSize.Width*thRel.X), core::floor32(blockSize.Height*thRel.Y))), 0);
sprintf(textureName, "terrain%u_%u", tm, mesh->getMeshBufferCount());
buffer->Material.setTexture(0, driver->addTexture(textureName, img));
if (buffer->Material.getTexture(0))
{
c8 tmp[255];
sprintf(tmp, "Generated terrain texture (%dx%d): %s",
buffer->Material.getTexture(0)->getSize().Width,
buffer->Material.getTexture(0)->getSize().Height,
textureName);
os::Printer::log(tmp);
}
else
os::Printer::log("Could not create terrain texture.", textureName, ELL_ERROR);
img->drop();
}
buffer->recalculateBoundingBox();
mesh->addMeshBuffer(buffer);
buffer->drop();
// keep on processing
processed.X += maxVtxBlockSize.Width - borderSkip;
}
// keep on processing
processed.X = 0;
processed.Y += maxVtxBlockSize.Height - borderSkip;
}
mesh->recalculateBoundingBox();
return mesh;
}
/*
a cylinder, a cone and a cross
point up on (0,1.f, 0.f )
*/
IMesh* CGeometryCreator::createArrowMesh(const u32 tesselationCylinder,
const u32 tesselationCone,
const f32 height,
const f32 cylinderHeight,
const f32 width0,
const f32 width1,
const video::SColor vtxColor0,
const video::SColor vtxColor1) const
{
SMesh* mesh = (SMesh*)createCylinderMesh(width0, cylinderHeight, tesselationCylinder, vtxColor0, false);
IMesh* mesh2 = createConeMesh(width1, height-cylinderHeight, tesselationCone, vtxColor1, vtxColor0);
for (u32 i=0; i<mesh2->getMeshBufferCount(); ++i)
{
scene::IMeshBuffer* buffer = mesh2->getMeshBuffer(i);
for (u32 j=0; j<buffer->getVertexCount(); ++j)
buffer->getPosition(j).Y += cylinderHeight;
buffer->setDirty(EBT_VERTEX);
+ buffer->recalculateBoundingBox();
mesh->addMeshBuffer(buffer);
}
mesh2->drop();
mesh->setHardwareMappingHint(EHM_STATIC);
+ mesh->recalculateBoundingBox();
return mesh;
}
/* A sphere with proper normals and texture coords */
IMesh* CGeometryCreator::createSphereMesh(f32 radius, u32 polyCountX, u32 polyCountY) const
{
// thanks to Alfaz93 who made his code available for Irrlicht on which
// this one is based!
// we are creating the sphere mesh here.
if (polyCountX < 2)
polyCountX = 2;
if (polyCountY < 2)
polyCountY = 2;
while (polyCountX * polyCountY > 32767) // prevent u16 overflow
{
polyCountX /= 2;
polyCountY /= 2;
}
const u32 polyCountXPitch = polyCountX+1; // get to same vertex on next level
SMeshBuffer* buffer = new SMeshBuffer();
buffer->Indices.reallocate((polyCountX * polyCountY) * 6);
const video::SColor clr(100, 255,255,255);
u32 level = 0;
for (u32 p1 = 0; p1 < polyCountY-1; ++p1)
{
//main quads, top to bottom
for (u32 p2 = 0; p2 < polyCountX - 1; ++p2)
{
const u32 curr = level + p2;
buffer->Indices.push_back(curr + polyCountXPitch);
buffer->Indices.push_back(curr);
buffer->Indices.push_back(curr + 1);
buffer->Indices.push_back(curr + polyCountXPitch);
buffer->Indices.push_back(curr+1);
buffer->Indices.push_back(curr + 1 + polyCountXPitch);
}
// the connectors from front to end
buffer->Indices.push_back(level + polyCountX - 1 + polyCountXPitch);
buffer->Indices.push_back(level + polyCountX - 1);
buffer->Indices.push_back(level + polyCountX);
buffer->Indices.push_back(level + polyCountX - 1 + polyCountXPitch);
buffer->Indices.push_back(level + polyCountX);
buffer->Indices.push_back(level + polyCountX + polyCountXPitch);
level += polyCountXPitch;
}
const u32 polyCountSq = polyCountXPitch * polyCountY; // top point
const u32 polyCountSq1 = polyCountSq + 1; // bottom point
const u32 polyCountSqM1 = (polyCountY - 1) * polyCountXPitch; // last row's first vertex
for (u32 p2 = 0; p2 < polyCountX - 1; ++p2)
{
// create triangles which are at the top of the sphere
buffer->Indices.push_back(polyCountSq);
buffer->Indices.push_back(p2 + 1);
buffer->Indices.push_back(p2);
// create triangles which are at the bottom of the sphere
buffer->Indices.push_back(polyCountSqM1 + p2);
buffer->Indices.push_back(polyCountSqM1 + p2 + 1);
buffer->Indices.push_back(polyCountSq1);
}
// create final triangle which is at the top of the sphere
buffer->Indices.push_back(polyCountSq);
buffer->Indices.push_back(polyCountX);
buffer->Indices.push_back(polyCountX-1);
// create final triangle which is at the bottom of the sphere
buffer->Indices.push_back(polyCountSqM1 + polyCountX - 1);
buffer->Indices.push_back(polyCountSqM1);
buffer->Indices.push_back(polyCountSq1);
// calculate the angle which separates all points in a circle
const f64 AngleX = 2 * core::PI / polyCountX;
const f64 AngleY = core::PI / polyCountY;
u32 i=0;
f64 axz;
// we don't start at 0.
f64 ay = 0;//AngleY / 2;
buffer->Vertices.set_used((polyCountXPitch * polyCountY) + 2);
for (u32 y = 0; y < polyCountY; ++y)
{
ay += AngleY;
const f64 sinay = sin(ay);
axz = 0;
// calculate the necessary vertices without the doubled one
for (u32 xz = 0;xz < polyCountX; ++xz)
{
// calculate points position
const core::vector3df pos(static_cast<f32>(radius * cos(axz) * sinay),
static_cast<f32>(radius * cos(ay)),
static_cast<f32>(radius * sin(axz) * sinay));
// for spheres the normal is the position
core::vector3df normal(pos);
normal.normalize();
// calculate texture coordinates via sphere mapping
// tu is the same on each level, so only calculate once
f32 tu = 0.5f;
if (y==0)
{
if (normal.Y != -1.0f && normal.Y != 1.0f)
tu = static_cast<f32>(acos(core::clamp(normal.X/sinay, -1.0, 1.0)) * 0.5 *core::RECIPROCAL_PI64);
if (normal.Z < 0.0f)
tu=1-tu;
}
else
tu = buffer->Vertices[i-polyCountXPitch].TCoords.X;
buffer->Vertices[i] = video::S3DVertex(pos.X, pos.Y, pos.Z,
normal.X, normal.Y, normal.Z,
clr, tu,
static_cast<f32>(ay*core::RECIPROCAL_PI64));
++i;
axz += AngleX;
}
// This is the doubled vertex on the initial position
buffer->Vertices[i] = video::S3DVertex(buffer->Vertices[i-polyCountX]);
buffer->Vertices[i].TCoords.X=1.0f;
++i;
}
// the vertex at the top of the sphere
buffer->Vertices[i] = video::S3DVertex(0.0f,radius,0.0f, 0.0f,1.0f,0.0f, clr, 0.5f, 0.0f);
// the vertex at the bottom of the sphere
++i;
buffer->Vertices[i] = video::S3DVertex(0.0f,-radius,0.0f, 0.0f,-1.0f,0.0f, clr, 0.5f, 1.0f);
// recalculate bounding box
buffer->BoundingBox.reset(buffer->Vertices[i].Pos);
buffer->BoundingBox.addInternalPoint(buffer->Vertices[i-1].Pos);
buffer->BoundingBox.addInternalPoint(radius,0.0f,0.0f);
buffer->BoundingBox.addInternalPoint(-radius,0.0f,0.0f);
buffer->BoundingBox.addInternalPoint(0.0f,0.0f,radius);
buffer->BoundingBox.addInternalPoint(0.0f,0.0f,-radius);
SMesh* mesh = new SMesh();
mesh->addMeshBuffer(buffer);
buffer->drop();
mesh->setHardwareMappingHint(EHM_STATIC);
mesh->recalculateBoundingBox();
return mesh;
}
/* A cylinder with proper normals and texture coords */
IMesh* CGeometryCreator::createCylinderMesh(f32 radius, f32 length,
u32 tesselation, const video::SColor& color,
bool closeTop, f32 oblique) const
{
SMeshBuffer* buffer = new SMeshBuffer();
const f32 recTesselation = core::reciprocal((f32)tesselation);
const f32 recTesselationHalf = recTesselation * 0.5f;
const f32 angleStep = (core::PI * 2.f ) * recTesselation;
const f32 angleStepHalf = angleStep*0.5f;
u32 i;
video::S3DVertex v;
v.Color = color;
buffer->Vertices.reallocate(tesselation*4+4+(closeTop?2:1));
buffer->Indices.reallocate((tesselation*2+1)*(closeTop?12:9));
f32 tcx = 0.f;
for ( i = 0; i <= tesselation; ++i )
{
const f32 angle = angleStep * i;
v.Pos.X = radius * cosf(angle);
v.Pos.Y = 0.f;
v.Pos.Z = radius * sinf(angle);
v.Normal = v.Pos;
v.Normal.normalize();
v.TCoords.X=tcx;
v.TCoords.Y=0.f;
buffer->Vertices.push_back(v);
v.Pos.X += oblique;
v.Pos.Y = length;
v.Normal = v.Pos;
v.Normal.normalize();
v.TCoords.Y=1.f;
buffer->Vertices.push_back(v);
v.Pos.X = radius * cosf(angle + angleStepHalf);
v.Pos.Y = 0.f;
v.Pos.Z = radius * sinf(angle + angleStepHalf);
v.Normal = v.Pos;
v.Normal.normalize();
v.TCoords.X=tcx+recTesselationHalf;
v.TCoords.Y=0.f;
buffer->Vertices.push_back(v);
v.Pos.X += oblique;
v.Pos.Y = length;
v.Normal = v.Pos;
v.Normal.normalize();
v.TCoords.Y=1.f;
buffer->Vertices.push_back(v);
tcx += recTesselation;
}
// indices for the main hull part
const u32 nonWrappedSize = tesselation* 4;
for (i=0; i != nonWrappedSize; i += 2)
{
buffer->Indices.push_back(i + 2);
buffer->Indices.push_back(i + 0);
buffer->Indices.push_back(i + 1);
buffer->Indices.push_back(i + 2);
buffer->Indices.push_back(i + 1);
buffer->Indices.push_back(i + 3);
}
// two closing quads between end and start
buffer->Indices.push_back(0);
buffer->Indices.push_back(i + 0);
buffer->Indices.push_back(i + 1);
buffer->Indices.push_back(0);
buffer->Indices.push_back(i + 1);
buffer->Indices.push_back(1);
// close down
v.Pos.X = 0.f;
v.Pos.Y = 0.f;
v.Pos.Z = 0.f;
v.Normal.X = 0.f;
v.Normal.Y = -1.f;
v.Normal.Z = 0.f;
v.TCoords.X = 1.f;
v.TCoords.Y = 1.f;
buffer->Vertices.push_back(v);
u32 index = buffer->Vertices.size() - 1;
for ( i = 0; i != nonWrappedSize; i += 2 )
{
buffer->Indices.push_back(index);
buffer->Indices.push_back(i + 0);
buffer->Indices.push_back(i + 2);
}
buffer->Indices.push_back(index);
buffer->Indices.push_back(i + 0);
buffer->Indices.push_back(0);
if (closeTop)
{
// close top
v.Pos.X = oblique;
v.Pos.Y = length;
v.Pos.Z = 0.f;
v.Normal.X = 0.f;
v.Normal.Y = 1.f;
v.Normal.Z = 0.f;
v.TCoords.X = 0.f;
v.TCoords.Y = 0.f;
buffer->Vertices.push_back(v);
index = buffer->Vertices.size() - 1;
for ( i = 0; i != nonWrappedSize; i += 2 )
{
buffer->Indices.push_back(i + 1);
buffer->Indices.push_back(index);
buffer->Indices.push_back(i + 3);
}
buffer->Indices.push_back(i + 1);
buffer->Indices.push_back(index);
buffer->Indices.push_back(1);
}
buffer->recalculateBoundingBox();
SMesh* mesh = new SMesh();
mesh->addMeshBuffer(buffer);
mesh->setHardwareMappingHint(EHM_STATIC);
mesh->recalculateBoundingBox();
buffer->drop();
return mesh;
}
/* A cone with proper normals and texture coords */
IMesh* CGeometryCreator::createConeMesh(f32 radius, f32 length, u32 tesselation,
const video::SColor& colorTop,
const video::SColor& colorBottom,
f32 oblique) const
{
SMeshBuffer* buffer = new SMeshBuffer();
const f32 angleStep = (core::PI * 2.f ) / tesselation;
const f32 angleStepHalf = angleStep*0.5f;
video::S3DVertex v;
u32 i;
v.Color = colorTop;
for ( i = 0; i != tesselation; ++i )
{
f32 angle = angleStep * f32(i);
v.Pos.X = radius * cosf(angle);
v.Pos.Y = 0.f;
v.Pos.Z = radius * sinf(angle);
v.Normal = v.Pos;
v.Normal.normalize();
buffer->Vertices.push_back(v);
angle += angleStepHalf;
v.Pos.X = radius * cosf(angle);
v.Pos.Y = 0.f;
v.Pos.Z = radius * sinf(angle);
v.Normal = v.Pos;
v.Normal.normalize();
buffer->Vertices.push_back(v);
}
const u32 nonWrappedSize = buffer->Vertices.size() - 1;
// close top
v.Pos.X = oblique;
v.Pos.Y = length;
v.Pos.Z = 0.f;
v.Normal.X = 0.f;
v.Normal.Y = 1.f;
v.Normal.Z = 0.f;
buffer->Vertices.push_back(v);
u32 index = buffer->Vertices.size() - 1;
for ( i = 0; i != nonWrappedSize; i += 1 )
{
buffer->Indices.push_back(i + 0);
buffer->Indices.push_back(index);
buffer->Indices.push_back(i + 1);
}
buffer->Indices.push_back(i + 0);
buffer->Indices.push_back(index);
buffer->Indices.push_back(0);
// close down
v.Color = colorBottom;
v.Pos.X = 0.f;
v.Pos.Y = 0.f;
v.Pos.Z = 0.f;
v.Normal.X = 0.f;
v.Normal.Y = -1.f;
v.Normal.Z = 0.f;
buffer->Vertices.push_back(v);
index = buffer->Vertices.size() - 1;
for ( i = 0; i != nonWrappedSize; i += 1 )
{
buffer->Indices.push_back(index);
buffer->Indices.push_back(i + 0);
buffer->Indices.push_back(i + 1);
}
buffer->Indices.push_back(index);
buffer->Indices.push_back(i + 0);
buffer->Indices.push_back(0);
buffer->recalculateBoundingBox();
SMesh* mesh = new SMesh();
mesh->addMeshBuffer(buffer);
buffer->drop();
mesh->setHardwareMappingHint(EHM_STATIC);
mesh->recalculateBoundingBox();
return mesh;
}
void CGeometryCreator::addToBuffer(const video::S3DVertex& v, SMeshBuffer* Buffer) const
{
const s32 tnidx = Buffer->Vertices.linear_reverse_search(v);
const bool alreadyIn = (tnidx != -1);
u16 nidx = (u16)tnidx;
if (!alreadyIn)
{
nidx = (u16)Buffer->Vertices.size();
Buffer->Indices.push_back(nidx);
Buffer->Vertices.push_back(v);
}
else
Buffer->Indices.push_back(nidx);
}
IMesh* CGeometryCreator::createVolumeLightMesh(
const u32 subdivideU, const u32 subdivideV,
const video::SColor footColor, const video::SColor tailColor,
const f32 lpDistance, const core::vector3df& lightDim) const
{
SMeshBuffer* Buffer = new SMeshBuffer();
Buffer->setHardwareMappingHint(EHM_STATIC);
const core::vector3df lightPoint(0, -(lpDistance*lightDim.Y), 0);
const f32 ax = lightDim.X * 0.5f; // X Axis
const f32 az = lightDim.Z * 0.5f; // Z Axis
Buffer->Vertices.clear();
Buffer->Vertices.reallocate(6+12*(subdivideU+subdivideV));
Buffer->Indices.clear();
Buffer->Indices.reallocate(6+12*(subdivideU+subdivideV));
//draw the bottom foot.. the glowing region
addToBuffer(video::S3DVertex(-ax, 0, az, 0,0,0, footColor, 0, 1),Buffer);
addToBuffer(video::S3DVertex( ax, 0, az, 0,0,0, footColor, 1, 1),Buffer);
addToBuffer(video::S3DVertex( ax, 0,-az, 0,0,0, footColor, 1, 0),Buffer);
addToBuffer(video::S3DVertex( ax, 0,-az, 0,0,0, footColor, 1, 0),Buffer);
addToBuffer(video::S3DVertex(-ax, 0,-az, 0,0,0, footColor, 0, 0),Buffer);
addToBuffer(video::S3DVertex(-ax, 0, az, 0,0,0, footColor, 0, 1),Buffer);
f32 tu = 0.f;
const f32 tuStep = 1.f/subdivideU;
f32 bx = -ax;
const f32 bxStep = lightDim.X * tuStep;
// Slices in X/U space
for (u32 i = 0; i <= subdivideU; ++i)
{
// These are the two endpoints for a slice at the foot
core::vector3df end1(bx, 0.0f, -az);
core::vector3df end2(bx, 0.0f, az);
end1 -= lightPoint; // get a vector from point to lightsource
end1.normalize(); // normalize vector
end1 *= lightDim.Y; // multiply it out by shootlength
end1.X += bx; // Add the original point location to the vector
end1.Z -= az;
// Do it again for the other point.
end2 -= lightPoint;
end2.normalize();
end2 *= lightDim.Y;
end2.X += bx;
end2.Z += az;
addToBuffer(video::S3DVertex(bx , 0, az, 0,0,0, footColor, tu, 1),Buffer);
addToBuffer(video::S3DVertex(bx , 0, -az, 0,0,0, footColor, tu, 0),Buffer);
addToBuffer(video::S3DVertex(end2.X , end2.Y, end2.Z, 0,0,0, tailColor, tu, 1),Buffer);
addToBuffer(video::S3DVertex(bx , 0, -az, 0,0,0, footColor, tu, 0),Buffer);
addToBuffer(video::S3DVertex(end1.X , end1.Y, end1.Z, 0,0,0, tailColor, tu, 0),Buffer);
addToBuffer(video::S3DVertex(end2.X , end2.Y, end2.Z, 0,0,0, tailColor, tu, 1),Buffer);
//back side
addToBuffer(video::S3DVertex(-end2.X , end2.Y, -end2.Z, 0,0,0, tailColor, tu, 1),Buffer);
addToBuffer(video::S3DVertex(-bx , 0, -az, 0,0,0, footColor, tu, 1),Buffer);
addToBuffer(video::S3DVertex(-bx , 0, az, 0,0,0, footColor, tu, 0),Buffer);
addToBuffer(video::S3DVertex(-bx , 0, az, 0,0,0, footColor, tu, 0),Buffer);
addToBuffer(video::S3DVertex(-end1.X , end1.Y, -end1.Z, 0,0,0, tailColor, tu, 0),Buffer);
addToBuffer(video::S3DVertex(-end2.X , end2.Y, -end2.Z, 0,0,0, tailColor, tu, 1),Buffer);
tu += tuStep;
bx += bxStep;
}
f32 tv = 0.f;
const f32 tvStep = 1.f/subdivideV;
f32 bz = -az;
const f32 bzStep = lightDim.Z * tvStep;
// Slices in Z/V space
for(u32 i = 0; i <= subdivideV; ++i)
{
// These are the two endpoints for a slice at the foot
core::vector3df end1(-ax, 0.0f, bz);
core::vector3df end2(ax, 0.0f, bz);
end1 -= lightPoint; // get a vector from point to lightsource
end1.normalize(); // normalize vector
end1 *= lightDim.Y; // multiply it out by shootlength
end1.X -= ax; // Add the original point location to the vector
end1.Z += bz;
// Do it again for the other point.
end2 -= lightPoint;
end2.normalize();
end2 *= lightDim.Y;
end2.X += ax;
end2.Z += bz;
|
paupawsan/Irrlicht
|
c83ebcc5bdd27870ba968158dee3934049339fb6
|
Remove destructors.
|
diff --git a/source/Irrlicht/CMountPointReader.cpp b/source/Irrlicht/CMountPointReader.cpp
index 07df00c..e644ec2 100644
--- a/source/Irrlicht/CMountPointReader.cpp
+++ b/source/Irrlicht/CMountPointReader.cpp
@@ -1,174 +1,168 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CMountPointReader.h"
#ifdef __IRR_COMPILE_WITH_MOUNT_ARCHIVE_LOADER_
#include "CReadFile.h"
#include "os.h"
namespace irr
{
namespace io
{
//! Constructor
CArchiveLoaderMount::CArchiveLoaderMount( io::IFileSystem* fs)
: FileSystem(fs)
{
#ifdef _DEBUG
setDebugName("CArchiveLoaderMount");
#endif
}
-//! destructor
-CArchiveLoaderMount::~CArchiveLoaderMount()
-{
-}
-
-
//! returns true if the file maybe is able to be loaded by this class
bool CArchiveLoaderMount::isALoadableFileFormat(const io::path& filename) const
{
bool ret = false;
io::path fname(filename);
deletePathFromFilename(fname);
if (!fname.size())
{
ret = true;
}
return ret;
}
//! Check to see if the loader can create archives of this type.
bool CArchiveLoaderMount::isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) const
{
return fileType == EFAT_FOLDER;
}
//! Check if the file might be loaded by this class
bool CArchiveLoaderMount::isALoadableFileFormat(io::IReadFile* file) const
{
return false;
}
//! Creates an archive from the filename
IFileArchive* CArchiveLoaderMount::createArchive(const io::path& filename, bool ignoreCase, bool ignorePaths) const
{
IFileArchive *archive = 0;
EFileSystemType current = FileSystem->setFileListSystem(FILESYSTEM_NATIVE);
io::path save = FileSystem->getWorkingDirectory();
io::path fullPath = FileSystem->getAbsolutePath(filename);
FileSystem->flattenFilename(fullPath);
if ( FileSystem->changeWorkingDirectoryTo ( fullPath ) )
{
archive = new CMountPointReader(FileSystem, fullPath, ignoreCase, ignorePaths);
}
FileSystem->changeWorkingDirectoryTo(save);
FileSystem->setFileListSystem(current);
return archive;
}
//! creates/loads an archive from the file.
//! \return Pointer to the created archive. Returns 0 if loading failed.
IFileArchive* CArchiveLoaderMount::createArchive(io::IReadFile* file, bool ignoreCase, bool ignorePaths) const
{
return 0;
}
//! compatible Folder Architecture
CMountPointReader::CMountPointReader(IFileSystem * parent, const io::path& basename, bool ignoreCase, bool ignorePaths)
: CFileList(basename, ignoreCase, ignorePaths), Parent(parent)
{
//! ensure CFileList path ends in a slash
if (Path.lastChar() != '/' )
Path.append('/');
const io::path work = Parent->getWorkingDirectory();
Parent->changeWorkingDirectoryTo(basename);
buildDirectory();
Parent->changeWorkingDirectoryTo(work);
sort();
}
//! returns the list of files
const IFileList* CMountPointReader::getFileList() const
{
return this;
}
void CMountPointReader::buildDirectory()
{
IFileList * list = Parent->createFileList();
if (!list)
return;
const u32 size = list->getFileCount();
for (u32 i=0; i < size; ++i)
{
io::path full = list->getFullFileName(i);
full = full.subString(Path.size(), full.size() - Path.size());
if (!list->isDirectory(i))
{
addItem(full, list->getFileSize(i), false, RealFileNames.size());
RealFileNames.push_back(list->getFullFileName(i));
}
else
{
const io::path rel = list->getFileName(i);
io::path pwd = Parent->getWorkingDirectory();
if (pwd.lastChar() != '/')
pwd.append('/');
pwd.append(rel);
if ( rel != "." && rel != ".." )
{
addItem(full, 0, true, 0);
Parent->changeWorkingDirectoryTo(pwd);
buildDirectory();
Parent->changeWorkingDirectoryTo("..");
}
}
}
list->drop();
}
//! opens a file by index
IReadFile* CMountPointReader::createAndOpenFile(u32 index)
{
if (index >= Files.size())
return 0;
return createReadFile(RealFileNames[Files[index].ID]);
}
//! opens a file by file name
IReadFile* CMountPointReader::createAndOpenFile(const io::path& filename)
{
s32 index = findFile(filename, false);
if (index != -1)
return createAndOpenFile(index);
else
return 0;
}
} // io
} // irr
#endif // __IRR_COMPILE_WITH_MOUNT_ARCHIVE_LOADER_
diff --git a/source/Irrlicht/CMountPointReader.h b/source/Irrlicht/CMountPointReader.h
index 299dc0d..044b233 100644
--- a/source/Irrlicht/CMountPointReader.h
+++ b/source/Irrlicht/CMountPointReader.h
@@ -1,95 +1,89 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_MOUNT_READER_H_INCLUDED__
#define __C_MOUNT_READER_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef __IRR_COMPILE_WITH_MOUNT_ARCHIVE_LOADER_
#include "IFileSystem.h"
#include "CFileList.h"
namespace irr
{
namespace io
{
//! Archiveloader capable of loading MountPoint Archives
class CArchiveLoaderMount : public IArchiveLoader
{
public:
//! Constructor
CArchiveLoaderMount(io::IFileSystem* fs);
- //! destructor
- virtual ~CArchiveLoaderMount();
-
//! returns true if the file maybe is able to be loaded by this class
//! based on the file extension (e.g. ".zip")
virtual bool isALoadableFileFormat(const io::path& filename) const;
//! Check if the file might be loaded by this class
/** Check might look into the file.
\param file File handle to check.
\return True if file seems to be loadable. */
virtual bool isALoadableFileFormat(io::IReadFile* file) const;
//! Check to see if the loader can create archives of this type.
/** Check based on the archive type.
\param fileType The archive type to check.
\return True if the archile loader supports this type, false if not */
virtual bool isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) const;
//! Creates an archive from the filename
/** \param file File handle to check.
\return Pointer to newly created archive, or 0 upon error. */
virtual IFileArchive* createArchive(const io::path& filename, bool ignoreCase, bool ignorePaths) const;
//! creates/loads an archive from the file.
//! \return Pointer to the created archive. Returns 0 if loading failed.
virtual IFileArchive* createArchive(io::IReadFile* file, bool ignoreCase, bool ignorePaths) const;
private:
io::IFileSystem* FileSystem;
};
//! A File Archive which uses a mountpoint
class CMountPointReader : public virtual IFileArchive, virtual CFileList
{
public:
//! Constructor
CMountPointReader(IFileSystem *parent, const io::path& basename,
bool ignoreCase, bool ignorePaths);
- //! Destructor
- virtual ~CMountPointReader();
-
//! opens a file by index
virtual IReadFile* createAndOpenFile(u32 index);
//! opens a file by file name
virtual IReadFile* createAndOpenFile(const io::path& filename);
//! returns the list of files
virtual const IFileList* getFileList() const;
//! get the class Type
virtual E_FILE_ARCHIVE_TYPE getType() const { return EFAT_FOLDER; }
private:
core::array<io::path> RealFileNames;
IFileSystem *Parent;
void buildDirectory();
};
} // io
} // irr
#endif // __IRR_COMPILE_WITH_MOUNT_ARCHIVE_LOADER_
#endif // __C_MOUNT_READER_H_INCLUDED__
|
paupawsan/Irrlicht
|
7df5460acf4271d93d7d06ca0900228e43e4fe91
|
Init fix by Madkinder.
|
diff --git a/source/Irrlicht/CB3DMeshFileLoader.cpp b/source/Irrlicht/CB3DMeshFileLoader.cpp
index 6f64fec..842e28c 100644
--- a/source/Irrlicht/CB3DMeshFileLoader.cpp
+++ b/source/Irrlicht/CB3DMeshFileLoader.cpp
@@ -92,969 +92,969 @@ bool CB3DMeshFileLoader::load()
}
// Add main chunk...
B3dStack.push_back(SB3dChunk(header, B3DFile->getPos()-8));
// Get file version, but ignore it, as it's not important with b3d files...
s32 fileVersion;
B3DFile->read(&fileVersion, sizeof(fileVersion));
#ifdef __BIG_ENDIAN__
fileVersion = os::Byteswap::byteswap(fileVersion);
#endif
//------ Read main chunk ------
while ( (B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos() )
{
B3DFile->read(&header, sizeof(header));
#ifdef __BIG_ENDIAN__
header.size = os::Byteswap::byteswap(header.size);
#endif
B3dStack.push_back(SB3dChunk(header, B3DFile->getPos()-8));
if ( strncmp( B3dStack.getLast().name, "TEXS", 4 ) == 0 )
{
if (!readChunkTEXS())
return false;
}
else if ( strncmp( B3dStack.getLast().name, "BRUS", 4 ) == 0 )
{
if (!readChunkBRUS())
return false;
}
else if ( strncmp( B3dStack.getLast().name, "NODE", 4 ) == 0 )
{
if (!readChunkNODE((CSkinnedMesh::SJoint*)0) )
return false;
}
else
{
os::Printer::log("Unknown chunk found in mesh base - skipping");
B3DFile->seek(B3dStack.getLast().startposition + B3dStack.getLast().length);
B3dStack.erase(B3dStack.size()-1);
}
}
B3dStack.clear();
BaseVertices.clear();
AnimatedVertices_VertexID.clear();
AnimatedVertices_BufferID.clear();
Materials.clear();
Textures.clear();
return true;
}
bool CB3DMeshFileLoader::readChunkNODE(CSkinnedMesh::SJoint *inJoint)
{
CSkinnedMesh::SJoint *joint = AnimatedMesh->addJoint(inJoint);
readString(joint->Name);
#ifdef _B3D_READER_DEBUG
os::Printer::log("read ChunkNODE", joint->Name.c_str());
#endif
f32 position[3], scale[3], rotation[4];
readFloats(position, 3);
readFloats(scale, 3);
readFloats(rotation, 4);
joint->Animatedposition = core::vector3df(position[0],position[1],position[2]) ;
joint->Animatedscale = core::vector3df(scale[0],scale[1],scale[2]);
joint->Animatedrotation = core::quaternion(rotation[1], rotation[2], rotation[3], rotation[0]);
//Build LocalMatrix:
core::matrix4 positionMatrix;
positionMatrix.setTranslation( joint->Animatedposition );
core::matrix4 scaleMatrix;
scaleMatrix.setScale( joint->Animatedscale );
core::matrix4 rotationMatrix = joint->Animatedrotation.getMatrix();
joint->LocalMatrix = positionMatrix * rotationMatrix * scaleMatrix;
if (inJoint)
joint->GlobalMatrix = inJoint->GlobalMatrix * joint->LocalMatrix;
else
joint->GlobalMatrix = joint->LocalMatrix;
while(B3dStack.getLast().startposition + B3dStack.getLast().length > B3DFile->getPos()) // this chunk repeats
{
SB3dChunkHeader header;
B3DFile->read(&header, sizeof(header));
#ifdef __BIG_ENDIAN__
header.size = os::Byteswap::byteswap(header.size);
#endif
B3dStack.push_back(SB3dChunk(header, B3DFile->getPos()-8));
if ( strncmp( B3dStack.getLast().name, "NODE", 4 ) == 0 )
{
if (!readChunkNODE(joint))
return false;
}
else if ( strncmp( B3dStack.getLast().name, "MESH", 4 ) == 0 )
{
if (!readChunkMESH(joint))
return false;
}
else if ( strncmp( B3dStack.getLast().name, "BONE", 4 ) == 0 )
{
if (!readChunkBONE(joint))
return false;
}
else if ( strncmp( B3dStack.getLast().name, "KEYS", 4 ) == 0 )
{
if(!readChunkKEYS(joint))
return false;
}
else if ( strncmp( B3dStack.getLast().name, "ANIM", 4 ) == 0 )
{
if (!readChunkANIM())
return false;
}
else
{
os::Printer::log("Unknown chunk found in node chunk - skipping");
B3DFile->seek(B3dStack.getLast().startposition + B3dStack.getLast().length);
B3dStack.erase(B3dStack.size()-1);
}
}
B3dStack.erase(B3dStack.size()-1);
return true;
}
bool CB3DMeshFileLoader::readChunkMESH(CSkinnedMesh::SJoint *inJoint)
{
#ifdef _B3D_READER_DEBUG
os::Printer::log("read ChunkMESH");
#endif
const s32 vertices_Start=BaseVertices.size(); //B3Ds have Vertex ID's local within the mesh I don't want this
s32 brush_id;
B3DFile->read(&brush_id, sizeof(brush_id));
#ifdef __BIG_ENDIAN__
brush_id = os::Byteswap::byteswap(brush_id);
#endif
NormalsInFile=false;
HasVertexColors=false;
while((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) //this chunk repeats
{
SB3dChunkHeader header;
B3DFile->read(&header, sizeof(header));
#ifdef __BIG_ENDIAN__
header.size = os::Byteswap::byteswap(header.size);
#endif
B3dStack.push_back(SB3dChunk(header, B3DFile->getPos()-8));
if ( strncmp( B3dStack.getLast().name, "VRTS", 4 ) == 0 )
{
if (!readChunkVRTS(inJoint))
return false;
}
else if ( strncmp( B3dStack.getLast().name, "TRIS", 4 ) == 0 )
{
scene::SSkinMeshBuffer *meshBuffer = AnimatedMesh->addMeshBuffer();
if (brush_id!=-1)
{
loadTextures(Materials[brush_id]);
meshBuffer->Material=Materials[brush_id].Material;
}
if(readChunkTRIS(meshBuffer,AnimatedMesh->getMeshBuffers().size()-1, vertices_Start)==false)
return false;
if (!NormalsInFile)
{
s32 i;
for ( i=0; i<(s32)meshBuffer->Indices.size(); i+=3)
{
core::plane3df p(meshBuffer->getVertex(meshBuffer->Indices[i+0])->Pos,
meshBuffer->getVertex(meshBuffer->Indices[i+1])->Pos,
meshBuffer->getVertex(meshBuffer->Indices[i+2])->Pos);
meshBuffer->getVertex(meshBuffer->Indices[i+0])->Normal += p.Normal;
meshBuffer->getVertex(meshBuffer->Indices[i+1])->Normal += p.Normal;
meshBuffer->getVertex(meshBuffer->Indices[i+2])->Normal += p.Normal;
}
for ( i = 0; i<(s32)meshBuffer->getVertexCount(); ++i )
{
meshBuffer->getVertex(i)->Normal.normalize();
BaseVertices[vertices_Start+i].Normal=meshBuffer->getVertex(i)->Normal;
}
}
}
else
{
os::Printer::log("Unknown chunk found in mesh - skipping");
B3DFile->seek(B3dStack.getLast().startposition + B3dStack.getLast().length);
B3dStack.erase(B3dStack.size()-1);
}
}
B3dStack.erase(B3dStack.size()-1);
return true;
}
/*
VRTS:
int flags ;1=normal values present, 2=rgba values present
int tex_coord_sets ;texture coords per vertex (eg: 1 for simple U/V) max=8
but we only support 3
int tex_coord_set_size ;components per set (eg: 2 for simple U/V) max=4
{
float x,y,z ;always present
float nx,ny,nz ;vertex normal: present if (flags&1)
float red,green,blue,alpha ;vertex color: present if (flags&2)
float tex_coords[tex_coord_sets][tex_coord_set_size] ;tex coords
}
*/
bool CB3DMeshFileLoader::readChunkVRTS(CSkinnedMesh::SJoint *inJoint)
{
#ifdef _B3D_READER_DEBUG
os::Printer::log("read ChunkVRTS");
#endif
const s32 max_tex_coords = 3;
s32 flags, tex_coord_sets, tex_coord_set_size;
B3DFile->read(&flags, sizeof(flags));
B3DFile->read(&tex_coord_sets, sizeof(tex_coord_sets));
B3DFile->read(&tex_coord_set_size, sizeof(tex_coord_set_size));
#ifdef __BIG_ENDIAN__
flags = os::Byteswap::byteswap(flags);
tex_coord_sets = os::Byteswap::byteswap(tex_coord_sets);
tex_coord_set_size = os::Byteswap::byteswap(tex_coord_set_size);
#endif
if (tex_coord_sets >= max_tex_coords || tex_coord_set_size >= 4) // Something is wrong
{
os::Printer::log("tex_coord_sets or tex_coord_set_size too big", B3DFile->getFileName(), ELL_ERROR);
return false;
}
//------ Allocate Memory, for speed -----------//
s32 numberOfReads = 3;
if (flags & 1)
{
NormalsInFile = true;
numberOfReads += 3;
}
if (flags & 2)
{
numberOfReads += 4;
HasVertexColors=true;
}
numberOfReads += tex_coord_sets*tex_coord_set_size;
const s32 memoryNeeded = (B3dStack.getLast().length / sizeof(f32)) / numberOfReads;
BaseVertices.reallocate(memoryNeeded + BaseVertices.size() + 1);
AnimatedVertices_VertexID.reallocate(memoryNeeded + AnimatedVertices_VertexID.size() + 1);
//--------------------------------------------//
while( (B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) // this chunk repeats
{
f32 position[3];
f32 normal[3]={0.f, 0.f, 0.f};
f32 color[4]={1.0f, 1.0f, 1.0f, 1.0f};
f32 tex_coords[max_tex_coords][4];
readFloats(position, 3);
if (flags & 1)
readFloats(normal, 3);
if (flags & 2)
readFloats(color, 4);
for (s32 i=0; i<tex_coord_sets; ++i)
readFloats(tex_coords[i], tex_coord_set_size);
f32 tu=0.0f, tv=0.0f;
if (tex_coord_sets >= 1 && tex_coord_set_size >= 2)
{
tu=tex_coords[0][0];
tv=tex_coords[0][1];
}
f32 tu2=0.0f, tv2=0.0f;
if (tex_coord_sets>1 && tex_coord_set_size>1)
{
tu2=tex_coords[1][0];
tv2=tex_coords[1][1];
}
// Create Vertex...
video::S3DVertex2TCoords Vertex(position[0], position[1], position[2],
normal[0], normal[1], normal[2],
video::SColorf(color[0], color[1], color[2], color[3]).toSColor(),
tu, tv, tu2, tv2);
// Transform the Vertex position by nested node...
inJoint->GlobalMatrix.transformVect(Vertex.Pos);
inJoint->GlobalMatrix.rotateVect(Vertex.Normal);
//Add it...
BaseVertices.push_back(Vertex);
AnimatedVertices_VertexID.push_back(-1);
AnimatedVertices_BufferID.push_back(-1);
}
B3dStack.erase(B3dStack.size()-1);
return true;
}
bool CB3DMeshFileLoader::readChunkTRIS(scene::SSkinMeshBuffer *meshBuffer, u32 meshBufferID, s32 vertices_Start)
{
#ifdef _B3D_READER_DEBUG
os::Printer::log("read ChunkTRIS");
#endif
bool showVertexWarning=false;
s32 triangle_brush_id; // Note: Irrlicht can't have different brushes for each triangle (using a workaround)
B3DFile->read(&triangle_brush_id, sizeof(triangle_brush_id));
#ifdef __BIG_ENDIAN__
triangle_brush_id = os::Byteswap::byteswap(triangle_brush_id);
#endif
SB3dMaterial *B3dMaterial;
if (triangle_brush_id != -1)
{
loadTextures(Materials[triangle_brush_id]);
B3dMaterial = &Materials[triangle_brush_id];
meshBuffer->Material = B3dMaterial->Material;
}
else
B3dMaterial = 0;
const s32 memoryNeeded = B3dStack.getLast().length / sizeof(s32);
meshBuffer->Indices.reallocate(memoryNeeded + meshBuffer->Indices.size() + 1);
while((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) // this chunk repeats
{
s32 vertex_id[3];
B3DFile->read(vertex_id, 3*sizeof(s32));
#ifdef __BIG_ENDIAN__
vertex_id[0] = os::Byteswap::byteswap(vertex_id[0]);
vertex_id[1] = os::Byteswap::byteswap(vertex_id[1]);
vertex_id[2] = os::Byteswap::byteswap(vertex_id[2]);
#endif
//Make Ids global:
vertex_id[0] += vertices_Start;
vertex_id[1] += vertices_Start;
vertex_id[2] += vertices_Start;
for(s32 i=0; i<3; ++i)
{
if ((u32)vertex_id[i] >= AnimatedVertices_VertexID.size())
{
os::Printer::log("Illegal vertex index found", B3DFile->getFileName(), ELL_ERROR);
return false;
}
if (AnimatedVertices_VertexID[ vertex_id[i] ] != -1)
{
if ( AnimatedVertices_BufferID[ vertex_id[i] ] != (s32)meshBufferID ) //If this vertex is linked in a different meshbuffer
{
AnimatedVertices_VertexID[ vertex_id[i] ] = -1;
AnimatedVertices_BufferID[ vertex_id[i] ] = -1;
showVertexWarning=true;
}
}
if (AnimatedVertices_VertexID[ vertex_id[i] ] == -1) //If this vertex is not in the meshbuffer
{
//Check for lightmapping:
if (BaseVertices[ vertex_id[i] ].TCoords2 != core::vector2df(0.f,0.f))
meshBuffer->convertTo2TCoords(); //Will only affect the meshbuffer the first time this is called
//Add the vertex to the meshbuffer:
if (meshBuffer->VertexType == video::EVT_STANDARD)
meshBuffer->Vertices_Standard.push_back( BaseVertices[ vertex_id[i] ] );
else
meshBuffer->Vertices_2TCoords.push_back(BaseVertices[ vertex_id[i] ] );
//create vertex id to meshbuffer index link:
AnimatedVertices_VertexID[ vertex_id[i] ] = meshBuffer->getVertexCount()-1;
AnimatedVertices_BufferID[ vertex_id[i] ] = meshBufferID;
if (B3dMaterial)
{
// Apply Material/Color/etc...
video::S3DVertex *Vertex=meshBuffer->getVertex(meshBuffer->getVertexCount()-1);
if (!HasVertexColors)
Vertex->Color=B3dMaterial->Material.DiffuseColor;
else if (Vertex->Color.getAlpha() == 255)
Vertex->Color.setAlpha( (s32)(B3dMaterial->alpha * 255.0f) );
// Use texture's scale
if (B3dMaterial->Textures[0])
{
Vertex->TCoords.X *= B3dMaterial->Textures[0]->Xscale;
Vertex->TCoords.Y *= B3dMaterial->Textures[0]->Yscale;
}
/*
if (B3dMaterial->Textures[1])
{
Vertex->TCoords2.X *=B3dMaterial->Textures[1]->Xscale;
Vertex->TCoords2.Y *=B3dMaterial->Textures[1]->Yscale;
}
*/
}
}
}
meshBuffer->Indices.push_back( AnimatedVertices_VertexID[ vertex_id[0] ] );
meshBuffer->Indices.push_back( AnimatedVertices_VertexID[ vertex_id[1] ] );
meshBuffer->Indices.push_back( AnimatedVertices_VertexID[ vertex_id[2] ] );
}
B3dStack.erase(B3dStack.size()-1);
if (showVertexWarning)
os::Printer::log("B3dMeshLoader: Warning, different meshbuffers linking to the same vertex, this will cause problems with animated meshes");
return true;
}
bool CB3DMeshFileLoader::readChunkBONE(CSkinnedMesh::SJoint *inJoint)
{
#ifdef _B3D_READER_DEBUG
os::Printer::log("read ChunkBONE");
#endif
if (B3dStack.getLast().length > 8)
{
while((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) // this chunk repeats
{
u32 globalVertexID;
f32 strength;
B3DFile->read(&globalVertexID, sizeof(globalVertexID));
B3DFile->read(&strength, sizeof(strength));
#ifdef __BIG_ENDIAN__
globalVertexID = os::Byteswap::byteswap(globalVertexID);
strength = os::Byteswap::byteswap(strength);
#endif
if (AnimatedVertices_VertexID[globalVertexID]==-1)
{
os::Printer::log("B3dMeshLoader: Weight has bad vertex id (no link to meshbuffer index found)");
}
else if (strength >0)
{
CSkinnedMesh::SWeight *weight=AnimatedMesh->addWeight(inJoint);
weight->strength=strength;
//Find the meshbuffer and Vertex index from the Global Vertex ID:
weight->vertex_id = AnimatedVertices_VertexID[globalVertexID];
weight->buffer_id = AnimatedVertices_BufferID[globalVertexID];
}
}
}
B3dStack.erase(B3dStack.size()-1);
return true;
}
bool CB3DMeshFileLoader::readChunkKEYS(CSkinnedMesh::SJoint *inJoint)
{
#ifdef _B3D_READER_DEBUG
// os::Printer::log("read ChunkKEYS");
#endif
s32 flags;
B3DFile->read(&flags, sizeof(flags));
#ifdef __BIG_ENDIAN__
flags = os::Byteswap::byteswap(flags);
#endif
CSkinnedMesh::SPositionKey *oldPosKey=0;
core::vector3df oldPos[2];
CSkinnedMesh::SScaleKey *oldScaleKey=0;
core::vector3df oldScale[2];
CSkinnedMesh::SRotationKey *oldRotKey=0;
core::quaternion oldRot[2];
- bool isFirst[3]={true};
+ bool isFirst[3]={true,true,true};
while((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) //this chunk repeats
{
s32 frame;
B3DFile->read(&frame, sizeof(frame));
#ifdef __BIG_ENDIAN__
frame = os::Byteswap::byteswap(frame);
#endif
// Add key frames, frames in Irrlicht are zero-based
f32 data[4];
if (flags & 1)
{
readFloats(data, 3);
if ((oldPosKey!=0) && (oldPos[0]==oldPos[1]))
{
const core::vector3df pos(data[0], data[1], data[2]);
if (oldPos[1]==pos)
oldPosKey->frame = (f32)frame-1;
else
{
oldPos[0]=oldPos[1];
oldPosKey=AnimatedMesh->addPositionKey(inJoint);
oldPosKey->frame = (f32)frame-1;
oldPos[1].set(oldPosKey->position.set(pos));
}
}
else if (oldPosKey==0 && isFirst[0])
{
oldPosKey=AnimatedMesh->addPositionKey(inJoint);
oldPosKey->frame = (f32)frame-1;
oldPos[0].set(oldPosKey->position.set(data[0], data[1], data[2]));
oldPosKey=0;
isFirst[0]=false;
}
else
{
if (oldPosKey!=0)
oldPos[0]=oldPos[1];
oldPosKey=AnimatedMesh->addPositionKey(inJoint);
oldPosKey->frame = (f32)frame-1;
oldPos[1].set(oldPosKey->position.set(data[0], data[1], data[2]));
}
}
if (flags & 2)
{
readFloats(data, 3);
if ((oldScaleKey!=0) && (oldScale[0]==oldScale[1]))
{
const core::vector3df scale(data[0], data[1], data[2]);
if (oldScale[1]==scale)
oldScaleKey->frame = (f32)frame-1;
else
{
oldScale[0]=oldScale[1];
oldScaleKey=AnimatedMesh->addScaleKey(inJoint);
oldScaleKey->frame = (f32)frame-1;
oldScale[1].set(oldScaleKey->scale.set(scale));
}
}
else if (oldScaleKey==0 && isFirst[1])
{
oldScaleKey=AnimatedMesh->addScaleKey(inJoint);
oldScaleKey->frame = (f32)frame-1;
oldScale[0].set(oldScaleKey->scale.set(data[0], data[1], data[2]));
oldScaleKey=0;
isFirst[1]=false;
}
else
{
if (oldScaleKey!=0)
oldScale[0]=oldScale[1];
oldScaleKey=AnimatedMesh->addScaleKey(inJoint);
oldScaleKey->frame = (f32)frame-1;
oldScale[1].set(oldScaleKey->scale.set(data[0], data[1], data[2]));
}
}
if (flags & 4)
{
readFloats(data, 4);
if ((oldRotKey!=0) && (oldRot[0]==oldRot[1]))
{
// meant to be in this order since b3d stores W first
const core::quaternion rot(data[1], data[2], data[3], data[0]);
if (oldRot[1]==rot)
oldRotKey->frame = (f32)frame-1;
else
{
oldRot[0]=oldRot[1];
oldRotKey=AnimatedMesh->addRotationKey(inJoint);
oldRotKey->frame = (f32)frame-1;
oldRot[1].set(oldRotKey->rotation.set(data[1], data[2], data[3], data[0]));
}
}
else if (oldRotKey==0 && isFirst[2])
{
oldRotKey=AnimatedMesh->addRotationKey(inJoint);
oldRotKey->frame = (f32)frame-1;
// meant to be in this order since b3d stores W first
oldRot[0].set(oldRotKey->rotation.set(data[1], data[2], data[3], data[0]));
oldRotKey=0;
isFirst[2]=false;
}
else
{
if (oldRotKey!=0)
oldRot[0]=oldRot[1];
oldRotKey=AnimatedMesh->addRotationKey(inJoint);
oldRotKey->frame = (f32)frame-1;
// meant to be in this order since b3d stores W first
oldRot[1].set(oldRotKey->rotation.set(data[1], data[2], data[3], data[0]));
}
}
}
B3dStack.erase(B3dStack.size()-1);
return true;
}
bool CB3DMeshFileLoader::readChunkANIM()
{
#ifdef _B3D_READER_DEBUG
os::Printer::log("read ChunkANIM");
#endif
s32 animFlags; //not stored\used
s32 animFrames;//not stored\used
f32 animFPS; //not stored\used
B3DFile->read(&animFlags, sizeof(s32));
B3DFile->read(&animFrames, sizeof(s32));
readFloats(&animFPS, 1);
#ifdef __BIG_ENDIAN__
animFlags = os::Byteswap::byteswap(animFlags);
animFrames = os::Byteswap::byteswap(animFrames);
#endif
B3dStack.erase(B3dStack.size()-1);
return true;
}
bool CB3DMeshFileLoader::readChunkTEXS()
{
#ifdef _B3D_READER_DEBUG
os::Printer::log("read ChunkTEXS");
#endif
while((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) //this chunk repeats
{
Textures.push_back(SB3dTexture());
SB3dTexture& B3dTexture = Textures.getLast();
readString(B3dTexture.TextureName);
B3dTexture.TextureName.replace('\\','/');
#ifdef _B3D_READER_DEBUG
os::Printer::log("read Texture", B3dTexture.TextureName.c_str());
#endif
B3DFile->read(&B3dTexture.Flags, sizeof(s32));
B3DFile->read(&B3dTexture.Blend, sizeof(s32));
#ifdef __BIG_ENDIAN__
B3dTexture.Flags = os::Byteswap::byteswap(B3dTexture.Flags);
B3dTexture.Blend = os::Byteswap::byteswap(B3dTexture.Blend);
#endif
#ifdef _B3D_READER_DEBUG
os::Printer::log("Flags", core::stringc(B3dTexture.Flags).c_str());
os::Printer::log("Blend", core::stringc(B3dTexture.Blend).c_str());
#endif
readFloats(&B3dTexture.Xpos, 1);
readFloats(&B3dTexture.Ypos, 1);
readFloats(&B3dTexture.Xscale, 1);
readFloats(&B3dTexture.Yscale, 1);
readFloats(&B3dTexture.Angle, 1);
}
B3dStack.erase(B3dStack.size()-1);
return true;
}
bool CB3DMeshFileLoader::readChunkBRUS()
{
#ifdef _B3D_READER_DEBUG
os::Printer::log("read ChunkBRUS");
#endif
u32 n_texs;
B3DFile->read(&n_texs, sizeof(u32));
#ifdef __BIG_ENDIAN__
n_texs = os::Byteswap::byteswap(n_texs);
#endif
// number of texture ids read for Irrlicht
const u32 num_textures = core::min_(n_texs, video::MATERIAL_MAX_TEXTURES);
// number of bytes to skip (for ignored texture ids)
const u32 n_texs_offset = (num_textures<n_texs)?(n_texs-num_textures):0;
while((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) //this chunk repeats
{
// This is what blitz basic calls a brush, like a Irrlicht Material
core::stringc name;
readString(name);
#ifdef _B3D_READER_DEBUG
os::Printer::log("read Material", name);
#endif
Materials.push_back(SB3dMaterial());
SB3dMaterial& B3dMaterial=Materials.getLast();
readFloats(&B3dMaterial.red, 1);
readFloats(&B3dMaterial.green, 1);
readFloats(&B3dMaterial.blue, 1);
readFloats(&B3dMaterial.alpha, 1);
readFloats(&B3dMaterial.shininess, 1);
B3DFile->read(&B3dMaterial.blend, sizeof(B3dMaterial.blend));
B3DFile->read(&B3dMaterial.fx, sizeof(B3dMaterial.fx));
#ifdef __BIG_ENDIAN__
B3dMaterial.blend = os::Byteswap::byteswap(B3dMaterial.blend);
B3dMaterial.fx = os::Byteswap::byteswap(B3dMaterial.fx);
#endif
#ifdef _B3D_READER_DEBUG
os::Printer::log("Blend", core::stringc(B3dMaterial.blend).c_str());
os::Printer::log("FX", core::stringc(B3dMaterial.fx).c_str());
#endif
u32 i;
for (i=0; i<num_textures; ++i)
{
s32 texture_id=-1;
B3DFile->read(&texture_id, sizeof(s32));
#ifdef __BIG_ENDIAN__
texture_id = os::Byteswap::byteswap(texture_id);
#endif
//--- Get pointers to the texture, based on the IDs ---
if ((u32)texture_id < Textures.size())
{
B3dMaterial.Textures[i]=&Textures[texture_id];
#ifdef _B3D_READER_DEBUG
os::Printer::log("Layer", core::stringc(i).c_str());
os::Printer::log("using texture", Textures[texture_id].TextureName.c_str());
#endif
}
else
B3dMaterial.Textures[i]=0;
}
// skip other texture ids
for (i=0; i<n_texs_offset; ++i)
{
s32 texture_id=-1;
B3DFile->read(&texture_id, sizeof(s32));
#ifdef __BIG_ENDIAN__
texture_id = os::Byteswap::byteswap(texture_id);
#endif
if (ShowWarning && (texture_id != -1) && (n_texs>video::MATERIAL_MAX_TEXTURES))
{
os::Printer::log("Too many textures used in one material", B3DFile->getFileName(), ELL_WARNING);
ShowWarning = false;
}
}
//Fixes problems when the lightmap is on the first texture:
if (B3dMaterial.Textures[0] != 0)
{
if (B3dMaterial.Textures[0]->Flags & 65536) // 65536 = secondary UV
{
SB3dTexture *TmpTexture;
TmpTexture = B3dMaterial.Textures[1];
B3dMaterial.Textures[1] = B3dMaterial.Textures[0];
B3dMaterial.Textures[0] = TmpTexture;
}
}
//If a preceeding texture slot is empty move the others down:
for (i=num_textures; i>0; --i)
{
for (u32 j=i-1; j<num_textures-1; ++j)
{
if (B3dMaterial.Textures[j+1] != 0 && B3dMaterial.Textures[j] == 0)
{
B3dMaterial.Textures[j] = B3dMaterial.Textures[j+1];
B3dMaterial.Textures[j+1] = 0;
}
}
}
//------ Convert blitz flags/blend to irrlicht -------
//Two textures:
if (B3dMaterial.Textures[1])
{
if (B3dMaterial.alpha==1.f)
{
if (B3dMaterial.Textures[1]->Blend == 5) //(Multiply 2)
B3dMaterial.Material.MaterialType = video::EMT_LIGHTMAP_M2;
else
B3dMaterial.Material.MaterialType = video::EMT_LIGHTMAP;
B3dMaterial.Material.Lighting = false;
}
else
{
B3dMaterial.Material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
B3dMaterial.Material.ZWriteEnable = false;
}
}
else if (B3dMaterial.Textures[0]) //One texture:
{
// Flags & 0x1 is usual SOLID, 0x8 is mipmap (handled before)
if (B3dMaterial.Textures[0]->Flags & 0x2) //(Alpha mapped)
{
B3dMaterial.Material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
B3dMaterial.Material.ZWriteEnable = false;
}
else if (B3dMaterial.Textures[0]->Flags & 0x4) //(Masked)
B3dMaterial.Material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; // TODO: create color key texture
else if (B3dMaterial.Textures[0]->Flags & 0x40)
B3dMaterial.Material.MaterialType = video::EMT_SPHERE_MAP;
else if (B3dMaterial.Textures[0]->Flags & 0x80)
B3dMaterial.Material.MaterialType = video::EMT_SPHERE_MAP; // TODO: Should be cube map
else if (B3dMaterial.alpha == 1.f)
B3dMaterial.Material.MaterialType = video::EMT_SOLID;
else
{
B3dMaterial.Material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
B3dMaterial.Material.ZWriteEnable = false;
}
}
else //No texture:
{
if (B3dMaterial.alpha == 1.f)
B3dMaterial.Material.MaterialType = video::EMT_SOLID;
else
{
B3dMaterial.Material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
B3dMaterial.Material.ZWriteEnable = false;
}
}
B3dMaterial.Material.DiffuseColor = video::SColorf(B3dMaterial.red, B3dMaterial.green, B3dMaterial.blue, B3dMaterial.alpha).toSColor();
B3dMaterial.Material.ColorMaterial=video::ECM_NONE;
//------ Material fx ------
if (B3dMaterial.fx & 1) //full-bright
{
B3dMaterial.Material.AmbientColor = video::SColor(255, 255, 255, 255);
B3dMaterial.Material.Lighting = false;
}
else
B3dMaterial.Material.AmbientColor = B3dMaterial.Material.DiffuseColor;
if (B3dMaterial.fx & 2) //use vertex colors instead of brush color
B3dMaterial.Material.ColorMaterial=video::ECM_DIFFUSE_AND_AMBIENT;
if (B3dMaterial.fx & 4) //flatshaded
B3dMaterial.Material.GouraudShading = false;
if (B3dMaterial.fx & 16) //disable backface culling
B3dMaterial.Material.BackfaceCulling = false;
if (B3dMaterial.fx & 32) //force vertex alpha-blending
{
B3dMaterial.Material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
B3dMaterial.Material.ZWriteEnable = false;
}
B3dMaterial.Material.Shininess = B3dMaterial.shininess;
}
B3dStack.erase(B3dStack.size()-1);
return true;
}
void CB3DMeshFileLoader::loadTextures(SB3dMaterial& material) const
{
const bool previous32BitTextureFlag = SceneManager->getVideoDriver()->getTextureCreationFlag(video::ETCF_ALWAYS_32_BIT);
SceneManager->getVideoDriver()->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);
// read texture from disk
// note that mipmaps might be disabled by Flags & 0x8
const bool doMipMaps = SceneManager->getVideoDriver()->getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);
for (u32 i=0; i<video::MATERIAL_MAX_TEXTURES; ++i)
{
SB3dTexture* B3dTexture = material.Textures[i];
if (B3dTexture && B3dTexture->TextureName.size() && !material.Material.getTexture(i))
{
if (!SceneManager->getParameters()->getAttributeAsBool(B3D_LOADER_IGNORE_MIPMAP_FLAG))
SceneManager->getVideoDriver()->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, (B3dTexture->Flags & 0x8) ? true:false);
{
video::ITexture* tex = 0;
io::IFileSystem* fs = SceneManager->getFileSystem();
io::path texnameWithUserPath( SceneManager->getParameters()->getAttributeAsString(B3D_TEXTURE_PATH) );
if ( texnameWithUserPath.size() )
{
texnameWithUserPath += '/';
texnameWithUserPath += B3dTexture->TextureName;
}
if (fs->existFile(texnameWithUserPath))
tex = SceneManager->getVideoDriver()->getTexture(texnameWithUserPath);
else if (fs->existFile(B3dTexture->TextureName))
tex = SceneManager->getVideoDriver()->getTexture(B3dTexture->TextureName);
else if (fs->existFile(fs->getFileDir(B3DFile->getFileName()) +"/"+ fs->getFileBasename(B3dTexture->TextureName)))
tex = SceneManager->getVideoDriver()->getTexture(fs->getFileDir(B3DFile->getFileName()) +"/"+ fs->getFileBasename(B3dTexture->TextureName));
else
tex = SceneManager->getVideoDriver()->getTexture(fs->getFileBasename(B3dTexture->TextureName));
material.Material.setTexture(i, tex);
}
if (material.Textures[i]->Flags & 0x10) // Clamp U
material.Material.TextureLayer[i].TextureWrapU=video::ETC_CLAMP;
if (material.Textures[i]->Flags & 0x20) // Clamp V
material.Material.TextureLayer[i].TextureWrapV=video::ETC_CLAMP;
}
}
SceneManager->getVideoDriver()->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, doMipMaps);
SceneManager->getVideoDriver()->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, previous32BitTextureFlag);
}
void CB3DMeshFileLoader::readString(core::stringc& newstring)
{
newstring="";
while (B3DFile->getPos() <= B3DFile->getSize())
{
c8 character;
B3DFile->read(&character, sizeof(character));
if (character==0)
return;
newstring.append(character);
}
}
void CB3DMeshFileLoader::readFloats(f32* vec, u32 count)
{
B3DFile->read(vec, count*sizeof(f32));
#ifdef __BIG_ENDIAN__
for (u32 n=0; n<count; ++n)
vec[n] = os::Byteswap::byteswap(vec[n]);
#endif
}
} // end namespace scene
} // end namespace irr
#endif // _IRR_COMPILE_WITH_B3D_LOADER_
|
paupawsan/Irrlicht
|
b3913d7024c3922450cc17e9099e6397d3d53bd4
|
Add check for null pointer. Hopefully fixes the problem found by cyuyan on WindowsMobile
|
diff --git a/source/Irrlicht/CMountPointReader.cpp b/source/Irrlicht/CMountPointReader.cpp
index bb02130..07df00c 100644
--- a/source/Irrlicht/CMountPointReader.cpp
+++ b/source/Irrlicht/CMountPointReader.cpp
@@ -1,177 +1,174 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CMountPointReader.h"
#ifdef __IRR_COMPILE_WITH_MOUNT_ARCHIVE_LOADER_
#include "CReadFile.h"
#include "os.h"
namespace irr
{
namespace io
{
//! Constructor
CArchiveLoaderMount::CArchiveLoaderMount( io::IFileSystem* fs)
: FileSystem(fs)
{
#ifdef _DEBUG
setDebugName("CArchiveLoaderMount");
#endif
}
//! destructor
CArchiveLoaderMount::~CArchiveLoaderMount()
{
}
//! returns true if the file maybe is able to be loaded by this class
bool CArchiveLoaderMount::isALoadableFileFormat(const io::path& filename) const
{
bool ret = false;
io::path fname(filename);
deletePathFromFilename(fname);
if (!fname.size())
{
ret = true;
}
return ret;
}
//! Check to see if the loader can create archives of this type.
bool CArchiveLoaderMount::isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) const
{
return fileType == EFAT_FOLDER;
}
//! Check if the file might be loaded by this class
bool CArchiveLoaderMount::isALoadableFileFormat(io::IReadFile* file) const
{
return false;
}
//! Creates an archive from the filename
IFileArchive* CArchiveLoaderMount::createArchive(const io::path& filename, bool ignoreCase, bool ignorePaths) const
{
IFileArchive *archive = 0;
EFileSystemType current = FileSystem->setFileListSystem(FILESYSTEM_NATIVE);
io::path save = FileSystem->getWorkingDirectory();
io::path fullPath = FileSystem->getAbsolutePath(filename);
FileSystem->flattenFilename(fullPath);
if ( FileSystem->changeWorkingDirectoryTo ( fullPath ) )
{
archive = new CMountPointReader(FileSystem, fullPath, ignoreCase, ignorePaths);
}
FileSystem->changeWorkingDirectoryTo(save);
FileSystem->setFileListSystem(current);
return archive;
}
//! creates/loads an archive from the file.
//! \return Pointer to the created archive. Returns 0 if loading failed.
IFileArchive* CArchiveLoaderMount::createArchive(io::IReadFile* file, bool ignoreCase, bool ignorePaths) const
{
return 0;
}
-//! compatible Folder Archticture
-//
+//! compatible Folder Architecture
CMountPointReader::CMountPointReader(IFileSystem * parent, const io::path& basename, bool ignoreCase, bool ignorePaths)
: CFileList(basename, ignoreCase, ignorePaths), Parent(parent)
{
//! ensure CFileList path ends in a slash
if (Path.lastChar() != '/' )
- Path.append ('/');
+ Path.append('/');
- io::path work = Parent->getWorkingDirectory();
+ const io::path work = Parent->getWorkingDirectory();
Parent->changeWorkingDirectoryTo(basename);
buildDirectory();
Parent->changeWorkingDirectoryTo(work);
sort();
}
-CMountPointReader::~CMountPointReader()
-{
-
-}
//! returns the list of files
const IFileList* CMountPointReader::getFileList() const
{
return this;
}
void CMountPointReader::buildDirectory()
{
IFileList * list = Parent->createFileList();
+ if (!list)
+ return;
const u32 size = list->getFileCount();
for (u32 i=0; i < size; ++i)
{
io::path full = list->getFullFileName(i);
full = full.subString(Path.size(), full.size() - Path.size());
if (!list->isDirectory(i))
{
addItem(full, list->getFileSize(i), false, RealFileNames.size());
RealFileNames.push_back(list->getFullFileName(i));
}
else
{
const io::path rel = list->getFileName(i);
io::path pwd = Parent->getWorkingDirectory();
if (pwd.lastChar() != '/')
pwd.append('/');
pwd.append(rel);
if ( rel != "." && rel != ".." )
{
addItem(full, 0, true, 0);
Parent->changeWorkingDirectoryTo(pwd);
- buildDirectory ();
+ buildDirectory();
Parent->changeWorkingDirectoryTo("..");
}
}
}
list->drop();
}
//! opens a file by index
IReadFile* CMountPointReader::createAndOpenFile(u32 index)
{
if (index >= Files.size())
return 0;
return createReadFile(RealFileNames[Files[index].ID]);
}
//! opens a file by file name
IReadFile* CMountPointReader::createAndOpenFile(const io::path& filename)
{
s32 index = findFile(filename, false);
if (index != -1)
return createAndOpenFile(index);
else
return 0;
}
} // io
} // irr
#endif // __IRR_COMPILE_WITH_MOUNT_ARCHIVE_LOADER_
|
paupawsan/Irrlicht
|
f89251f388a370516c176fb74a640abe7ca69e0f
|
Fix rounding problems in SColor::getInterpolated, SColorf::toSColor and SColorHSL::toRGB1 (thx to Virion for noticing)
|
diff --git a/include/SColor.h b/include/SColor.h
index 763ee89..8b04661 100644
--- a/include/SColor.h
+++ b/include/SColor.h
@@ -1,582 +1,582 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __COLOR_H_INCLUDED__
#define __COLOR_H_INCLUDED__
#include "irrTypes.h"
#include "irrMath.h"
namespace irr
{
namespace video
{
//! Creates a 16 bit A1R5G5B5 color
inline u16 RGBA16(u32 r, u32 g, u32 b, u32 a=0xFF)
{
return (u16)((a & 0x80) << 8 |
(r & 0xF8) << 7 |
(g & 0xF8) << 2 |
(b & 0xF8) >> 3);
}
//! Creates a 16 bit A1R5G5B5 color
inline u16 RGB16(u32 r, u32 g, u32 b)
{
return RGBA16(r,g,b);
}
//! Creates a 16bit A1R5G5B5 color, based on 16bit input values
inline u16 RGB16from16(u16 r, u16 g, u16 b)
{
return (0x8000 |
(r & 0x1F) << 10 |
(g & 0x1F) << 5 |
(b & 0x1F));
}
//! Converts a 32bit (X8R8G8B8) color to a 16bit A1R5G5B5 color
inline u16 X8R8G8B8toA1R5G5B5(u32 color)
{
return (u16)(0x8000 |
( color & 0x00F80000) >> 9 |
( color & 0x0000F800) >> 6 |
( color & 0x000000F8) >> 3);
}
//! Converts a 32bit (A8R8G8B8) color to a 16bit A1R5G5B5 color
inline u16 A8R8G8B8toA1R5G5B5(u32 color)
{
return (u16)(( color & 0x80000000) >> 16|
( color & 0x00F80000) >> 9 |
( color & 0x0000F800) >> 6 |
( color & 0x000000F8) >> 3);
}
//! Converts a 32bit (A8R8G8B8) color to a 16bit R5G6B5 color
inline u16 A8R8G8B8toR5G6B5(u32 color)
{
return (u16)(( color & 0x00F80000) >> 8 |
( color & 0x0000FC00) >> 5 |
( color & 0x000000F8) >> 3);
}
//! Convert A8R8G8B8 Color from A1R5G5B5 color
/** build a nicer 32bit Color by extending dest lower bits with source high bits. */
inline u32 A1R5G5B5toA8R8G8B8(u16 color)
{
return ( (( -( (s32) color & 0x00008000 ) >> (s32) 31 ) & 0xFF000000 ) |
(( color & 0x00007C00 ) << 9) | (( color & 0x00007000 ) << 4) |
(( color & 0x000003E0 ) << 6) | (( color & 0x00000380 ) << 1) |
(( color & 0x0000001F ) << 3) | (( color & 0x0000001C ) >> 2)
);
}
//! Returns A8R8G8B8 Color from R5G6B5 color
inline u32 R5G6B5toA8R8G8B8(u16 color)
{
return 0xFF000000 |
((color & 0xF800) << 8)|
((color & 0x07E0) << 5)|
((color & 0x001F) << 3);
}
//! Returns A1R5G5B5 Color from R5G6B5 color
inline u16 R5G6B5toA1R5G5B5(u16 color)
{
return 0x8000 | (((color & 0xFFC0) >> 1) | (color & 0x1F));
}
//! Returns R5G6B5 Color from A1R5G5B5 color
inline u16 A1R5G5B5toR5G6B5(u16 color)
{
return (((color & 0x7FE0) << 1) | (color & 0x1F));
}
//! Returns the alpha component from A1R5G5B5 color
/** In Irrlicht, alpha refers to opacity.
\return The alpha value of the color. 0 is transparent, 1 is opaque. */
inline u32 getAlpha(u16 color)
{
return ((color >> 15)&0x1);
}
//! Returns the red component from A1R5G5B5 color.
/** Shift left by 3 to get 8 bit value. */
inline u32 getRed(u16 color)
{
return ((color >> 10)&0x1F);
}
//! Returns the green component from A1R5G5B5 color
/** Shift left by 3 to get 8 bit value. */
inline u32 getGreen(u16 color)
{
return ((color >> 5)&0x1F);
}
//! Returns the blue component from A1R5G5B5 color
/** Shift left by 3 to get 8 bit value. */
inline u32 getBlue(u16 color)
{
return (color & 0x1F);
}
//! Returns the average from a 16 bit A1R5G5B5 color
inline s32 getAverage(s16 color)
{
return ((getRed(color)<<3) + (getGreen(color)<<3) + (getBlue(color)<<3)) / 3;
}
//! Class representing a 32 bit ARGB color.
/** The color values for alpha, red, green, and blue are
stored in a single u32. So all four values may be between 0 and 255.
Alpha in Irrlicht is opacity, so 0 is fully transparent, 255 is fully opaque (solid).
This class is used by most parts of the Irrlicht Engine
to specify a color. Another way is using the class SColorf, which
stores the color values in 4 floats.
This class must consist of only one u32 and must not use virtual functions.
*/
class SColor
{
public:
//! Constructor of the Color. Does nothing.
/** The color value is not initialized to save time. */
SColor() {}
//! Constructs the color from 4 values representing the alpha, red, green and blue component.
/** Must be values between 0 and 255. */
SColor (u32 a, u32 r, u32 g, u32 b)
: color(((a & 0xff)<<24) | ((r & 0xff)<<16) | ((g & 0xff)<<8) | (b & 0xff)) {}
//! Constructs the color from a 32 bit value. Could be another color.
SColor(u32 clr)
: color(clr) {}
//! Returns the alpha component of the color.
/** The alpha component defines how opaque a color is.
\return The alpha value of the color. 0 is fully transparent, 255 is fully opaque. */
u32 getAlpha() const { return color>>24; }
//! Returns the red component of the color.
/** \return Value between 0 and 255, specifying how red the color is.
0 means no red, 255 means full red. */
u32 getRed() const { return (color>>16) & 0xff; }
//! Returns the green component of the color.
/** \return Value between 0 and 255, specifying how green the color is.
0 means no green, 255 means full green. */
u32 getGreen() const { return (color>>8) & 0xff; }
//! Returns the blue component of the color.
/** \return Value between 0 and 255, specifying how blue the color is.
0 means no blue, 255 means full blue. */
u32 getBlue() const { return color & 0xff; }
//! Get lightness of the color in the range [0,255]
f32 getLightness() const
{
return 0.5f*(core::max_(core::max_(getRed(),getGreen()),getBlue())+core::min_(core::min_(getRed(),getGreen()),getBlue()));
}
//! Get luminance of the color in the range [0,255].
f32 getLuminance() const
{
return 0.3f*getRed() + 0.59f*getGreen() + 0.11f*getBlue();
}
//! Get average intensity of the color in the range [0,255].
u32 getAverage() const
{
return ( getRed() + getGreen() + getBlue() ) / 3;
}
//! Sets the alpha component of the Color.
/** The alpha component defines how transparent a color should be.
\param a The alpha value of the color. 0 is fully transparent, 255 is fully opaque. */
void setAlpha(u32 a) { color = ((a & 0xff)<<24) | (color & 0x00ffffff); }
//! Sets the red component of the Color.
/** \param r: Has to be a value between 0 and 255.
0 means no red, 255 means full red. */
void setRed(u32 r) { color = ((r & 0xff)<<16) | (color & 0xff00ffff); }
//! Sets the green component of the Color.
/** \param g: Has to be a value between 0 and 255.
0 means no green, 255 means full green. */
void setGreen(u32 g) { color = ((g & 0xff)<<8) | (color & 0xffff00ff); }
//! Sets the blue component of the Color.
/** \param b: Has to be a value between 0 and 255.
0 means no blue, 255 means full blue. */
void setBlue(u32 b) { color = (b & 0xff) | (color & 0xffffff00); }
//! Calculates a 16 bit A1R5G5B5 value of this color.
/** \return 16 bit A1R5G5B5 value of this color. */
u16 toA1R5G5B5() const { return A8R8G8B8toA1R5G5B5(color); }
//! Converts color to OpenGL color format
/** From ARGB to RGBA in 4 byte components for endian aware
passing to OpenGL
\param dest: address where the 4x8 bit OpenGL color is stored. */
void toOpenGLColor(u8* dest) const
{
*dest = (u8)getRed();
*++dest = (u8)getGreen();
*++dest = (u8)getBlue();
*++dest = (u8)getAlpha();
}
//! Sets all four components of the color at once.
/** Constructs the color from 4 values representing the alpha,
red, green and blue components of the color. Must be values
between 0 and 255.
\param a: Alpha component of the color. The alpha component
defines how transparent a color should be. Has to be a value
between 0 and 255. 255 means not transparent (opaque), 0 means
fully transparent.
\param r: Sets the red component of the Color. Has to be a
value between 0 and 255. 0 means no red, 255 means full red.
\param g: Sets the green component of the Color. Has to be a
value between 0 and 255. 0 means no green, 255 means full
green.
\param b: Sets the blue component of the Color. Has to be a
value between 0 and 255. 0 means no blue, 255 means full blue. */
void set(u32 a, u32 r, u32 g, u32 b)
{
color = (((a & 0xff)<<24) | ((r & 0xff)<<16) | ((g & 0xff)<<8) | (b & 0xff));
}
void set(u32 col) { color = col; }
//! Compares the color to another color.
/** \return True if the colors are the same, and false if not. */
bool operator==(const SColor& other) const { return other.color == color; }
//! Compares the color to another color.
/** \return True if the colors are different, and false if they are the same. */
bool operator!=(const SColor& other) const { return other.color != color; }
//! comparison operator
/** \return True if this color is smaller than the other one */
bool operator<(const SColor& other) const { return (color < other.color); }
//! Adds two colors, result is clamped to 0..255 values
/** \param other Color to add to this color
\return Addition of the two colors, clamped to 0..255 values */
SColor operator+(const SColor& other) const
{
return SColor(core::min_(getAlpha() + other.getAlpha(), 255u),
core::min_(getRed() + other.getRed(), 255u),
core::min_(getGreen() + other.getGreen(), 255u),
core::min_(getBlue() + other.getBlue(), 255u));
}
//! Interpolates the color with a f32 value to another color
/** \param other: Other color
\param d: value between 0.0f and 1.0f
\return Interpolated color. */
SColor getInterpolated(const SColor &other, f32 d) const
{
d = core::clamp(d, 0.f, 1.f);
const f32 inv = 1.0f - d;
- return SColor((u32)(other.getAlpha()*inv + getAlpha()*d),
- (u32)(other.getRed()*inv + getRed()*d),
- (u32)(other.getGreen()*inv + getGreen()*d),
- (u32)(other.getBlue()*inv + getBlue()*d));
+ return SColor((u32)core::round32(other.getAlpha()*inv + getAlpha()*d),
+ (u32)core::round32(other.getRed()*inv + getRed()*d),
+ (u32)core::round32(other.getGreen()*inv + getGreen()*d),
+ (u32)core::round32(other.getBlue()*inv + getBlue()*d));
}
//! Returns interpolated color. ( quadratic )
/** \param c1: first color to interpolate with
\param c2: second color to interpolate with
\param d: value between 0.0f and 1.0f. */
SColor getInterpolated_quadratic(const SColor& c1, const SColor& c2, f32 d) const
{
// this*(1-d)*(1-d) + 2 * c1 * (1-d) + c2 * d * d;
d = core::clamp(d, 0.f, 1.f);
const f32 inv = 1.f - d;
const f32 mul0 = inv * inv;
const f32 mul1 = 2.f * d * inv;
const f32 mul2 = d * d;
return SColor(
core::clamp( core::floor32(
getAlpha() * mul0 + c1.getAlpha() * mul1 + c2.getAlpha() * mul2 ), 0, 255 ),
core::clamp( core::floor32(
getRed() * mul0 + c1.getRed() * mul1 + c2.getRed() * mul2 ), 0, 255 ),
core::clamp ( core::floor32(
getGreen() * mul0 + c1.getGreen() * mul1 + c2.getGreen() * mul2 ), 0, 255 ),
core::clamp ( core::floor32(
getBlue() * mul0 + c1.getBlue() * mul1 + c2.getBlue() * mul2 ), 0, 255 ));
}
//! color in A8R8G8B8 Format
u32 color;
};
//! Class representing a color with four floats.
/** The color values for red, green, blue
and alpha are each stored in a 32 bit floating point variable.
So all four values may be between 0.0f and 1.0f.
Another, faster way to define colors is using the class SColor, which
stores the color values in a single 32 bit integer.
*/
class SColorf
{
public:
//! Default constructor for SColorf.
/** Sets red, green and blue to 0.0f and alpha to 1.0f. */
SColorf() : r(0.0f), g(0.0f), b(0.0f), a(1.0f) {}
//! Constructs a color from up to four color values: red, green, blue, and alpha.
/** \param r: Red color component. Should be a value between
0.0f meaning no red and 1.0f, meaning full red.
\param g: Green color component. Should be a value between 0.0f
meaning no green and 1.0f, meaning full green.
\param b: Blue color component. Should be a value between 0.0f
meaning no blue and 1.0f, meaning full blue.
\param a: Alpha color component of the color. The alpha
component defines how transparent a color should be. Has to be
a value between 0.0f and 1.0f, 1.0f means not transparent
(opaque), 0.0f means fully transparent. */
SColorf(f32 r, f32 g, f32 b, f32 a = 1.0f) : r(r), g(g), b(b), a(a) {}
//! Constructs a color from 32 bit Color.
/** \param c: 32 bit color from which this SColorf class is
constructed from. */
SColorf(SColor c)
{
const f32 inv = 1.0f / 255.0f;
r = c.getRed() * inv;
g = c.getGreen() * inv;
b = c.getBlue() * inv;
a = c.getAlpha() * inv;
}
//! Converts this color to a SColor without floats.
SColor toSColor() const
{
- return SColor((u32)(a*255.0f), (u32)(r*255.0f), (u32)(g*255.0f), (u32)(b*255.0f));
+ return SColor((u32)core::round32(a*255.0f), (u32)core::round32(r*255.0f), (u32)core::round32(g*255.0f), (u32)core::round32(b*255.0f));
}
//! Sets three color components to new values at once.
/** \param rr: Red color component. Should be a value between 0.0f meaning
no red (=black) and 1.0f, meaning full red.
\param gg: Green color component. Should be a value between 0.0f meaning
no green (=black) and 1.0f, meaning full green.
\param bb: Blue color component. Should be a value between 0.0f meaning
no blue (=black) and 1.0f, meaning full blue. */
void set(f32 rr, f32 gg, f32 bb) {r = rr; g =gg; b = bb; }
//! Sets all four color components to new values at once.
/** \param aa: Alpha component. Should be a value between 0.0f meaning
fully transparent and 1.0f, meaning opaque.
\param rr: Red color component. Should be a value between 0.0f meaning
no red and 1.0f, meaning full red.
\param gg: Green color component. Should be a value between 0.0f meaning
no green and 1.0f, meaning full green.
\param bb: Blue color component. Should be a value between 0.0f meaning
no blue and 1.0f, meaning full blue. */
void set(f32 aa, f32 rr, f32 gg, f32 bb) {a = aa; r = rr; g =gg; b = bb; }
//! Interpolates the color with a f32 value to another color
/** \param other: Other color
\param d: value between 0.0f and 1.0f
\return Interpolated color. */
SColorf getInterpolated(const SColorf &other, f32 d) const
{
d = core::clamp(d, 0.f, 1.f);
const f32 inv = 1.0f - d;
return SColorf(other.r*inv + r*d,
other.g*inv + g*d, other.b*inv + b*d, other.a*inv + a*d);
}
//! Returns interpolated color. ( quadratic )
/** \param c1: first color to interpolate with
\param c2: second color to interpolate with
\param d: value between 0.0f and 1.0f. */
inline SColorf getInterpolated_quadratic(const SColorf& c1, const SColorf& c2,
f32 d) const
{
d = core::clamp(d, 0.f, 1.f);
// this*(1-d)*(1-d) + 2 * c1 * (1-d) + c2 * d * d;
const f32 inv = 1.f - d;
const f32 mul0 = inv * inv;
const f32 mul1 = 2.f * d * inv;
const f32 mul2 = d * d;
return SColorf (r * mul0 + c1.r * mul1 + c2.r * mul2,
g * mul0 + c1.g * mul1 + c2.g * mul2,
g * mul0 + c1.b * mul1 + c2.b * mul2,
a * mul0 + c1.a * mul1 + c2.a * mul2);
}
//! Sets a color component by index. R=0, G=1, B=2, A=3
void setColorComponentValue(s32 index, f32 value)
{
switch(index)
{
case 0: r = value; break;
case 1: g = value; break;
case 2: b = value; break;
case 3: a = value; break;
}
}
//! Returns the alpha component of the color in the range 0.0 (transparent) to 1.0 (opaque)
f32 getAlpha() const { return a; }
//! Returns the red component of the color in the range 0.0 to 1.0
f32 getRed() const { return r; }
//! Returns the green component of the color in the range 0.0 to 1.0
f32 getGreen() const { return g; }
//! Returns the blue component of the color in the range 0.0 to 1.0
f32 getBlue() const { return b; }
//! red color component
f32 r;
//! green color component
f32 g;
//! blue component
f32 b;
//! alpha color component
f32 a;
};
//! Class representing a color in HSV format
/** The color values for hue, saturation, value
are stored in a 32 bit floating point variable.
*/
class SColorHSL
{
public:
SColorHSL ( f32 h = 0.f, f32 s = 0.f, f32 l = 0.f )
: Hue ( h ), Saturation ( s ), Luminance ( l ) {}
void fromRGB(const SColor &color);
void toRGB(SColor &color) const;
f32 Hue;
f32 Saturation;
f32 Luminance;
private:
inline u32 toRGB1(f32 rm1, f32 rm2, f32 rh) const;
};
inline void SColorHSL::fromRGB(const SColor &color)
{
const u32 maxValInt = core::max_(color.getRed(), color.getGreen(), color.getBlue());
const f32 maxVal = (f32)maxValInt;
const f32 minVal = (f32)core::min_(color.getRed(), color.getGreen(), color.getBlue());
Luminance = (maxVal/minVal)*0.5f;
if (core::equals(maxVal, minVal))
{
Hue=0.f;
Saturation=0.f;
return;
}
const f32 delta = maxVal-minVal;
if ( Luminance <= 0.5f )
{
Saturation = (delta)/(maxVal+minVal);
}
else
{
Saturation = (delta)/(2-maxVal-minVal);
}
if (maxValInt == color.getRed())
Hue = (color.getGreen()-color.getBlue())/delta;
else if (maxValInt == color.getGreen())
Hue = 2+(color.getBlue()-color.getRed())/delta;
else // blue is max
Hue = 4+(color.getRed()-color.getGreen())/delta;
Hue *= (60.0f * core::DEGTORAD);
while ( Hue < 0.f )
Hue += 2.f * core::PI;
}
inline void SColorHSL::toRGB(SColor &color) const
{
if (core::iszero(Saturation)) // grey
{
u8 c = (u8) ( Luminance * 255.0 );
color.setRed(c);
color.setGreen(c);
color.setBlue(c);
return;
}
f32 rm2;
if ( Luminance <= 0.5f )
{
rm2 = Luminance + Luminance * Saturation;
}
else
{
rm2 = Luminance + Saturation - Luminance * Saturation;
}
const f32 rm1 = 2.0f * Luminance - rm2;
color.setRed ( toRGB1(rm1, rm2, Hue + (120.0f * core::DEGTORAD )) );
color.setGreen ( toRGB1(rm1, rm2, Hue) );
color.setBlue ( toRGB1(rm1, rm2, Hue - (120.0f * core::DEGTORAD) ) );
}
inline u32 SColorHSL::toRGB1(f32 rm1, f32 rm2, f32 rh) const
{
while ( rh > 2.f * core::PI )
rh -= 2.f * core::PI;
while ( rh < 0.f )
rh += 2.f * core::PI;
if (rh < 60.0f * core::DEGTORAD )
rm1 = rm1 + (rm2 - rm1) * rh / (60.0f * core::DEGTORAD);
else if (rh < 180.0f * core::DEGTORAD )
rm1 = rm2;
else if (rh < 240.0f * core::DEGTORAD )
rm1 = rm1 + (rm2 - rm1) * ( ( 240.0f * core::DEGTORAD ) - rh) /
(60.0f * core::DEGTORAD);
- return (u32) (rm1 * 255.f);
+ return (u32) core::round32(rm1 * 255.f);
}
} // end namespace video
} // end namespace irr
#endif
diff --git a/tests/color.cpp b/tests/color.cpp
new file mode 100644
index 0000000..2811b24
--- /dev/null
+++ b/tests/color.cpp
@@ -0,0 +1,21 @@
+#include "testUtils.h"
+
+using namespace irr;
+using namespace video;
+
+bool rounding()
+{
+ SColorf colf(0.003922, 0.007843, 0.011765); // test-values by virion which once failed
+ SColor col = colf.toSColor();
+ return col.getRed() == 1 && col.getGreen() == 2 && col.getBlue() == 3;
+}
+
+//! Test SColor and SColorf
+bool color(void)
+{
+ bool ok = true;
+
+ ok &= rounding();
+
+ return ok;
+}
diff --git a/tests/main.cpp b/tests/main.cpp
index bd2a8e2..bcf3731 100644
--- a/tests/main.cpp
+++ b/tests/main.cpp
@@ -1,239 +1,240 @@
// Copyright (C) 2008-2009 Colin MacDonald and Christian Stehno
// No rights reserved: this software is in the public domain.
// This is the entry point for the Irrlicht test suite.
// This is an MSVC pragma to link against the Irrlicht library.
// Other builds must link against it in the project files.
#if defined(_MSC_VER)
#pragma comment(lib, "Irrlicht.lib")
#define _CRT_SECURE_NO_WARNINGS 1
#endif // _MSC_VER
#include "testUtils.h"
#include <stdio.h>
#include <time.h>
#include <vector>
struct STestDefinition
{
//! The test entry point function
bool(*testSignature)(void);
//! A descriptive name for the test
const char * testName;
};
//! This is the main entry point for the Irrlicht test suite.
/** \return The number of test that failed, i.e. 0 is success. */
int main(int argumentCount, char * arguments[])
{
if(argumentCount > 3)
{
logTestString("\nUsage: %s [testNumber] [testCount]\n");
return 9999;
}
#define TEST(x)\
{\
extern bool x(void);\
STestDefinition newTest;\
newTest.testSignature = x;\
newTest.testName = #x;\
tests.push_back(newTest);\
}
// Use an STL vector so that we don't rely on Irrlicht.
std::vector<STestDefinition> tests;
// Note that to interactively debug a test, you will generally want to move it
// (temporarily) to the beginning of the list, since each test runs in its own
// process.
TEST(disambiguateTextures); // Normally you should run this first, since it validates the working directory.
// Now the simple tests without device
TEST(testIrrArray);
TEST(testIrrMap);
TEST(testIrrList);
TEST(exports);
TEST(irrCoreEquals);
TEST(testIrrString);
TEST(line2dIntersectWith);
TEST(matrixOps);
TEST(testDimension2d);
TEST(testVector2d);
TEST(testVector3d);
TEST(testQuaternion);
TEST(testS3DVertex);
TEST(testaabbox3d);
+ TEST(color);
// TODO: Needs to be fixed first
// TEST(testTriangle3d);
TEST(vectorPositionDimension2d);
// file system checks (with null driver)
TEST(filesystem);
TEST(archiveReader);
TEST(testXML);
TEST(serializeAttributes);
// null driver
TEST(fast_atof);
TEST(loadTextures);
TEST(collisionResponseAnimator);
TEST(enumerateImageManipulators);
TEST(removeCustomAnimator);
TEST(sceneCollisionManager);
TEST(sceneNodeAnimator);
TEST(meshLoaders);
TEST(testTimer);
// software drivers only
TEST(softwareDevice);
TEST(b3dAnimation);
TEST(burningsVideo);
TEST(cursorSetVisible);
TEST(drawRectOutline);
TEST(flyCircleAnimator);
TEST(md2Animation);
TEST(testGeometryCreator);
TEST(writeImageToFile);
TEST(meshTransform);
// all driver checks
TEST(drawPixel);
TEST(guiDisabledMenu);
TEST(makeColorKeyTexture);
TEST(renderTargetTexture);
TEST(textureFeatures);
TEST(textureRenderStates);
TEST(transparentAlphaChannelRef);
TEST(antiAliasing);
TEST(draw2DImage);
// TODO: Needs to be fixed first.
// TEST(projectionMatrix);
// large scenes
TEST(planeMatrix);
TEST(terrainSceneNode);
TEST(lightMaps);
unsigned int numberOfTests = tests.size();
unsigned int testToRun = 0;
unsigned int fails = 0;
bool firstRun=true;
const bool spawn=false;
// args: [testNumber] [testCount]
if(argumentCount > 1)
{
if (!strcmp(arguments[1],"--list"))
{
for (unsigned int i=0; i<tests.size(); ++i)
{
printf("%3d: %s\n", i, tests[i].testName);
}
printf("\n");
return 0;
}
int tmp = atoi(arguments[1]);
firstRun = (tmp>=0);
testToRun=abs(tmp);
if (!firstRun)
testToRun -= 1;
if(argumentCount > 2)
{
numberOfTests = testToRun + abs(atoi(arguments[2]));
if (numberOfTests>=tests.size())
numberOfTests=tests.size();
}
}
if(testToRun >= numberOfTests)
{
logTestString("\nError: invalid test %d (maximum %d)\n",
testToRun, numberOfTests-testToRun);
return 9999;
}
const unsigned int testCount = numberOfTests-testToRun;
const bool logFileOpened = openTestLog(firstRun);
assert(logFileOpened);
if (firstRun)
{
if (numberOfTests)
{
for (unsigned int i=testToRun; i<numberOfTests; ++i)
{
logTestString("\nStarting test %d, '%s'\n",
i, tests[i].testName);
if (spawn)
{
closeTestLog();
char runNextTest[256];
(void)sprintf(runNextTest, "\"%s\" -%d 1", arguments[0], i+1);
// Spawn the next test in a new process.
if (system(runNextTest))
{
(void)openTestLog(false);
logTestString("\n******** Test failure ********\n"\
"Test %d '%s' failed\n"\
"******** Test failure ********\n",
i, tests[i].testName);
++fails;
}
else
(void)openTestLog(false);
}
else
{
if (!tests[i].testSignature())
{
logTestString("\n******** Test failure ********\n"\
"Test %d '%s' failed\n"\
"******** Test failure ********\n",
i, tests[i].testName);
++fails;
}
}
}
}
const int passed = testCount - fails;
logTestString("\nTests finished. %d test%s of %d passed.\n\n",
passed, 1 == passed ? "" : "s", testCount);
if(0 == fails && testCount==tests.size())
{
time_t rawtime;
struct tm * timeinfo;
(void)time(&rawtime);
timeinfo = gmtime(&rawtime);
(void)printf("\nTest suite pass at GMT %s\n", asctime(timeinfo));
FILE * testsLastPassedAtFile = fopen("tests-last-passed-at.txt", "w");
if(testsLastPassedAtFile)
{
(void)fprintf(testsLastPassedAtFile, "Tests finished. %d test%s of %d passed.\n",
passed, 1 == passed ? "" : "s", numberOfTests);
#ifdef _DEBUG
(void)fprintf(testsLastPassedAtFile, "Compiled as DEBUG\n");
#else
(void)fprintf(testsLastPassedAtFile, "Compiled as RELEASE\n");
#endif
(void)fprintf(testsLastPassedAtFile, "Test suite pass at GMT %s\n", asctime(timeinfo));
(void)fclose(testsLastPassedAtFile);
}
}
closeTestLog();
#ifdef _IRR_WINDOWS_
(void)system("tests.log");
#else
(void)system("$PAGER tests.log");
#endif
return fails;
}
else
{
const bool res = tests[testToRun].testSignature();
closeTestLog();
return res?0:1;
}
}
diff --git a/tests/tests-last-passed-at.txt b/tests/tests-last-passed-at.txt
index 71b990b..c43456d 100644
--- a/tests/tests-last-passed-at.txt
+++ b/tests/tests-last-passed-at.txt
@@ -1,4 +1,4 @@
-Tests finished. 51 tests of 51 passed.
+Tests finished. 52 tests of 52 passed.
Compiled as DEBUG
-Test suite pass at GMT Mon Mar 8 13:04:19 2010
+Test suite pass at GMT Sun Mar 28 16:24:25 2010
|
paupawsan/Irrlicht
|
68ae2116c841b41c87d58bb94d4e32d096894340
|
Scrollbar in CGUIListBox no longer uses id 0, but id -1 as usual (thx to Auria for noticing). If you used the id to distinguish the scrollbar from the listbox in your code, please switch to using isSubElement.
|
diff --git a/source/Irrlicht/CGUIListBox.cpp b/source/Irrlicht/CGUIListBox.cpp
index 0a4f737..37a9937 100644
--- a/source/Irrlicht/CGUIListBox.cpp
+++ b/source/Irrlicht/CGUIListBox.cpp
@@ -1,551 +1,551 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CGUIListBox.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include "CGUIListBox.h"
#include "IGUISkin.h"
#include "IGUIEnvironment.h"
#include "IVideoDriver.h"
#include "IGUIFont.h"
#include "IGUISpriteBank.h"
#include "CGUIScrollBar.h"
#include "os.h"
namespace irr
{
namespace gui
{
//! constructor
CGUIListBox::CGUIListBox(IGUIEnvironment* environment, IGUIElement* parent,
s32 id, core::rect<s32> rectangle, bool clip,
bool drawBack, bool moveOverSelect)
: IGUIListBox(environment, parent, id, rectangle), Selected(-1),
ItemHeight(0),ItemHeightOverride(0),
TotalItemHeight(0), ItemsIconWidth(0), Font(0), IconBank(0),
ScrollBar(0), selectTime(0), LastKeyTime(0), Selecting(false), DrawBack(drawBack),
MoveOverSelect(moveOverSelect), AutoScroll(true), HighlightWhenNotFocused(true)
{
#ifdef _DEBUG
setDebugName("CGUIListBox");
#endif
IGUISkin* skin = Environment->getSkin();
const s32 s = skin->getSize(EGDS_SCROLLBAR_SIZE);
- ScrollBar = new CGUIScrollBar(false, Environment, this, 0,
+ ScrollBar = new CGUIScrollBar(false, Environment, this, -1,
core::rect<s32>(RelativeRect.getWidth() - s, 0, RelativeRect.getWidth(), RelativeRect.getHeight()),
!clip);
ScrollBar->setSubElement(true);
ScrollBar->setTabStop(false);
ScrollBar->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT);
ScrollBar->setVisible(false);
ScrollBar->setPos(0);
setNotClipped(!clip);
// this element can be tabbed to
setTabStop(true);
setTabOrder(-1);
updateAbsolutePosition();
}
//! destructor
CGUIListBox::~CGUIListBox()
{
if (ScrollBar)
ScrollBar->drop();
if (Font)
Font->drop();
if (IconBank)
IconBank->drop();
}
//! returns amount of list items
u32 CGUIListBox::getItemCount() const
{
return Items.size();
}
//! returns string of a list item. the may be a value from 0 to itemCount-1
const wchar_t* CGUIListBox::getListItem(u32 id) const
{
if (id>=Items.size())
return 0;
return Items[id].text.c_str();
}
//! Returns the icon of an item
s32 CGUIListBox::getIcon(u32 id) const
{
if (id>=Items.size())
return -1;
return Items[id].icon;
}
//! adds a list item, returns id of item
u32 CGUIListBox::addItem(const wchar_t* text)
{
return addItem(text, -1);
}
//! adds a list item, returns id of item
void CGUIListBox::removeItem(u32 id)
{
if (id >= Items.size())
return;
if ((u32)Selected==id)
{
Selected = -1;
}
else if ((u32)Selected > id)
{
Selected -= 1;
selectTime = os::Timer::getTime();
}
Items.erase(id);
recalculateItemHeight();
}
//! clears the list
void CGUIListBox::clear()
{
Items.clear();
ItemsIconWidth = 0;
Selected = -1;
if (ScrollBar)
ScrollBar->setPos(0);
recalculateItemHeight();
}
void CGUIListBox::recalculateItemHeight()
{
IGUISkin* skin = Environment->getSkin();
if (Font != skin->getFont())
{
if (Font)
Font->drop();
Font = skin->getFont();
if ( 0 == ItemHeightOverride )
ItemHeight = 0;
if (Font)
{
if ( 0 == ItemHeightOverride )
ItemHeight = Font->getDimension(L"A").Height + 4;
Font->grab();
}
}
TotalItemHeight = ItemHeight * Items.size();
ScrollBar->setMax(TotalItemHeight - AbsoluteRect.getHeight());
s32 minItemHeight = ItemHeight > 0 ? ItemHeight : 1;
ScrollBar->setSmallStep ( minItemHeight );
ScrollBar->setLargeStep ( 2*minItemHeight );
if ( TotalItemHeight <= AbsoluteRect.getHeight() )
ScrollBar->setVisible(false);
else
ScrollBar->setVisible(true);
}
//! returns id of selected item. returns -1 if no item is selected.
s32 CGUIListBox::getSelected() const
{
return Selected;
}
//! sets the selected item. Set this to -1 if no item should be selected
void CGUIListBox::setSelected(s32 id)
{
if ((u32)id>=Items.size())
Selected = -1;
else
Selected = id;
selectTime = os::Timer::getTime();
recalculateScrollPos();
}
//! sets the selected item. Set this to -1 if no item should be selected
void CGUIListBox::setSelected(const wchar_t *item)
{
s32 index = -1;
if ( item )
{
for ( index = 0; index < (s32) Items.size(); ++index )
{
if ( Items[index].text == item )
break;
}
}
setSelected ( index );
}
//! called if an event happened.
bool CGUIListBox::OnEvent(const SEvent& event)
{
if (IsEnabled)
{
switch(event.EventType)
{
case EET_KEY_INPUT_EVENT:
if (event.KeyInput.PressedDown &&
(event.KeyInput.Key == KEY_DOWN ||
event.KeyInput.Key == KEY_UP ||
event.KeyInput.Key == KEY_HOME ||
event.KeyInput.Key == KEY_END ||
event.KeyInput.Key == KEY_NEXT ||
event.KeyInput.Key == KEY_PRIOR ) )
{
s32 oldSelected = Selected;
switch (event.KeyInput.Key)
{
case KEY_DOWN:
Selected += 1;
break;
case KEY_UP:
Selected -= 1;
break;
case KEY_HOME:
Selected = 0;
break;
case KEY_END:
Selected = (s32)Items.size()-1;
break;
case KEY_NEXT:
Selected += AbsoluteRect.getHeight() / ItemHeight;
break;
case KEY_PRIOR:
Selected -= AbsoluteRect.getHeight() / ItemHeight;
break;
default:
break;
}
if (Selected >= (s32)Items.size())
Selected = Items.size() - 1;
else
if (Selected<0)
Selected = 0;
recalculateScrollPos();
// post the news
if (oldSelected != Selected && Parent && !Selecting && !MoveOverSelect)
{
SEvent e;
e.EventType = EET_GUI_EVENT;
e.GUIEvent.Caller = this;
e.GUIEvent.Element = 0;
e.GUIEvent.EventType = EGET_LISTBOX_CHANGED;
Parent->OnEvent(e);
}
return true;
}
else
if (!event.KeyInput.PressedDown && ( event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE ) )
{
if (Parent)
{
SEvent e;
e.EventType = EET_GUI_EVENT;
e.GUIEvent.Caller = this;
e.GUIEvent.Element = 0;
e.GUIEvent.EventType = EGET_LISTBOX_SELECTED_AGAIN;
Parent->OnEvent(e);
}
return true;
}
else if (event.KeyInput.PressedDown && event.KeyInput.Char)
{
// change selection based on text as it is typed.
u32 now = os::Timer::getTime();
if (now - LastKeyTime < 500)
{
// add to key buffer if it isn't a key repeat
if (!(KeyBuffer.size() == 1 && KeyBuffer[0] == event.KeyInput.Char))
{
KeyBuffer += L" ";
KeyBuffer[KeyBuffer.size()-1] = event.KeyInput.Char;
}
}
else
{
KeyBuffer = L" ";
KeyBuffer[0] = event.KeyInput.Char;
}
LastKeyTime = now;
// find the selected item, starting at the current selection
s32 start = Selected;
// dont change selection if the key buffer matches the current item
if (Selected > -1 && KeyBuffer.size() > 1)
{
if (Items[Selected].text.size() >= KeyBuffer.size() &&
KeyBuffer.equals_ignore_case(Items[Selected].text.subString(0,KeyBuffer.size())))
return true;
}
s32 current;
for (current = start+1; current < (s32)Items.size(); ++current)
{
if (Items[current].text.size() >= KeyBuffer.size())
{
if (KeyBuffer.equals_ignore_case(Items[current].text.subString(0,KeyBuffer.size())))
{
if (Parent && Selected != current && !Selecting && !MoveOverSelect)
{
SEvent e;
e.EventType = EET_GUI_EVENT;
e.GUIEvent.Caller = this;
e.GUIEvent.Element = 0;
e.GUIEvent.EventType = EGET_LISTBOX_CHANGED;
Parent->OnEvent(e);
}
setSelected(current);
return true;
}
}
}
for (current = 0; current <= start; ++current)
{
if (Items[current].text.size() >= KeyBuffer.size())
{
if (KeyBuffer.equals_ignore_case(Items[current].text.subString(0,KeyBuffer.size())))
{
if (Parent && Selected != current && !Selecting && !MoveOverSelect)
{
Selected = current;
SEvent e;
e.EventType = EET_GUI_EVENT;
e.GUIEvent.Caller = this;
e.GUIEvent.Element = 0;
e.GUIEvent.EventType = EGET_LISTBOX_CHANGED;
Parent->OnEvent(e);
}
setSelected(current);
return true;
}
}
}
return true;
}
break;
case EET_GUI_EVENT:
switch(event.GUIEvent.EventType)
{
case gui::EGET_SCROLL_BAR_CHANGED:
if (event.GUIEvent.Caller == ScrollBar)
return true;
break;
case gui::EGET_ELEMENT_FOCUS_LOST:
{
if (event.GUIEvent.Caller == this)
Selecting = false;
}
default:
break;
}
break;
case EET_MOUSE_INPUT_EVENT:
{
core::position2d<s32> p(event.MouseInput.X, event.MouseInput.Y);
switch(event.MouseInput.Event)
{
case EMIE_MOUSE_WHEEL:
ScrollBar->setPos(ScrollBar->getPos() + (s32)event.MouseInput.Wheel*-ItemHeight/2);
return true;
case EMIE_LMOUSE_PRESSED_DOWN:
{
Selecting = true;
return true;
}
case EMIE_LMOUSE_LEFT_UP:
{
Selecting = false;
if (isPointInside(p))
selectNew(event.MouseInput.Y);
return true;
}
case EMIE_MOUSE_MOVED:
if (Selecting || MoveOverSelect)
{
if (isPointInside(p))
{
selectNew(event.MouseInput.Y, true);
return true;
}
}
default:
break;
}
}
break;
case EET_LOG_TEXT_EVENT:
case EET_USER_EVENT:
case EET_JOYSTICK_INPUT_EVENT:
case EGUIET_FORCE_32_BIT:
break;
}
}
return IGUIElement::OnEvent(event);
}
void CGUIListBox::selectNew(s32 ypos, bool onlyHover)
{
u32 now = os::Timer::getTime();
s32 oldSelected = Selected;
// find new selected item.
if (ItemHeight!=0)
Selected = ((ypos - AbsoluteRect.UpperLeftCorner.Y - 1) + ScrollBar->getPos()) / ItemHeight;
if (Selected<0)
Selected = 0;
else
if ((u32)Selected >= Items.size())
Selected = Items.size() - 1;
recalculateScrollPos();
// post the news
if (Parent && !onlyHover)
{
SEvent event;
event.EventType = EET_GUI_EVENT;
event.GUIEvent.Caller = this;
event.GUIEvent.Element = 0;
event.GUIEvent.EventType = (Selected == oldSelected && now < selectTime + 500) ? EGET_LISTBOX_SELECTED_AGAIN : EGET_LISTBOX_CHANGED;
Parent->OnEvent(event);
}
selectTime = now;
}
//! Update the position and size of the listbox, and update the scrollbar
void CGUIListBox::updateAbsolutePosition()
{
IGUIElement::updateAbsolutePosition();
recalculateItemHeight();
}
//! draws the element and its children
void CGUIListBox::draw()
{
if (!IsVisible)
return;
recalculateItemHeight(); // if the font changed
IGUISkin* skin = Environment->getSkin();
core::rect<s32>* clipRect = 0;
// draw background
core::rect<s32> frameRect(AbsoluteRect);
// draw items
core::rect<s32> clientClip(AbsoluteRect);
clientClip.UpperLeftCorner.Y += 1;
clientClip.UpperLeftCorner.X += 1;
if (ScrollBar->isVisible())
clientClip.LowerRightCorner.X = AbsoluteRect.LowerRightCorner.X - skin->getSize(EGDS_SCROLLBAR_SIZE);
clientClip.LowerRightCorner.Y -= 1;
clientClip.clipAgainst(AbsoluteClippingRect);
skin->draw3DSunkenPane(this, skin->getColor(EGDC_3D_HIGH_LIGHT), true,
DrawBack, frameRect, &clientClip);
if (clipRect)
clientClip.clipAgainst(*clipRect);
frameRect = AbsoluteRect;
frameRect.UpperLeftCorner.X += 1;
if (ScrollBar->isVisible())
frameRect.LowerRightCorner.X = AbsoluteRect.LowerRightCorner.X - skin->getSize(EGDS_SCROLLBAR_SIZE);
frameRect.LowerRightCorner.Y = AbsoluteRect.UpperLeftCorner.Y + ItemHeight;
frameRect.UpperLeftCorner.Y -= ScrollBar->getPos();
frameRect.LowerRightCorner.Y -= ScrollBar->getPos();
bool hl = (HighlightWhenNotFocused || Environment->hasFocus(this) || Environment->hasFocus(ScrollBar));
for (s32 i=0; i<(s32)Items.size(); ++i)
{
if (frameRect.LowerRightCorner.Y >= AbsoluteRect.UpperLeftCorner.Y &&
frameRect.UpperLeftCorner.Y <= AbsoluteRect.LowerRightCorner.Y)
{
if (i == Selected && hl)
skin->draw2DRectangle(this, skin->getColor(EGDC_HIGH_LIGHT), frameRect, &clientClip);
core::rect<s32> textRect = frameRect;
textRect.UpperLeftCorner.X += 3;
if (Font)
{
if (IconBank && (Items[i].icon > -1))
{
core::position2di iconPos = textRect.UpperLeftCorner;
iconPos.Y += textRect.getHeight() / 2;
iconPos.X += ItemsIconWidth/2;
if ( i==Selected && hl )
{
IconBank->draw2DSprite( (u32)Items[i].icon, iconPos, &clientClip,
hasItemOverrideColor(i, EGUI_LBC_ICON_HIGHLIGHT) ?
getItemOverrideColor(i, EGUI_LBC_ICON_HIGHLIGHT) : getItemDefaultColor(EGUI_LBC_ICON_HIGHLIGHT),
selectTime, os::Timer::getTime(), false, true);
}
else
{
IconBank->draw2DSprite( (u32)Items[i].icon, iconPos, &clientClip,
hasItemOverrideColor(i, EGUI_LBC_ICON) ? getItemOverrideColor(i, EGUI_LBC_ICON) : getItemDefaultColor(EGUI_LBC_ICON),
0 , (i==Selected) ? os::Timer::getTime() : 0, false, true);
}
}
|
paupawsan/Irrlicht
|
b76e12a90cbc0b8596432982c306b23f70cee09a
|
Fix octree with frustum+parent checks enabled (didn't clip at all before). Now using plane-checks instead of edge-checks for frustum-box intersection.
|
diff --git a/changes.txt b/changes.txt
index f3ca961..afae1f5 100644
--- a/changes.txt
+++ b/changes.txt
@@ -1,514 +1,516 @@
-----------------------------
Changes in 1.7.1 (17.02.2010)
+
+ - Fix octree with frustum+parent checks enabled (didn't clip at all before). Now using plane-checks instead of edge-checks for frustum-box intersection.
- Prevent that X11 selects larger resolutions in fullscreen even when perfect fits are available.
- Ignore setResizable also on X11 when we're fullscreen to avoid messing up the window mode.
- Work around a crash when pressing ESC after closing a Messagebox (found by Acki)
- Prevent borland compile warnings in SColorHSL::FromRGB and in SVertexColorThresholdManipulator (found by mdeininger)
- Improve Windows version detection rules (Patch from brferreira)
- Make it compile on Borland compilers (thx to mdeininger)
- Make sure that CAnimatedMeshSceneNode::clone calls the virtual updateAbsolutePosition for the new object
- Fix that clones got dropped too often when SceneNodes without parent got cloned (found by Ulf)
- Make sure TAB is still recognized on X11 when shift+tab is pressed. This does also fix going to the previous tabstop on X11.
- Send EGET_ELEMENT_LEFT also when there won't be a new hovered element
- Update docs for EGET_ELEMENT_LEFT and EGET_ELEMENT_HOVERED
- Fix tooltips: Remove them when the element is hidden or removed (thx to seven for finding)
- Fix tooltips: Make (more) sure they don't get confused by gui-subelements
- Fix tooltips: Get faster relaunch times working
- Fix tooltips: Make sure hovered element is never the tooltip itself
- Fix string::remove which got in an endless loop when remove was called with an empty string (found and fixed by Ulf)
- Correctly release the GLSL shaders
- Make sure we only release an X11 atom when it was actually created
- Fix aabbox collision test, which not only broke the collision test routines, but also frustum culling, octree tests, etc.
- Fix compilation problem under OSX due to wrong glProgramParameteri usage
- mem leak in OBJ loader fixed
- Removed some default parameters to reduce ambigious situations
---------------------------
Changes in 1.7 (03.02.2010)
- Implement minimize and deminimize under OSX.
- Define sorting order for vector2d and vector3d in operators <, <=, > and >= to fix bugs 2783509 and 2783510. Operators order now by X,Y,Z and use float tolerances.
- Ogre mesh 32bit indices fixed.
- Fix tooltips for gui-elements with sub-element like IGUISpinBox (id: 2927079, found by ArakisTheKitsune)
- ITimer no longer stops when started twice
- wchar_t filesystem updates under Windows.
- Joystick POV fixed under Windows, ids fixed under OSX.
- Some updates to skinned mesh for better bones support and scaling animations.
- OSX supports external window id in creation parameters now.
- Fix bbox collision tests.
- Updates for win32 key handling
- new convenience method for flat plane creation.
- Sky dome and other meshes use VBOs by default now.
- Speed up b3d loading for files with many frames, material color flags and vertex color support enhanced.
- Add hasType to IGUIElement as a dynamic_cast substitute.
- Add another parameter to IGUISkin::draw3DWindowBackground to allow getting the client area without actually drawing
- Add function getClientRect to IGUIWindow for getting the draw-able area
- Fix bug that menus on IGUIWindows with titlebar got drawn too high (id: 2714400)
- Renamed OctTree to Octree
- Allow getting a ConstIterator from a non-const core:list
- Add swap functions to irrMath and to the core classes.
- Deprecate map::isEmpty() and replace it with map::empty() to make it similar to other base classes.
- Allow to set the logging level already in SIrrlichtCreationParameters.
- Add clearSystemMessages to devices (implemented only for Linux and Win32 so far).
- Support changing the render window from beginScene also with OpenGL driver.
- Add getMaterial2D which allows to alter the 2d render state settings, such as filtering, anti-aliasing, thickness, etc.
- Fix incorrect cursorpos for resizable windows on Windows Vista (found and patched by buffer)
- Change the beginScene window parameter from void* to SExposedVideoData&. This will allow to manage contexts for OpenGL at some point.
- Add bzip2 and LZMA decompression modes for zip loader.
- Add OBJ_TEXTURE_PATH and B3D_TEXTURE_PATH to SceneParameters to allow setting texture-paths for obj and b3d.
- Irrlicht keeps now filenames additionally to the internally used names, thereby fixing some problems with uppercase-filenames on Linux.
- Bugfix: Mousewheel no longer sends EMIE_MOUSE_WHEEL messages twice on Linux.
- Use latest jpeglib
- refactoring: E_ATTRIBUTE_TYPE and IAttribute have now own headers
- CStringWArrayAttribute speedup
- SceneNodeAnimatorFollowSpline can now loop and pingpong
- Meshviewer.example got some fast-scale buttons.
- Support AES-encrypted zip files. Should work with 128, 196, and 256 bit AES. This addition also adds a new PRNG, SHA, and other algorithms to the engine, though no interface is yet added for them. The implementation of the encryption algorithms is provided by Dr Brian Gladman.
- flattenFilename and getAbsolutePath fixed and properly added at several places.
- Added geometry shaders for OpenGL. A first version of the code was submitted by Matthew Kielan (devsh).
- Bugfix: irrArray should no longer crash when using other allocators.
- Add MaterialViewer example.
- Texture activation now back in setMaterial, which simplifies writing external material renderers (OpenGL only).
- Checkbox uses now disabled text color when disabled.
- Changed colors for window-title caption to keep them readable when not active.
- Draw sub-menus to left side if they would be outside main-window otherwise.
- Give ListBox better defaults for the ScrollBar stepsizes.
- Double and triple click events now for each mouse-button. Old events for that got removed.
- Fix adding archives twice, which caused multiple archives of the same name and type covering each other. This one required a texture name change from using backslashes to slashes under Windows.
- Give access to texture mipmaps. You can provide custom mipmap textures upon generation, regeneration, and locking.
Make sure the provided data is large enough and covers all miplevels. Also the returned pointer (from lock) will only cover the smaller data of the mipmap level dimension chosen (level 0 is the original texture).
- Separate TextureWrap mode into U and V fields
- Add mirror texture wrap modes
- windows show now active/inactive state
- remove unneeded drop/grab calls found by manik_sheeri
- fix rounding problem in IGUIElements which have EGUIA_SCALE alignments.
- MessageBox supports now automatic resizing and images.
Deprecated EGDS_MESSAGE_BOX_WIDTH and EGDS_MESSAGE_BOX_HEIGHT
- Let maya-cam animator react on a setTarget call to the camera which happened outside it's own control
- New contextmenue features:
automatic checking for checked flag.
close handling now customizable
serialization can handle incomplete xml's
setEventParent now in public interface
New function findItemWithCommandId
New function insertItem
- new vector3d::getSphericalCoordinateAngles method.
- new triangle3d::isTotalOutsideBox method.
- Newly introduced VertexManipulator interface. This allows for very easy creation of vertex manipulation algorithms. Several manipulators, e.g. vertex color changer and transformation algorithms are already available.
- createMeshWith1TCoords avoids vertex duplication
- getRotation now handles matrices with scaling as well
- Ogre format animations now supported.
- irrArray: Fixed issues with push_front and reallocation
Changed behavior for set_pointer and clear, when free_when_destroyed is false
- NPK (Nebula device archive) reader added, it's an uncompressed PAK-like format
- SSkinMeshBuffer::MoveTo* methods renamed to convertTo*
- Multiple Render Target (MRT) support added, including some enhanced blend features where supported
- Directory changing fixed for virtual file systems (Archives etc)
- Fix texture matrix init in scene manager and driver
- More draw2dimage support in software drivers
- Sphere node now properly chooses a good tesselation based on the parameters
- Active camera not registered twice anymore
- Parallax/normal map shader rotation bug under OpenGL fixed
- bump map handling for obj files fixed
- Fog serialization added
- New context menu features added
- Bounding Box updates for skinned meshes fixed
- The current FPS for an animated scene node can be queried now, added some variables to serialization
- Scrollbars fixed
- Fixed 2d vertex primitive method to correctly handle transparency
- Fullscreen handling has been enhanced for Windows, now proper resolution is restored on Alt-Tab etc.
- Cameras can now be added to the scene node without automatically activating them
Clone method added
- New video driver method getMaxTextureSize
- PAK archive reader fixed
- TRANSPARENT_ALPHA_CHANNEL_REF uses modulate to enable lighting
- LIGHTMAP_ADD now always uses add operator
- Some Unicode file system fixes
- destructor of irrString not virtual anymore, please don't derive from irrString
Some new methods added, for searching and splitting
Assignment operator optimized
- new lightness method for SColor
- draw3DTriangle now renders filled polygons, old behavior can be achieved by setting EMT_WIREFRAME
-----------------------------
Changes in 1.6.1 (13.01.2010)
- Fix pingpong for CSceneNodeAnimatorFlyStraight (found by gbox)
- Fix bug with IGUIEditBox where the cursor position is reset on text change.
- Make sure the window top-left corner on Windows is not negative on start so that Windows sytem-menu is always visible.
- Fix problem that the window did sometimes not get the keyboard focus in X11 in fullscreen. Add more debug output in case focus grabbing goes wrong.
- Fix screensize in videodriver when we didn't get the requested window size. This also prevents that gui-clicks are no longer synchronized with gui-drawing and elements can't be hit anymore.
- Bugfix: Prevent a crash when getTypeName was called for the guienvironment. EGUIET_ELEMENT got changed for this.
- Bugfix: Horizontal centered font with linebreaks draw now all lines. For example multiline TextSceneNodes work again.
- Bugfix: spinbox can no longer get in an endless loop due to floating point rounding error (found by slavik262)
- !!API change!! Disabled AntiAliasing of Lines in material default
Please enable this manually per material when sure that it won't lead to SW rendering.
- IGUIComboBox: clicking on the statictext displaying the active selection does now close and open listbox correctly. (Bug found by Reiko)
- Scrollbuttons in IGUITabControl adapt now to tab-height.
- Fix texturing of cylinder mesh
- Fix modal dialog position (found by LoneBoco: http://sourceforge.net/tracker/?func=detail&aid=2900266&group_id=74339&atid=540676)
- Fix DMF loading
- Fixing left+right special keys (ctrl, shift, alt) on Win32 (thanks to pc0de for good patch-ideas).
- Make stringarrays for enums in IGUISkin a little safer
- Add support for keys KEY_PRINT, KEY_HOME (on numpad) and KEY_NUMLOCK on Linux.
- Fix material handling in createMeshWith1TCoords
- Fix another (OldValue == NewValue) before drop()/grap(), this time in CTextureAttribute::setTexture.
- Fix LIGHTMAP_LIGHTING for D3D drivers.
- AntiAliasing disabled for debug render elements.
- Bugfix: CGUIToolBar::addButton does no longer mess up when no image is set and does now actually work with the text.
- Fix ninja animation range which got messed up a little when b3d animations got fixed (thx gbox for finding)
---------------------------
Changes in 1.6 (23.09.2009)
- Added IFileSystem::createEmptyFileList, exposed IFileList::sort, addItem and added getID
- Fix MAKE_IRR_ID so it can be used from outside the irr namespace (Micha's patch)
- Renamed some methods in ISkinnedMesh to match the official Irrlicht naming scheme according to createXXX()
- Change debug data to draw using lines instead of arrows, which is much faster. Patch by pc0de
- Fix a bug with FPS camera animator causing stutters. Patch by FuzzYspo0N
- Fix scrolling controls in CGUITabControl
- Fix a bug when getting optimal texture size in D3D drivers, by Jetro Lauha (tonic)
- Added EGDS_TITLEBARTEXT_DISTANCE_X and EGDS_TITLEBARTEXT_DISTANCE_Y to GUI, submitted by FuzzYspo0N
- Fix for UFT8 filenames displayed in file dialog, patch by MadHyde.
- Added const method for array::binary_search, potentially slow as it doesn't sort the list!
- Add support for scaling button images.
- Irrlicht can now come with multiple device types compiled in, the device to use is selected by SIrrlichtCreationParameters.DeviceType. This defaults to EIDT_BEST which automatically select the best device available starting with native, then X11, SDL and finally the console.
- Added support for EXP2 fog distribution. This required a change in the setFog parameters where now an enum value instead of the bool linear is given.
- IFileSystem changes:
- Renamed the following functions-
IFileArchive::getArchiveType to getType
IFileSystem::registerFileArchive to addFileArchive
IFileSystem::unregisterFileArchive to removeFileArchive
IFileArchive::openFile to createAndOpenFile
- New enum, E_FILE_ARCHIVE_TYPE. getType on IArchiveLoader and IFileArchive now both return this.
- IFileSystem::addFileArchive takes a parameter to specify the archive type rather always using the file extension. IFileSystem::addZipFileArchive, addFolderFileArchive and addPakFileArchive now use this but these functions are now marked as deprecated. Users should now use addFileArchive instead.
- Added TAR archive loader.
- The ZIP archive loader can now load gzip files, combined with the TAR loader this means Irrlicht now has native support for .tar.gz
Currently this must be done in two calls, for example:
fileSystem->addFileArchive("path/to/myArchive.tar.gz");
fileSystem->addFileArchive("myArchive.tar");
- Fix highlighting in IGUIEditBox where kerning pairs are used in the font. For example in future italic, OS or other custom fonts.
- IOSOperator::getTextFromClipboard returns now const c8* instead of c8*
- Support for copy&paste on linux (X11) added (fixing bug 2804014 found by Pan)
- bugfix for 2795321 found by egrath: Don't rely anymore on broken XkbSetDetectableAutoRepeat.
- bugfix: CMountPointReader::openFile no longer returns true for empty files. Corresponding test added.
- Direct3D now also uses screen coordinates in 2d mode, just like OpenGL. This means that screen coords are going from 0..ScreenWidth and 0..ScreenHeight instead of -1..1.
- ALT+F4 keypress now closes Windows SDL device
- Allow Direct3D drivers in SDL, patch by Halifax
- Added compiler error when attempting to compile with VC6.
- Use setWindowTextA in Windows device for WIN64 platform, posted by veegun
- ELL_ERROR log events are now created when shaders fail to compile or link, reported by Halan
- irrList now uses irrAllocator, fixed by Nox
- Added IGUIWindow::setDraggable and IGUIWindow::isDraggable, by Nox
- Added SGI RGB file reader by Gary Conway, for loading Silicon Graphics .rgb, .rgba, .sgi, .int and .inta textures
- Renamed setResizeAble to setResizable
- Added new device method minimizeWindow which minimizes the window (just as if the minimize button has been clicked).
- SkyDome is now serialized correctly
- Added PLY mesh reader and writer
- Ensure ListBox on combo box doesn't hang off the bottom of the GUI root, by Matthias Specht
- Made IGUIElements recalculate clipping rectangle after setNotClipped, reported by Aelis440
- Bug fix for the combo box where it showed white text instead of skin colour before being focused, fix posted by drewbacca
- EGDS_MESSAGE_BOX_HEIGHT is now honoured, bug reported by Spkka
- Fixed a bug in the edit box where events are sometimes sent to a null parent, reported by Sudi.
- Coordinate system fix for OpenGL in SDL device
- Added generic console device. You can now use Irrlicht to create and manipuate graphics on a shell where no graphics hardware
or windowing system is available. To enable it uncomment #define _IRR_USE_CONSOLE_DEVICE_ in IrrCompileConfig.h
- The console device can now present images from the software drivers and display them as ASCII art in the console
- By default it replaces the default font in the skin, to prevent fonts from being huge.
- Fixed problems with changing cursor visibility while mouse is pressed on windows
- Allow control of background drawing in listbox
- Allow control of drawing background and titlebar in windows
- Improved window serialization
- Add mouse events EMIE_MOUSE_DOUBLE_CLICK and EMIE_MOUSE_TRIPLE_CLICK (thx to Ulf for patch proposal)
- Set "ButtonStates" for mouse events also on Linux (was only for Windows formerly)
- Add Shift+Control states to mouse event
- bugfix (2003238): serialize modal screens
- allow stacking modal screens
- allowing hiding modals
- replace many IsVisible checks with virtual isVisible() checks in IGUIElement
- bugfix: reset selected row when clearing CGUITable
- adding events EGET_EDITBOX_CHANGED and EGET_EDITBOX_MARKING_CHANGED
- prevent editbox from recalculating its textbreaking each frame
- let spinbox react on each textchange without waiting for enter to prevent getting value changes without corresponding EGET_SPINBOX_CHANGED events.
- new test for zipreader
- prevent dropping objects accidentally in many set functions
- Reversed change in vector3d::normalize.
Works now again as documented and a corresponding test has been added.
Does fix bug 2770709 (https://sourceforge.net/tracker/?func=detail&aid=2770709&group_id=74339&atid=540676)
- Animations can now be paused by setting the fps to 0.
- Avoid fp-precision problem in getPickedNodeBB (see also http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=33838&highlight=).
This change might also fix the problem with picking nodes found by aanderse (http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=32890&highlight=)
- implemented isALoadableFileFormat ( File *file ) for the Archive Loader
- PixelBlend16 and PixelBlend16_simd are working for the new rules.
- bugfix. CLightSceneNode didn't correctly update it's attributes
- vector template and equals tests
also set the equal test for s32 to behave like the f32 routine.
The function equals always implements a weak test.
that means a tolerance MUST always be used if you use the equal function. default is 1.
- VideoDriver drawPixel
The HW renderes are using the alpha components for blending.
The Software Renderes and image loaders are using CImage::setPixel copy.
so setPixel is engaged to either blends or copy the pixel
default: false
- Burningvideo
added RenderMaterial EMT_SPHERE_MAP
pushed burningsvideo to 0.43
added RenderMaterial EMT_REFLECTION_2_LAYER
pushed burningsvideo to 0.44
set EMT_TRANSPARENT_ALPHA_CHANNEL_REF
to use AlphaRef 0.5 like Direct3D
One Note: in OpenGL there is know difference between sphere_map and reflection layer
both using GL_TEXTURE_GEN_MODE GL_SPHERE_MAP, whereas in d3d one time using camera_normal
on sphere and reflection on refletcion_layer.
The visual difference is that on sphere map the "image is not moving" when you rotate the
viewer. For Burning i took the opengl visual. always moving
- rename quake3 SEntity to IEntity to be confom with IShader
- fixed createMeshWith2TCoords, normals were missing during copy.
- added
//! Creates a copy of the mesh, which will only consist of S3DVertex vertices.
IMesh* CMeshManipulator::createMeshWith1TCoords(IMesh* mesh) const
- added io::IFileSystem* CSceneManager::getFileSystem()
- added virtual const c8* ISceneManager::getAnimatorTypeName(ESCENE_NODE_ANIMATOR_TYPE type);
- added CSceneNodeAnimatorFlyCircle::radiusEllipsoid.
if radiusEllipsoid == 0 the default circle animation is done
else radiusEllipsoid forms the b-axe of the ellipsoid.
-> gummiball bouncing
- added ISceneManager::createFlyStraightAnimator variable bool ping-pong
used in loop mode to device if start from beginning ( default ) or make ping-pong
-> straight bouncing
- changed IFileSystem::registerFileArchive
remove the index of the hierarchy and added a new interface method
//! move the hirarchy of the filesystem. moves sourceIndex relative up or down
virtual bool moveFileArchive( u32 sourceIndex, s32 relative ) = 0;
- bugfix and changes in SViewFrustum::SViewFrustum
wrong size of Matrices copy.
renamed E_TRANSFORMATION_STATE_2 to E_TRANSFORMATION_STATE_FRUSTUM
therefore also changed SViewFrustum::setTransformState to not tap
in the pitfall again of wrong memory...
- moved
//! EMT_ONETEXTURE_BLEND: has BlendFactor Alphablending
inline bool textureBlendFunc_hasAlpha ( E_BLEND_FACTOR factor ) const
from the material renderes ( 3x declared ) to SMaterial.h
- updated managed light example to use standard driver selection
- BurningsVideo
- LightModel reworked.
Point Light & Direction Light works for Diffuse Color as expected
Specular and Fog still have problems ( needs new pixel shader )
pushed burningsvideo to 0.42 for this major step
- removed obsolete matrix transformations
diff --git a/source/Irrlicht/Octree.h b/source/Irrlicht/Octree.h
index df8d8f0..a22cf32 100644
--- a/source/Irrlicht/Octree.h
+++ b/source/Irrlicht/Octree.h
@@ -1,400 +1,388 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_OCTREE_H_INCLUDED__
#define __C_OCTREE_H_INCLUDED__
#include "SViewFrustum.h"
#include "S3DVertex.h"
#include "aabbox3d.h"
#include "irrArray.h"
#include "CMeshBuffer.h"
/**
Flags for Octree
*/
//! use meshbuffer for drawing, enables VBO usage
#define OCTREE_USE_HARDWARE false
//! use visibility information together with VBOs
#define OCTREE_USE_VISIBILITY true
//! use bounding box or frustum for calculate polys
#define OCTREE_BOX_BASED true
//! bypass full invisible/visible test
#define OCTREE_PARENTTEST
namespace irr
{
//! template octree.
/** T must be a vertex type which has a member
called .Pos, which is a core::vertex3df position. */
template <class T>
class Octree
{
public:
struct SMeshChunk : public scene::CMeshBuffer<T>
{
SMeshChunk ()
: scene::CMeshBuffer<T>(), MaterialId(0)
{
scene::CMeshBuffer<T>::grab();
}
virtual ~SMeshChunk ()
{
//removeAllHardwareBuffers
}
s32 MaterialId;
};
struct SIndexChunk
{
core::array<u16> Indices;
s32 MaterialId;
};
struct SIndexData
{
u16* Indices;
s32 CurrentSize;
s32 MaxSize;
};
//! Constructor
Octree(const core::array<SMeshChunk>& meshes, s32 minimalPolysPerNode=128) :
IndexData(0), IndexDataCount(meshes.size()), NodeCount(0)
{
IndexData = new SIndexData[IndexDataCount];
// construct array of all indices
core::array<SIndexChunk>* indexChunks = new core::array<SIndexChunk>;
indexChunks->reallocate(meshes.size());
for (u32 i=0; i!=meshes.size(); ++i)
{
IndexData[i].CurrentSize = 0;
IndexData[i].MaxSize = meshes[i].Indices.size();
IndexData[i].Indices = new u16[IndexData[i].MaxSize];
indexChunks->push_back(SIndexChunk());
SIndexChunk& tic = indexChunks->getLast();
tic.MaterialId = meshes[i].MaterialId;
tic.Indices = meshes[i].Indices;
}
// create tree
Root = new OctreeNode(NodeCount, 0, meshes, indexChunks, minimalPolysPerNode);
}
//! returns all ids of polygons partially or fully enclosed
//! by this bounding box.
void calculatePolys(const core::aabbox3d<f32>& box)
{
for (u32 i=0; i!=IndexDataCount; ++i)
IndexData[i].CurrentSize = 0;
Root->getPolys(box, IndexData, 0);
}
//! returns all ids of polygons partially or fully enclosed
//! by a view frustum.
void calculatePolys(const scene::SViewFrustum& frustum)
{
for (u32 i=0; i!=IndexDataCount; ++i)
IndexData[i].CurrentSize = 0;
Root->getPolys(frustum, IndexData, 0);
}
const SIndexData* getIndexData() const
{
return IndexData;
}
u32 getIndexDataCount() const
{
return IndexDataCount;
}
u32 getNodeCount() const
{
return NodeCount;
}
//! for debug purposes only, collects the bounding boxes of the tree
void getBoundingBoxes(const core::aabbox3d<f32>& box,
core::array< const core::aabbox3d<f32>* >&outBoxes) const
{
Root->getBoundingBoxes(box, outBoxes);
}
//! destructor
~Octree()
{
for (u32 i=0; i<IndexDataCount; ++i)
delete [] IndexData[i].Indices;
delete [] IndexData;
delete Root;
}
private:
// private inner class
class OctreeNode
{
public:
// constructor
OctreeNode(u32& nodeCount, u32 currentdepth,
const core::array<SMeshChunk>& allmeshdata,
core::array<SIndexChunk>* indices,
s32 minimalPolysPerNode) : IndexData(0),
Depth(currentdepth+1)
{
++nodeCount;
u32 i; // new ISO for scoping problem with different compilers
for (i=0; i!=8; ++i)
Children[i] = 0;
if (indices->empty())
{
delete indices;
return;
}
bool found = false;
// find first point for bounding box
for (i=0; i<indices->size(); ++i)
{
if (!(*indices)[i].Indices.empty())
{
Box.reset(allmeshdata[i].Vertices[(*indices)[i].Indices[0]].Pos);
found = true;
break;
}
}
if (!found)
{
delete indices;
return;
}
s32 totalPrimitives = 0;
// now lets calculate our bounding box
for (i=0; i<indices->size(); ++i)
{
totalPrimitives += (*indices)[i].Indices.size();
for (u32 j=0; j<(*indices)[i].Indices.size(); ++j)
Box.addInternalPoint(allmeshdata[i].Vertices[(*indices)[i].Indices[j]].Pos);
}
core::vector3df middle = Box.getCenter();
core::vector3df edges[8];
Box.getEdges(edges);
// calculate all children
core::aabbox3d<f32> box;
core::array<u16> keepIndices;
if (totalPrimitives > minimalPolysPerNode && !Box.isEmpty())
for (u32 ch=0; ch!=8; ++ch)
{
box.reset(middle);
box.addInternalPoint(edges[ch]);
// create indices for child
bool added = false;
core::array<SIndexChunk>* cindexChunks = new core::array<SIndexChunk>;
cindexChunks->reallocate(allmeshdata.size());
for (i=0; i<allmeshdata.size(); ++i)
{
cindexChunks->push_back(SIndexChunk());
SIndexChunk& tic = cindexChunks->getLast();
tic.MaterialId = allmeshdata[i].MaterialId;
for (u32 t=0; t<(*indices)[i].Indices.size(); t+=3)
{
if (box.isPointInside(allmeshdata[i].Vertices[(*indices)[i].Indices[t]].Pos) &&
box.isPointInside(allmeshdata[i].Vertices[(*indices)[i].Indices[t+1]].Pos) &&
box.isPointInside(allmeshdata[i].Vertices[(*indices)[i].Indices[t+2]].Pos))
{
tic.Indices.push_back((*indices)[i].Indices[t]);
tic.Indices.push_back((*indices)[i].Indices[t+1]);
tic.Indices.push_back((*indices)[i].Indices[t+2]);
added = true;
}
else
{
keepIndices.push_back((*indices)[i].Indices[t]);
keepIndices.push_back((*indices)[i].Indices[t+1]);
keepIndices.push_back((*indices)[i].Indices[t+2]);
}
}
memcpy( (*indices)[i].Indices.pointer(), keepIndices.pointer(), keepIndices.size()*sizeof(u16));
(*indices)[i].Indices.set_used(keepIndices.size());
keepIndices.set_used(0);
}
if (added)
Children[ch] = new OctreeNode(nodeCount, Depth,
allmeshdata, cindexChunks, minimalPolysPerNode);
else
delete cindexChunks;
} // end for all possible children
IndexData = indices;
}
// destructor
~OctreeNode()
{
delete IndexData;
for (u32 i=0; i<8; ++i)
delete Children[i];
}
// returns all ids of polygons partially or full enclosed
// by this bounding box.
void getPolys(const core::aabbox3d<f32>& box, SIndexData* idxdata, u32 parentTest ) const
{
#if defined (OCTREE_PARENTTEST )
// if not full inside
if ( parentTest != 2 )
{
// partially inside ?
if (!Box.intersectsWithBox(box))
return;
// fully inside ?
parentTest = Box.isFullInside(box)?2:1;
}
#else
if (Box.intersectsWithBox(box))
#endif
{
const u32 cnt = IndexData->size();
u32 i; // new ISO for scoping problem in some compilers
for (i=0; i<cnt; ++i)
{
const s32 idxcnt = (*IndexData)[i].Indices.size();
if (idxcnt)
{
memcpy(&idxdata[i].Indices[idxdata[i].CurrentSize],
&(*IndexData)[i].Indices[0], idxcnt * sizeof(s16));
idxdata[i].CurrentSize += idxcnt;
}
}
for (i=0; i!=8; ++i)
if (Children[i])
Children[i]->getPolys(box, idxdata,parentTest);
}
}
// returns all ids of polygons partially or full enclosed
// by the view frustum.
void getPolys(const scene::SViewFrustum& frustum, SIndexData* idxdata,u32 parentTest) const
{
u32 i; // new ISO for scoping problem in some compilers
// if parent is fully inside, no further check for the children is needed
#if defined (OCTREE_PARENTTEST )
if ( parentTest != 2 )
#endif
{
- core::vector3df edges[8];
- Box.getEdges(edges);
-
+#if defined (OCTREE_PARENTTEST )
+ parentTest = 2;
+#endif
for (i=0; i!=scene::SViewFrustum::VF_PLANE_COUNT; ++i)
{
- u32 boxInFrustum=0;
-
- for (u32 j=0; j!=8; ++j)
- {
- if (frustum.planes[i].classifyPointRelation(edges[j]) != core::ISREL3D_FRONT)
- {
- boxInFrustum += 1;
-#if !defined (OCTREE_PARENTTEST )
- break;
-#endif
- }
- }
-
- if ( 0 == boxInFrustum) // all edges outside
+ core::EIntersectionRelation3D r = Box.classifyPlaneRelation(frustum.planes[i]);
+ if ( r == core::ISREL3D_FRONT )
return;
-
#if defined (OCTREE_PARENTTEST )
- if ( 8 == boxInFrustum) // all edges in, all children in
- parentTest = 2;
+ if ( r == core::ISREL3D_CLIPPED )
+ parentTest = 1; // must still check childs
#endif
}
}
+
const u32 cnt = IndexData->size();
for (i=0; i!=cnt; ++i)
{
s32 idxcnt = (*IndexData)[i].Indices.size();
if (idxcnt)
{
memcpy(&idxdata[i].Indices[idxdata[i].CurrentSize],
&(*IndexData)[i].Indices[0], idxcnt * sizeof(s16));
idxdata[i].CurrentSize += idxcnt;
}
}
for (i=0; i!=8; ++i)
if (Children[i])
Children[i]->getPolys(frustum, idxdata,parentTest);
}
//! for debug purposes only, collects the bounding boxes of the node
void getBoundingBoxes(const core::aabbox3d<f32>& box,
core::array< const core::aabbox3d<f32>* >&outBoxes) const
{
if (Box.intersectsWithBox(box))
{
outBoxes.push_back(&Box);
for (u32 i=0; i!=8; ++i)
if (Children[i])
Children[i]->getBoundingBoxes(box, outBoxes);
}
}
private:
core::aabbox3df Box;
core::array<SIndexChunk>* IndexData;
OctreeNode* Children[8];
u32 Depth;
};
OctreeNode* Root;
SIndexData* IndexData;
u32 IndexDataCount;
u32 NodeCount;
};
} // end namespace
#endif
|
paupawsan/Irrlicht
|
9363bb91a0533c2ffb2e3824b6f369613bba2ca8
|
Make sure Irrlicht still compiles when __IRR_COMPILE_WITH_ZIP_ARCHIVE_LOADER_ is outcommented.
|
diff --git a/source/Irrlicht/CZipReader.cpp b/source/Irrlicht/CZipReader.cpp
index 7895d74..27a1dcb 100644
--- a/source/Irrlicht/CZipReader.cpp
+++ b/source/Irrlicht/CZipReader.cpp
@@ -1,556 +1,555 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CZipReader.h"
+#include "os.h"
+
+// This method is used for error output from bzip2.
+extern "C" void bz_internal_error(int errorCode)
+{
+ irr::os::Printer::log("Error in bzip2 handling", irr::core::stringc(errorCode), irr::ELL_ERROR);
+}
+
#ifdef __IRR_COMPILE_WITH_ZIP_ARCHIVE_LOADER_
#include "CFileList.h"
#include "CReadFile.h"
-#include "os.h"
#include "coreutil.h"
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_ZLIB_
#ifndef _IRR_USE_NON_SYSTEM_ZLIB_
#include <zlib.h> // use system lib
#else
#include "zlib/zlib.h"
#endif
#ifdef _IRR_COMPILE_WITH_ZIP_ENCRYPTION_
#include "aesGladman/fileenc.h"
#endif
#ifdef _IRR_COMPILE_WITH_BZIP2_
#ifndef _IRR_USE_NON_SYSTEM_BZLIB_
#include <bzlib.h>
#else
#include "bzip2/bzlib.h"
#endif
#endif
#ifdef _IRR_COMPILE_WITH_LZMA_
#include "lzma/LzmaDec.h"
#endif
#endif
-#ifdef BZ_NO_STDIO
-// This method is used for error output from bzip2.
-extern "C" void bz_internal_error(int errorCode)
-{
- irr::os::Printer::log("Error in bzip2 handling", irr::core::stringc(errorCode), irr::ELL_ERROR);
-}
-#endif
-
namespace irr
{
namespace io
{
// -----------------------------------------------------------------------------
// zip loader
// -----------------------------------------------------------------------------
//! Constructor
CArchiveLoaderZIP::CArchiveLoaderZIP(io::IFileSystem* fs)
: FileSystem(fs)
{
#ifdef _DEBUG
setDebugName("CArchiveLoaderZIP");
#endif
}
//! returns true if the file maybe is able to be loaded by this class
bool CArchiveLoaderZIP::isALoadableFileFormat(const io::path& filename) const
{
return core::hasFileExtension(filename, "zip", "pk3") ||
core::hasFileExtension(filename, "gz", "tgz");
}
//! Check to see if the loader can create archives of this type.
bool CArchiveLoaderZIP::isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) const
{
return (fileType == EFAT_ZIP || fileType == EFAT_GZIP);
}
//! Creates an archive from the filename
/** \param file File handle to check.
\return Pointer to newly created archive, or 0 upon error. */
IFileArchive* CArchiveLoaderZIP::createArchive(const io::path& filename, bool ignoreCase, bool ignorePaths) const
{
IFileArchive *archive = 0;
io::IReadFile* file = FileSystem->createAndOpenFile(filename);
if (file)
{
archive = createArchive(file, ignoreCase, ignorePaths);
file->drop();
}
return archive;
}
//! creates/loads an archive from the file.
//! \return Pointer to the created archive. Returns 0 if loading failed.
IFileArchive* CArchiveLoaderZIP::createArchive(io::IReadFile* file, bool ignoreCase, bool ignorePaths) const
{
IFileArchive *archive = 0;
if (file)
{
file->seek(0);
u16 sig;
file->read(&sig, 2);
#ifdef __BIG_ENDIAN__
os::Byteswap::byteswap(sig);
#endif
file->seek(0);
bool isGZip = (sig == 0x8b1f);
archive = new CZipReader(file, ignoreCase, ignorePaths, isGZip);
}
return archive;
}
//! Check if the file might be loaded by this class
/** Check might look into the file.
\param file File handle to check.
\return True if file seems to be loadable. */
bool CArchiveLoaderZIP::isALoadableFileFormat(io::IReadFile* file) const
{
SZIPFileHeader header;
file->read( &header.Sig, 4 );
#ifdef __BIG_ENDIAN__
os::Byteswap::byteswap(header.Sig);
#endif
return header.Sig == 0x04034b50 || // ZIP
(header.Sig&0xffff) == 0x8b1f; // gzip
}
// -----------------------------------------------------------------------------
// zip archive
// -----------------------------------------------------------------------------
CZipReader::CZipReader(IReadFile* file, bool ignoreCase, bool ignorePaths, bool isGZip)
: CFileList((file ? file->getFileName() : io::path("")), ignoreCase, ignorePaths), File(file), IsGZip(isGZip)
{
#ifdef _DEBUG
setDebugName("CZipReader");
#endif
if (File)
{
File->grab();
// load file entries
if (IsGZip)
while (scanGZipHeader()) { }
else
while (scanZipHeader()) { }
sort();
}
}
CZipReader::~CZipReader()
{
if (File)
File->drop();
}
//! get the archive type
E_FILE_ARCHIVE_TYPE CZipReader::getType() const
{
return IsGZip ? EFAT_GZIP : EFAT_ZIP;
}
const IFileList* CZipReader::getFileList() const
{
return this;
}
#if 0
#include <windows.h>
const c8 *sigName( u32 sig )
{
switch ( sig )
{
case 0x04034b50: return "PK0304";
case 0x02014b50: return "PK0102";
case 0x06054b50: return "PK0506";
}
return "unknown";
}
bool CZipReader::scanLocalHeader2()
{
c8 buf [ 128 ];
c8 *c;
File->read( &temp.header.Sig, 4 );
#ifdef __BIG_ENDIAN__
os::Byteswap::byteswap(temp.header.Sig);
#endif
sprintf ( buf, "sig: %08x,%s,", temp.header.Sig, sigName ( temp.header.Sig ) );
OutputDebugStringA ( buf );
// Local File Header
if ( temp.header.Sig == 0x04034b50 )
{
File->read( &temp.header.VersionToExtract, sizeof( temp.header ) - 4 );
temp.zipFileName.reserve( temp.header.FilenameLength+2);
c = (c8*) temp.zipFileName.c_str();
File->read( c, temp.header.FilenameLength);
c [ temp.header.FilenameLength ] = 0;
temp.zipFileName.verify();
sprintf ( buf, "%d,'%s'\n", temp.header.CompressionMethod, c );
OutputDebugStringA ( buf );
if (temp.header.ExtraFieldLength)
{
File->seek( temp.header.ExtraFieldLength, true);
}
if (temp.header.GeneralBitFlag & ZIP_INFO_IN_DATA_DESCRIPTOR)
{
// read data descriptor
File->seek(sizeof(SZIPFileDataDescriptor), true );
}
// compressed data
temp.fileDataPosition = File->getPos();
File->seek( temp.header.DataDescriptor.CompressedSize, true);
FileList.push_back( temp );
return true;
}
// Central directory structure
if ( temp.header.Sig == 0x04034b50 )
{
//SZIPFileCentralDirFileHeader h;
//File->read( &h, sizeof( h ) - 4 );
return true;
}
// End of central dir
if ( temp.header.Sig == 0x06054b50 )
{
return true;
}
// eof
if ( temp.header.Sig == 0x02014b50 )
{
return false;
}
return false;
}
#endif
//! scans for a local header, returns false if there is no more local file header.
//! The gzip file format seems to think that there can be multiple files in a gzip file
//! but none
bool CZipReader::scanGZipHeader()
{
SZipFileEntry entry;
entry.Offset = 0;
memset(&entry.header, 0, sizeof(SZIPFileHeader));
// read header
SGZIPMemberHeader header;
if (File->read(&header, sizeof(SGZIPMemberHeader)) == sizeof(SGZIPMemberHeader))
{
#ifdef __BIG_ENDIAN__
os::Byteswap::byteswap(header.sig);
os::Byteswap::byteswap(header.time);
#endif
// check header value
if (header.sig != 0x8b1f)
return false;
// now get the file info
if (header.flags & EGZF_EXTRA_FIELDS)
{
// read lenth of extra data
u16 dataLen;
File->read(&dataLen, 2);
#ifdef __BIG_ENDIAN__
os::Byteswap::byteswap(dataLen);
#endif
// skip it
File->seek(dataLen, true);
}
io::path ZipFileName = "";
if (header.flags & EGZF_FILE_NAME)
{
c8 c;
File->read(&c, 1);
while (c)
{
ZipFileName.append(c);
File->read(&c, 1);
}
}
else
{
// no file name?
ZipFileName = Path;
core::deletePathFromFilename(ZipFileName);
// rename tgz to tar or remove gz extension
if (core::hasFileExtension(ZipFileName, "tgz"))
{
ZipFileName[ ZipFileName.size() - 2] = 'a';
ZipFileName[ ZipFileName.size() - 1] = 'r';
}
else if (core::hasFileExtension(ZipFileName, "gz"))
{
ZipFileName[ ZipFileName.size() - 3] = 0;
ZipFileName.validate();
}
}
if (header.flags & EGZF_COMMENT)
{
c8 c='a';
while (c)
File->read(&c, 1);
}
if (header.flags & EGZF_CRC16)
File->seek(2, true);
// we are now at the start of the data blocks
entry.Offset = File->getPos();
entry.header.FilenameLength = ZipFileName.size();
entry.header.CompressionMethod = header.compressionMethod;
entry.header.DataDescriptor.CompressedSize = (File->getSize() - 8) - File->getPos();
// seek to file end
File->seek(entry.header.DataDescriptor.CompressedSize, true);
// read CRC
File->read(&entry.header.DataDescriptor.CRC32, 4);
// read uncompressed size
File->read(&entry.header.DataDescriptor.UncompressedSize, 4);
#ifdef __BIG_ENDIAN__
os::Byteswap::byteswap(entry.header.DataDescriptor.CRC32);
os::Byteswap::byteswap(entry.header.DataDescriptor.UncompressedSize);
#endif
// now we've filled all the fields, this is just a standard deflate block
addItem(ZipFileName, entry.header.DataDescriptor.UncompressedSize, false, 0);
FileInfo.push_back(entry);
}
// there's only one block of data in a gzip file
return false;
}
//! scans for a local header, returns false if there is no more local file header.
bool CZipReader::scanZipHeader()
{
io::path ZipFileName = "";
SZipFileEntry entry;
entry.Offset = 0;
memset(&entry.header, 0, sizeof(SZIPFileHeader));
File->read(&entry.header, sizeof(SZIPFileHeader));
#ifdef __BIG_ENDIAN__
entry.header.Sig = os::Byteswap::byteswap(entry.header.Sig);
entry.header.VersionToExtract = os::Byteswap::byteswap(entry.header.VersionToExtract);
entry.header.GeneralBitFlag = os::Byteswap::byteswap(entry.header.GeneralBitFlag);
entry.header.CompressionMethod = os::Byteswap::byteswap(entry.header.CompressionMethod);
entry.header.LastModFileTime = os::Byteswap::byteswap(entry.header.LastModFileTime);
entry.header.LastModFileDate = os::Byteswap::byteswap(entry.header.LastModFileDate);
entry.header.DataDescriptor.CRC32 = os::Byteswap::byteswap(entry.header.DataDescriptor.CRC32);
entry.header.DataDescriptor.CompressedSize = os::Byteswap::byteswap(entry.header.DataDescriptor.CompressedSize);
entry.header.DataDescriptor.UncompressedSize = os::Byteswap::byteswap(entry.header.DataDescriptor.UncompressedSize);
entry.header.FilenameLength = os::Byteswap::byteswap(entry.header.FilenameLength);
entry.header.ExtraFieldLength = os::Byteswap::byteswap(entry.header.ExtraFieldLength);
#endif
if (entry.header.Sig != 0x04034b50)
return false; // local file headers end here.
// read filename
{
c8 *tmp = new c8 [ entry.header.FilenameLength + 2 ];
File->read(tmp, entry.header.FilenameLength);
tmp[entry.header.FilenameLength] = 0;
ZipFileName = tmp;
delete [] tmp;
}
#ifdef _IRR_COMPILE_WITH_ZIP_ENCRYPTION_
// AES encryption
if ((entry.header.GeneralBitFlag & ZIP_FILE_ENCRYPTED) && (entry.header.CompressionMethod == 99))
{
s16 restSize = entry.header.ExtraFieldLength;
SZipFileExtraHeader extraHeader;
while (restSize)
{
File->read(&extraHeader, sizeof(extraHeader));
#ifdef __BIG_ENDIAN__
extraHeader.ID = os::Byteswap::byteswap(extraHeader.ID);
extraHeader.Size = os::Byteswap::byteswap(extraHeader.Size);
#endif
restSize -= sizeof(extraHeader);
if (extraHeader.ID==(s16)0x9901)
{
SZipFileAESExtraData data;
File->read(&data, sizeof(data));
#ifdef __BIG_ENDIAN__
data.Version = os::Byteswap::byteswap(data.Version);
data.CompressionMode = os::Byteswap::byteswap(data.CompressionMode);
#endif
restSize -= sizeof(data);
if (data.Vendor[0]=='A' && data.Vendor[1]=='E')
{
// encode values into Sig
// AE-Version | Strength | ActualMode
entry.header.Sig =
((data.Version & 0xff) << 24) |
(data.EncryptionStrength << 16) |
(data.CompressionMode);
File->seek(restSize, true);
break;
}
}
}
}
// move forward length of extra field.
else
#endif
if (entry.header.ExtraFieldLength)
File->seek(entry.header.ExtraFieldLength, true);
// if bit 3 was set, read DataDescriptor, following after the compressed data
if (entry.header.GeneralBitFlag & ZIP_INFO_IN_DATA_DESCRIPTOR)
{
// read data descriptor
File->read(&entry.header.DataDescriptor, sizeof(entry.header.DataDescriptor));
#ifdef __BIG_ENDIAN__
entry.header.DataDescriptor.CRC32 = os::Byteswap::byteswap(entry.header.DataDescriptor.CRC32);
entry.header.DataDescriptor.CompressedSize = os::Byteswap::byteswap(entry.header.DataDescriptor.CompressedSize);
entry.header.DataDescriptor.UncompressedSize = os::Byteswap::byteswap(entry.header.DataDescriptor.UncompressedSize);
#endif
}
// store position in file
entry.Offset = File->getPos();
// move forward length of data
File->seek(entry.header.DataDescriptor.CompressedSize, true);
#ifdef _DEBUG
//os::Debuginfo::print("added file from archive", ZipFileName.c_str());
#endif
addItem(ZipFileName, entry.header.DataDescriptor.UncompressedSize, false, FileInfo.size());
FileInfo.push_back(entry);
return true;
}
//! opens a file by file name
IReadFile* CZipReader::createAndOpenFile(const io::path& filename)
{
s32 index = findFile(filename, false);
if (index != -1)
return createAndOpenFile(index);
return 0;
}
#ifdef _IRR_COMPILE_WITH_LZMA_
//! Used for LZMA decompression. The lib has no default memory management
namespace
{
void *SzAlloc(void *p, size_t size) { p = p; return malloc(size); }
void SzFree(void *p, void *address) { p = p; free(address); }
ISzAlloc lzmaAlloc = { SzAlloc, SzFree };
}
#endif
//! opens a file by index
IReadFile* CZipReader::createAndOpenFile(u32 index)
{
// Irrlicht supports 0, 8, 12, 14, 99
//0 - The file is stored (no compression)
//1 - The file is Shrunk
//2 - The file is Reduced with compression factor 1
//3 - The file is Reduced with compression factor 2
//4 - The file is Reduced with compression factor 3
//5 - The file is Reduced with compression factor 4
//6 - The file is Imploded
//7 - Reserved for Tokenizing compression algorithm
//8 - The file is Deflated
//9 - Reserved for enhanced Deflating
//10 - PKWARE Date Compression Library Imploding
//12 - bzip2 - Compression Method from libbz2, WinZip 10
//14 - LZMA - Compression Method, WinZip 12
//96 - Jpeg compression - Compression Method, WinZip 12
//97 - WavPack - Compression Method, WinZip 11
//98 - PPMd - Compression Method, WinZip 10
//99 - AES encryption, WinZip 9
const SZipFileEntry &e = FileInfo[Files[index].ID];
wchar_t buf[64];
s16 actualCompressionMethod=e.header.CompressionMethod;
IReadFile* decrypted=0;
u8* decryptedBuf=0;
u32 decryptedSize=e.header.DataDescriptor.CompressedSize;
#ifdef _IRR_COMPILE_WITH_ZIP_ENCRYPTION_
if ((e.header.GeneralBitFlag & ZIP_FILE_ENCRYPTED) && (e.header.CompressionMethod == 99))
{
os::Printer::log("Reading encrypted file.");
u8 salt[16]={0};
const u16 saltSize = (((e.header.Sig & 0x00ff0000) >>16)+1)*4;
File->seek(e.Offset);
File->read(salt, saltSize);
char pwVerification[2];
char pwVerificationFile[2];
File->read(pwVerification, 2);
fcrypt_ctx zctx; // the encryption context
int rc = fcrypt_init(
(e.header.Sig & 0x00ff0000) >>16,
(const unsigned char*)Password.c_str(), // the password
Password.size(), // number of bytes in password
salt, // the salt
(unsigned char*)pwVerificationFile, // on return contains password verifier
&zctx); // encryption context
if (strncmp(pwVerificationFile, pwVerification, 2))
{
os::Printer::log("Wrong password");
return 0;
}
decryptedSize= e.header.DataDescriptor.CompressedSize-saltSize-12;
decryptedBuf= new u8[decryptedSize];
|
paupawsan/Irrlicht
|
4f012745456f74e0325ccd01eee82c18fc3ee1a2
|
Fix memory overflow in obj meshloader (thx for testcase from Brumm)
|
diff --git a/source/Irrlicht/COBJMeshFileLoader.cpp b/source/Irrlicht/COBJMeshFileLoader.cpp
index c4e1c2e..b40d40d 100644
--- a/source/Irrlicht/COBJMeshFileLoader.cpp
+++ b/source/Irrlicht/COBJMeshFileLoader.cpp
@@ -304,628 +304,628 @@ IAnimatedMesh* COBJMeshFileLoader::createMesh(io::IReadFile* file)
{
mesh->recalculateBoundingBox();
animMesh = new SAnimatedMesh();
animMesh->Type = EAMT_OBJ;
animMesh->addMesh(mesh);
animMesh->recalculateBoundingBox();
}
// Clean up the allocate obj file contents
delete [] buf;
// more cleaning up
cleanUp();
mesh->drop();
return animMesh;
}
const c8* COBJMeshFileLoader::readTextures(const c8* bufPtr, const c8* const bufEnd, SObjMtl* currMaterial, const io::path& relPath)
{
u8 type=0; // map_Kd - diffuse color texture map
// map_Ks - specular color texture map
// map_Ka - ambient color texture map
// map_Ns - shininess texture map
if ((!strncmp(bufPtr,"map_bump",8)) || (!strncmp(bufPtr,"bump",4)))
type=1; // normal map
else if ((!strncmp(bufPtr,"map_d",5)) || (!strncmp(bufPtr,"map_opacity",11)))
type=2; // opacity map
else if (!strncmp(bufPtr,"map_refl",8))
type=3; // reflection map
// extract new material's name
c8 textureNameBuf[WORD_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
f32 bumpiness = 6.0f;
bool clamp = false;
// handle options
while (textureNameBuf[0]=='-')
{
if (!strncmp(bufPtr,"-bm",3))
{
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
currMaterial->Meshbuffer->Material.MaterialTypeParam=core::fast_atof(textureNameBuf);
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
continue;
}
else
if (!strncmp(bufPtr,"-blendu",7))
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
else
if (!strncmp(bufPtr,"-blendv",7))
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
else
if (!strncmp(bufPtr,"-cc",3))
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
else
if (!strncmp(bufPtr,"-clamp",6))
bufPtr = readBool(bufPtr, clamp, bufEnd);
else
if (!strncmp(bufPtr,"-texres",7))
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
else
if (!strncmp(bufPtr,"-type",5))
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
else
if (!strncmp(bufPtr,"-mm",3))
{
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
}
else
if (!strncmp(bufPtr,"-o",2)) // texture coord translation
{
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
// next parameters are optional, so skip rest of loop if no number is found
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
if (!core::isdigit(textureNameBuf[0]))
continue;
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
if (!core::isdigit(textureNameBuf[0]))
continue;
}
else
if (!strncmp(bufPtr,"-s",2)) // texture coord scale
{
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
// next parameters are optional, so skip rest of loop if no number is found
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
if (!core::isdigit(textureNameBuf[0]))
continue;
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
if (!core::isdigit(textureNameBuf[0]))
continue;
}
else
if (!strncmp(bufPtr,"-t",2))
{
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
// next parameters are optional, so skip rest of loop if no number is found
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
if (!core::isdigit(textureNameBuf[0]))
continue;
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
if (!core::isdigit(textureNameBuf[0]))
continue;
}
// get next word
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
}
if ((type==1) && (core::isdigit(textureNameBuf[0])))
{
currMaterial->Meshbuffer->Material.MaterialTypeParam=core::fast_atof(textureNameBuf);
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
}
if (clamp)
currMaterial->Meshbuffer->Material.setFlag(video::EMF_TEXTURE_WRAP, video::ETC_CLAMP);
io::path texname(textureNameBuf);
texname.replace('\\', '/');
video::ITexture * texture = 0;
bool newTexture=false;
if (texname.size())
{
io::path texnameWithUserPath( SceneManager->getParameters()->getAttributeAsString(OBJ_TEXTURE_PATH) );
if ( texnameWithUserPath.size() )
{
texnameWithUserPath += '/';
texnameWithUserPath += texname;
}
if (FileSystem->existFile(texnameWithUserPath))
texture = SceneManager->getVideoDriver()->getTexture(texnameWithUserPath);
else if (FileSystem->existFile(texname))
{
newTexture = SceneManager->getVideoDriver()->findTexture(texname) == 0;
texture = SceneManager->getVideoDriver()->getTexture(texname);
}
else
{
newTexture = SceneManager->getVideoDriver()->findTexture(relPath + texname) == 0;
// try to read in the relative path, the .obj is loaded from
texture = SceneManager->getVideoDriver()->getTexture( relPath + texname );
}
}
if ( texture )
{
if (type==0)
currMaterial->Meshbuffer->Material.setTexture(0, texture);
else if (type==1)
{
if (newTexture)
SceneManager->getVideoDriver()->makeNormalMapTexture(texture, bumpiness);
currMaterial->Meshbuffer->Material.setTexture(1, texture);
currMaterial->Meshbuffer->Material.MaterialType=video::EMT_PARALLAX_MAP_SOLID;
currMaterial->Meshbuffer->Material.MaterialTypeParam=0.035f;
}
else if (type==2)
{
currMaterial->Meshbuffer->Material.setTexture(0, texture);
currMaterial->Meshbuffer->Material.MaterialType=video::EMT_TRANSPARENT_ADD_COLOR;
}
else if (type==3)
{
// currMaterial->Meshbuffer->Material.Textures[1] = texture;
// currMaterial->Meshbuffer->Material.MaterialType=video::EMT_REFLECTION_2_LAYER;
}
// Set diffuse material colour to white so as not to affect texture colour
// Because Maya set diffuse colour Kd to black when you use a diffuse colour map
// But is this the right thing to do?
currMaterial->Meshbuffer->Material.DiffuseColor.set(
currMaterial->Meshbuffer->Material.DiffuseColor.getAlpha(), 255, 255, 255 );
}
return bufPtr;
}
void COBJMeshFileLoader::readMTL(const c8* fileName, const io::path& relPath)
{
const io::path realFile(fileName);
io::IReadFile * mtlReader;
if (FileSystem->existFile(realFile))
mtlReader = FileSystem->createAndOpenFile(realFile);
else if (FileSystem->existFile(relPath + realFile))
mtlReader = FileSystem->createAndOpenFile(relPath + realFile);
else if (FileSystem->existFile(FileSystem->getFileBasename(realFile)))
mtlReader = FileSystem->createAndOpenFile(FileSystem->getFileBasename(realFile));
else
mtlReader = FileSystem->createAndOpenFile(relPath + FileSystem->getFileBasename(realFile));
if (!mtlReader) // fail to open and read file
{
os::Printer::log("Could not open material file", realFile, ELL_WARNING);
return;
}
const long filesize = mtlReader->getSize();
if (!filesize)
{
os::Printer::log("Skipping empty material file", realFile, ELL_WARNING);
mtlReader->drop();
return;
}
c8* buf = new c8[filesize];
mtlReader->read((void*)buf, filesize);
const c8* bufEnd = buf+filesize;
SObjMtl* currMaterial = 0;
const c8* bufPtr = buf;
while(bufPtr != bufEnd)
{
switch(*bufPtr)
{
case 'n': // newmtl
{
// if there's an existing material, store it first
if ( currMaterial )
Materials.push_back( currMaterial );
// extract new material's name
c8 mtlNameBuf[WORD_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(mtlNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
currMaterial = new SObjMtl;
currMaterial->Name = mtlNameBuf;
}
break;
case 'i': // illum - illumination
if ( currMaterial )
{
const u32 COLOR_BUFFER_LENGTH = 16;
c8 illumStr[COLOR_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(illumStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
currMaterial->Illumination = (c8)atol(illumStr);
}
break;
case 'N':
if ( currMaterial )
{
switch(bufPtr[1])
{
case 's': // Ns - shininess
{
const u32 COLOR_BUFFER_LENGTH = 16;
c8 nsStr[COLOR_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(nsStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
f32 shininessValue = core::fast_atof(nsStr);
// wavefront shininess is from [0, 1000], so scale for OpenGL
shininessValue *= 0.128f;
currMaterial->Meshbuffer->Material.Shininess = shininessValue;
}
break;
case 'i': // Ni - refraction index
{
c8 tmpbuf[WORD_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(tmpbuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
}
break;
}
}
break;
case 'K':
if ( currMaterial )
{
switch(bufPtr[1])
{
case 'd': // Kd = diffuse
{
bufPtr = readColor(bufPtr, currMaterial->Meshbuffer->Material.DiffuseColor, bufEnd);
}
break;
case 's': // Ks = specular
{
bufPtr = readColor(bufPtr, currMaterial->Meshbuffer->Material.SpecularColor, bufEnd);
}
break;
case 'a': // Ka = ambience
{
bufPtr=readColor(bufPtr, currMaterial->Meshbuffer->Material.AmbientColor, bufEnd);
}
break;
case 'e': // Ke = emissive
{
bufPtr=readColor(bufPtr, currMaterial->Meshbuffer->Material.EmissiveColor, bufEnd);
}
break;
} // end switch(bufPtr[1])
} // end case 'K': if ( 0 != currMaterial )...
break;
case 'b': // bump
case 'm': // texture maps
if (currMaterial)
{
bufPtr=readTextures(bufPtr, bufEnd, currMaterial, relPath);
}
break;
case 'd': // d - transparency
if ( currMaterial )
{
const u32 COLOR_BUFFER_LENGTH = 16;
c8 dStr[COLOR_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(dStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
f32 dValue = core::fast_atof(dStr);
currMaterial->Meshbuffer->Material.DiffuseColor.setAlpha( (s32)(dValue * 255) );
if (dValue<1.0f)
currMaterial->Meshbuffer->Material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
}
break;
case 'T':
if ( currMaterial )
{
switch ( bufPtr[1] )
{
case 'f': // Tf - Transmitivity
const u32 COLOR_BUFFER_LENGTH = 16;
c8 redStr[COLOR_BUFFER_LENGTH];
c8 greenStr[COLOR_BUFFER_LENGTH];
c8 blueStr[COLOR_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(redStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
bufPtr = goAndCopyNextWord(greenStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
bufPtr = goAndCopyNextWord(blueStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
f32 transparency = ( core::fast_atof(redStr) + core::fast_atof(greenStr) + core::fast_atof(blueStr) ) / 3;
currMaterial->Meshbuffer->Material.DiffuseColor.setAlpha( (s32)(transparency * 255) );
if (transparency < 1.0f)
currMaterial->Meshbuffer->Material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
}
}
break;
default: // comments or not recognised
break;
} // end switch(bufPtr[0])
// go to next line
bufPtr = goNextLine(bufPtr, bufEnd);
} // end while (bufPtr)
// end of file. if there's an existing material, store it
if ( currMaterial )
Materials.push_back( currMaterial );
delete [] buf;
mtlReader->drop();
}
//! Read RGB color
const c8* COBJMeshFileLoader::readColor(const c8* bufPtr, video::SColor& color, const c8* const bufEnd)
{
const u32 COLOR_BUFFER_LENGTH = 16;
c8 colStr[COLOR_BUFFER_LENGTH];
color.setAlpha(255);
bufPtr = goAndCopyNextWord(colStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
color.setRed((s32)(core::fast_atof(colStr) * 255.0f));
bufPtr = goAndCopyNextWord(colStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
color.setGreen((s32)(core::fast_atof(colStr) * 255.0f));
bufPtr = goAndCopyNextWord(colStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
color.setBlue((s32)(core::fast_atof(colStr) * 255.0f));
return bufPtr;
}
//! Read 3d vector of floats
const c8* COBJMeshFileLoader::readVec3(const c8* bufPtr, core::vector3df& vec, const c8* const bufEnd)
{
const u32 WORD_BUFFER_LENGTH = 256;
c8 wordBuffer[WORD_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
vec.X=-core::fast_atof(wordBuffer); // change handedness
bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
vec.Y=core::fast_atof(wordBuffer);
bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
vec.Z=core::fast_atof(wordBuffer);
return bufPtr;
}
//! Read 2d vector of floats
const c8* COBJMeshFileLoader::readUV(const c8* bufPtr, core::vector2df& vec, const c8* const bufEnd)
{
const u32 WORD_BUFFER_LENGTH = 256;
c8 wordBuffer[WORD_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
vec.X=core::fast_atof(wordBuffer);
bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
vec.Y=1-core::fast_atof(wordBuffer); // change handedness
return bufPtr;
}
//! Read boolean value represented as 'on' or 'off'
const c8* COBJMeshFileLoader::readBool(const c8* bufPtr, bool& tf, const c8* const bufEnd)
{
const u32 BUFFER_LENGTH = 8;
c8 tfStr[BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(tfStr, bufPtr, BUFFER_LENGTH, bufEnd);
tf = strcmp(tfStr, "off") != 0;
return bufPtr;
}
COBJMeshFileLoader::SObjMtl* COBJMeshFileLoader::findMtl(const core::stringc& mtlName, const core::stringc& grpName)
{
COBJMeshFileLoader::SObjMtl* defMaterial = 0;
// search existing Materials for best match
// exact match does return immediately, only name match means a new group
for (u32 i = 0; i < Materials.size(); ++i)
{
if ( Materials[i]->Name == mtlName )
{
if ( Materials[i]->Group == grpName )
return Materials[i];
else
defMaterial = Materials[i];
}
}
// we found a partial match
if (defMaterial)
{
Materials.push_back(new SObjMtl(*defMaterial));
Materials.getLast()->Group = grpName;
return Materials.getLast();
}
// we found a new group for a non-existant material
else if (grpName.size())
{
Materials.push_back(new SObjMtl(*Materials[0]));
Materials.getLast()->Group = grpName;
return Materials.getLast();
}
return 0;
}
//! skip space characters and stop on first non-space
const c8* COBJMeshFileLoader::goFirstWord(const c8* buf, const c8* const bufEnd, bool acrossNewlines)
{
// skip space characters
if (acrossNewlines)
while((buf != bufEnd) && core::isspace(*buf))
++buf;
else
while((buf != bufEnd) && core::isspace(*buf) && (*buf != '\n'))
++buf;
return buf;
}
//! skip current word and stop at beginning of next one
const c8* COBJMeshFileLoader::goNextWord(const c8* buf, const c8* const bufEnd, bool acrossNewlines)
{
// skip current word
while(( buf != bufEnd ) && !core::isspace(*buf))
++buf;
return goFirstWord(buf, bufEnd, acrossNewlines);
}
//! Read until line break is reached and stop at the next non-space character
const c8* COBJMeshFileLoader::goNextLine(const c8* buf, const c8* const bufEnd)
{
// look for newline characters
while(buf != bufEnd)
{
// found it, so leave
if (*buf=='\n' || *buf=='\r')
break;
++buf;
}
return goFirstWord(buf, bufEnd);
}
u32 COBJMeshFileLoader::copyWord(c8* outBuf, const c8* const inBuf, u32 outBufLength, const c8* const bufEnd)
{
if (!outBufLength)
return 0;
if (!inBuf)
{
*outBuf = 0;
return 0;
}
u32 i = 0;
while(inBuf[i])
{
if (core::isspace(inBuf[i]) || &(inBuf[i]) == bufEnd)
break;
++i;
}
u32 length = core::min_(i, outBufLength-1);
for (u32 j=0; j<length; ++j)
outBuf[j] = inBuf[j];
- outBuf[i] = 0;
+ outBuf[length] = 0;
return length;
}
core::stringc COBJMeshFileLoader::copyLine(const c8* inBuf, const c8* bufEnd)
{
if (!inBuf)
return core::stringc();
const c8* ptr = inBuf;
while (ptr<bufEnd)
{
if (*ptr=='\n' || *ptr=='\r')
break;
++ptr;
}
return core::stringc(inBuf, (u32)(ptr-inBuf+1));
}
const c8* COBJMeshFileLoader::goAndCopyNextWord(c8* outBuf, const c8* inBuf, u32 outBufLength, const c8* bufEnd)
{
inBuf = goNextWord(inBuf, bufEnd, false);
copyWord(outBuf, inBuf, outBufLength, bufEnd);
return inBuf;
}
bool COBJMeshFileLoader::retrieveVertexIndices(c8* vertexData, s32* idx, const c8* bufEnd, u32 vbsize, u32 vtsize, u32 vnsize)
{
c8 word[16] = "";
const c8* p = goFirstWord(vertexData, bufEnd);
u32 idxType = 0; // 0 = posIdx, 1 = texcoordIdx, 2 = normalIdx
u32 i = 0;
while ( p != bufEnd )
{
if ( ( core::isdigit(*p)) || (*p == '-') )
{
// build up the number
word[i++] = *p;
}
else if ( *p == '/' || *p == ' ' || *p == '\0' )
{
// number is completed. Convert and store it
word[i] = '\0';
// if no number was found index will become 0 and later on -1 by decrement
if (word[0]=='-')
{
idx[idxType] = core::strtol10(word+1,0);
idx[idxType] *= -1;
switch (idxType)
{
case 0:
idx[idxType] += vbsize;
break;
case 1:
idx[idxType] += vtsize;
break;
case 2:
idx[idxType] += vnsize;
break;
}
}
else
idx[idxType] = core::strtol10(word,0)-1;
// reset the word
word[0] = '\0';
i = 0;
// go to the next kind of index type
if (*p == '/')
{
if ( ++idxType > 2 )
{
// error checking, shouldn't reach here unless file is wrong
idxType = 0;
}
}
else
{
// set all missing values to disable (=-1)
while (++idxType < 3)
idx[idxType]=-1;
++p;
break; // while
}
}
// go to the next char
++p;
}
return true;
}
void COBJMeshFileLoader::cleanUp()
{
for (u32 i=0; i < Materials.size(); ++i )
{
Materials[i]->Meshbuffer->drop();
delete Materials[i];
}
Materials.clear();
}
} // end namespace scene
} // end namespace irr
#endif // _IRR_COMPILE_WITH_OBJ_LOADER_
|
paupawsan/Irrlicht
|
b5b80ba8fea48e2e3aa246b043cabbb4417f80af
|
Fix mem leak found by sebpes.
|
diff --git a/source/Irrlicht/COpenGLTexture.cpp b/source/Irrlicht/COpenGLTexture.cpp
index a713fd4..b565c91 100644
--- a/source/Irrlicht/COpenGLTexture.cpp
+++ b/source/Irrlicht/COpenGLTexture.cpp
@@ -1,894 +1,894 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_OPENGL_
#include "irrTypes.h"
#include "COpenGLTexture.h"
#include "COpenGLDriver.h"
#include "os.h"
#include "CImage.h"
#include "CColorConverter.h"
#include "irrString.h"
namespace irr
{
namespace video
{
//! constructor for usual textures
COpenGLTexture::COpenGLTexture(IImage* origImage, const io::path& name, void* mipmapData, COpenGLDriver* driver)
: ITexture(name), ColorFormat(ECF_A8R8G8B8), Driver(driver), Image(0), MipImage(0),
TextureName(0), InternalFormat(GL_RGBA), PixelFormat(GL_BGRA_EXT),
PixelType(GL_UNSIGNED_BYTE),
IsRenderTarget(false), AutomaticMipmapUpdate(false),
ReadOnlyLock(false), KeepImage(true)
{
#ifdef _DEBUG
setDebugName("COpenGLTexture");
#endif
HasMipMaps = Driver->getTextureCreationFlag(ETCF_CREATE_MIP_MAPS);
getImageValues(origImage);
glGenTextures(1, &TextureName);
if (ImageSize==TextureSize)
{
Image = new CImage(ColorFormat, ImageSize);
origImage->copyTo(Image);
}
else
{
Image = new CImage(ColorFormat, TextureSize);
// scale texture
origImage->copyToScaling(Image);
}
uploadTexture(true, mipmapData);
if (!KeepImage)
{
Image->drop();
Image=0;
}
}
//! constructor for basic setup (only for derived classes)
COpenGLTexture::COpenGLTexture(const io::path& name, COpenGLDriver* driver)
: ITexture(name), ColorFormat(ECF_A8R8G8B8), Driver(driver), Image(0), MipImage(0),
TextureName(0), InternalFormat(GL_RGBA), PixelFormat(GL_BGRA_EXT),
PixelType(GL_UNSIGNED_BYTE),
HasMipMaps(true), IsRenderTarget(false), AutomaticMipmapUpdate(false),
ReadOnlyLock(false), KeepImage(true)
{
#ifdef _DEBUG
setDebugName("COpenGLTexture");
#endif
}
//! destructor
COpenGLTexture::~COpenGLTexture()
{
if (TextureName)
glDeleteTextures(1, &TextureName);
if (Image)
Image->drop();
}
//! Choose best matching color format, based on texture creation flags
ECOLOR_FORMAT COpenGLTexture::getBestColorFormat(ECOLOR_FORMAT format)
{
ECOLOR_FORMAT destFormat = ECF_A8R8G8B8;
switch (format)
{
case ECF_A1R5G5B5:
if (!Driver->getTextureCreationFlag(ETCF_ALWAYS_32_BIT))
destFormat = ECF_A1R5G5B5;
break;
case ECF_R5G6B5:
if (!Driver->getTextureCreationFlag(ETCF_ALWAYS_32_BIT))
destFormat = ECF_A1R5G5B5;
break;
case ECF_A8R8G8B8:
if (Driver->getTextureCreationFlag(ETCF_ALWAYS_16_BIT) ||
Driver->getTextureCreationFlag(ETCF_OPTIMIZED_FOR_SPEED))
destFormat = ECF_A1R5G5B5;
break;
case ECF_R8G8B8:
if (Driver->getTextureCreationFlag(ETCF_ALWAYS_16_BIT) ||
Driver->getTextureCreationFlag(ETCF_OPTIMIZED_FOR_SPEED))
destFormat = ECF_A1R5G5B5;
default:
break;
}
if (Driver->getTextureCreationFlag(ETCF_NO_ALPHA_CHANNEL))
{
switch (destFormat)
{
case ECF_A1R5G5B5:
destFormat = ECF_R5G6B5;
break;
case ECF_A8R8G8B8:
destFormat = ECF_R8G8B8;
break;
default:
break;
}
}
return destFormat;
}
//! Get opengl values for the GPU texture storage
GLint COpenGLTexture::getOpenGLFormatAndParametersFromColorFormat(ECOLOR_FORMAT format,
GLint& filtering,
GLenum& colorformat,
GLenum& type)
{
// default
filtering = GL_LINEAR;
colorformat = GL_RGBA;
type = GL_UNSIGNED_BYTE;
switch(format)
{
case ECF_A1R5G5B5:
colorformat=GL_BGRA_EXT;
type=GL_UNSIGNED_SHORT_1_5_5_5_REV;
return GL_RGBA;
case ECF_R5G6B5:
colorformat=GL_BGR;
type=GL_UNSIGNED_SHORT_5_6_5_REV;
return GL_RGB;
case ECF_R8G8B8:
colorformat=GL_BGR;
type=GL_UNSIGNED_BYTE;
return GL_RGB;
case ECF_A8R8G8B8:
colorformat=GL_BGRA_EXT;
if (Driver->Version > 101)
type=GL_UNSIGNED_INT_8_8_8_8_REV;
return GL_RGBA;
// Floating Point texture formats. Thanks to Patryk "Nadro" Nadrowski.
case ECF_R16F:
{
#ifdef GL_ARB_texture_rg
filtering = GL_NEAREST;
colorformat = GL_RED;
type = GL_FLOAT;
return GL_R16F;
#else
return GL_RGB8;
#endif
}
case ECF_G16R16F:
{
#ifdef GL_ARB_texture_rg
filtering = GL_NEAREST;
colorformat = GL_RG;
type = GL_FLOAT;
return GL_RG16F;
#else
return GL_RGB8;
#endif
}
case ECF_A16B16G16R16F:
{
#ifdef GL_ARB_texture_rg
filtering = GL_NEAREST;
colorformat = GL_RGBA;
type = GL_FLOAT;
return GL_RGBA16F_ARB;
#else
return GL_RGBA8;
#endif
}
case ECF_R32F:
{
#ifdef GL_ARB_texture_rg
filtering = GL_NEAREST;
colorformat = GL_RED;
type = GL_FLOAT;
return GL_R32F;
#else
return GL_RGB8;
#endif
}
case ECF_G32R32F:
{
#ifdef GL_ARB_texture_rg
filtering = GL_NEAREST;
colorformat = GL_RG;
type = GL_FLOAT;
return GL_RG32F;
#else
return GL_RGB8;
#endif
}
case ECF_A32B32G32R32F:
{
#ifdef GL_ARB_texture_float
filtering = GL_NEAREST;
colorformat = GL_RGBA;
type = GL_FLOAT;
return GL_RGBA32F_ARB;
#else
return GL_RGBA8;
#endif
}
default:
{
os::Printer::log("Unsupported texture format", ELL_ERROR);
return GL_RGBA8;
}
}
}
// prepare values ImageSize, TextureSize, and ColorFormat based on image
void COpenGLTexture::getImageValues(IImage* image)
{
if (!image)
{
os::Printer::log("No image for OpenGL texture.", ELL_ERROR);
return;
}
ImageSize = image->getDimension();
if ( !ImageSize.Width || !ImageSize.Height)
{
os::Printer::log("Invalid size of image for OpenGL Texture.", ELL_ERROR);
return;
}
const f32 ratio = (f32)ImageSize.Width/(f32)ImageSize.Height;
if ((ImageSize.Width>Driver->MaxTextureSize) && (ratio >= 1.0f))
{
ImageSize.Width = Driver->MaxTextureSize;
ImageSize.Height = (u32)(Driver->MaxTextureSize/ratio);
}
else if (ImageSize.Height>Driver->MaxTextureSize)
{
ImageSize.Height = Driver->MaxTextureSize;
ImageSize.Width = (u32)(Driver->MaxTextureSize*ratio);
}
TextureSize=ImageSize.getOptimalSize(!Driver->queryFeature(EVDF_TEXTURE_NPOT));
ColorFormat = getBestColorFormat(image->getColorFormat());
}
//! copies the the texture into an open gl texture.
void COpenGLTexture::uploadTexture(bool newTexture, void* mipmapData, u32 level)
{
// check which image needs to be uploaded
IImage* image = level?MipImage:Image;
if (!image)
{
os::Printer::log("No image for OpenGL texture to upload", ELL_ERROR);
return;
}
// get correct opengl color data values
GLenum oldInternalFormat = InternalFormat;
GLint filtering;
InternalFormat = getOpenGLFormatAndParametersFromColorFormat(ColorFormat, filtering, PixelFormat, PixelType);
// make sure we don't change the internal format of existing images
if (!newTexture)
InternalFormat=oldInternalFormat;
Driver->setActiveTexture(0, this);
if (Driver->testGLError())
os::Printer::log("Could not bind Texture", ELL_ERROR);
// mipmap handling for main texture
if (!level && newTexture)
{
#ifndef DISABLE_MIPMAPPING
#ifdef GL_SGIS_generate_mipmap
// auto generate if possible and no mipmap data is given
if (HasMipMaps && !mipmapData && Driver->queryFeature(EVDF_MIP_MAP_AUTO_UPDATE))
{
if (Driver->getTextureCreationFlag(ETCF_OPTIMIZED_FOR_SPEED))
glHint(GL_GENERATE_MIPMAP_HINT_SGIS, GL_FASTEST);
else if (Driver->getTextureCreationFlag(ETCF_OPTIMIZED_FOR_QUALITY))
glHint(GL_GENERATE_MIPMAP_HINT_SGIS, GL_NICEST);
else
glHint(GL_GENERATE_MIPMAP_HINT_SGIS, GL_DONT_CARE);
// automatically generate and update mipmaps
glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE );
AutomaticMipmapUpdate=true;
}
else
#endif
{
// Either generate manually due to missing capability
// or use predefined mipmap data
AutomaticMipmapUpdate=false;
regenerateMipMapLevels(mipmapData);
}
if (HasMipMaps) // might have changed in regenerateMipMapLevels
{
// enable bilinear mipmap filter
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
else
#else
HasMipMaps=false;
os::Printer::log("Did not create OpenGL texture mip maps.", ELL_INFORMATION);
#endif
{
// enable bilinear filter without mipmaps
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
}
// now get image data and upload to GPU
void* source = image->lock();
if (newTexture)
glTexImage2D(GL_TEXTURE_2D, level, InternalFormat, image->getDimension().Width,
image->getDimension().Height, 0, PixelFormat, PixelType, source);
else
glTexSubImage2D(GL_TEXTURE_2D, level, 0, 0, image->getDimension().Width,
image->getDimension().Height, PixelFormat, PixelType, source);
image->unlock();
if (Driver->testGLError())
os::Printer::log("Could not glTexImage2D", ELL_ERROR);
}
//! lock function
void* COpenGLTexture::lock(bool readOnly, u32 mipmapLevel)
{
// store info about which image is locked
IImage* image = (mipmapLevel==0)?Image:MipImage;
ReadOnlyLock |= readOnly;
MipLevelStored = mipmapLevel;
// if data not available or might have changed on GPU download it
if (!image || IsRenderTarget)
{
// prepare the data storage if necessary
if (!image)
{
if (mipmapLevel)
{
u32 i=0;
u32 width = TextureSize.Width;
u32 height = TextureSize.Height;
do
{
if (width>1)
width>>=1;
if (height>1)
height>>=1;
++i;
}
while (i != mipmapLevel);
- image = new CImage(ECF_A8R8G8B8, core::dimension2du(width,height));
+ MipImage = image = new CImage(ECF_A8R8G8B8, core::dimension2du(width,height));
}
else
- image = new CImage(ECF_A8R8G8B8, ImageSize);
+ Image = image = new CImage(ECF_A8R8G8B8, ImageSize);
ColorFormat = ECF_A8R8G8B8;
}
if (!image)
return 0;
u8* pixels = static_cast<u8*>(image->lock());
if (!pixels)
return 0;
// we need to keep the correct texture bound later on
GLint tmpTexture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &tmpTexture);
glBindTexture(GL_TEXTURE_2D, TextureName);
// allows to read pixels in top-to-bottom order
#ifdef GL_MESA_pack_invert
if (Driver->queryOpenGLFeature(COpenGLExtensionHandler::IRR_MESA_pack_invert))
glPixelStorei(GL_PACK_INVERT_MESA, GL_TRUE);
#endif
// download GPU data as ARGB8 to pixels;
glGetTexImage(GL_TEXTURE_2D, mipmapLevel, GL_BGRA_EXT, GL_UNSIGNED_BYTE, pixels);
#ifdef GL_MESA_pack_invert
if (Driver->queryOpenGLFeature(COpenGLExtensionHandler::IRR_MESA_pack_invert))
glPixelStorei(GL_PACK_INVERT_MESA, GL_FALSE);
else
#endif
{
// opengl images are horizontally flipped, so we have to fix that here.
const s32 pitch=image->getPitch();
u8* p2 = pixels + (image->getDimension().Height - 1) * pitch;
u8* tmpBuffer = new u8[pitch];
for (u32 i=0; i < image->getDimension().Height; i += 2)
{
memcpy(tmpBuffer, pixels, pitch);
memcpy(pixels, p2, pitch);
memcpy(p2, tmpBuffer, pitch);
pixels += pitch;
p2 -= pitch;
}
delete [] tmpBuffer;
}
image->unlock();
//reset old bound texture
glBindTexture(GL_TEXTURE_2D, tmpTexture);
}
return image->lock();
}
//! unlock function
void COpenGLTexture::unlock()
{
// test if miplevel or main texture was locked
IImage* image = MipImage?MipImage:Image;
if (!image)
return;
// unlock image to see changes
image->unlock();
// copy texture data to GPU
if (!ReadOnlyLock)
uploadTexture(false, 0, MipLevelStored);
ReadOnlyLock = false;
// cleanup local image
if (MipImage)
{
MipImage->drop();
MipImage=0;
}
else if (!KeepImage)
{
Image->drop();
Image=0;
}
// update information
if (Image)
ColorFormat=Image->getColorFormat();
else
ColorFormat=ECF_A8R8G8B8;
}
//! Returns size of the original image.
const core::dimension2d<u32>& COpenGLTexture::getOriginalSize() const
{
return ImageSize;
}
//! Returns size of the texture.
const core::dimension2d<u32>& COpenGLTexture::getSize() const
{
return TextureSize;
}
//! returns driver type of texture, i.e. the driver, which created the texture
E_DRIVER_TYPE COpenGLTexture::getDriverType() const
{
return EDT_OPENGL;
}
//! returns color format of texture
ECOLOR_FORMAT COpenGLTexture::getColorFormat() const
{
return ColorFormat;
}
//! returns pitch of texture (in bytes)
u32 COpenGLTexture::getPitch() const
{
if (Image)
return Image->getPitch();
else
return 0;
}
//! return open gl texture name
GLuint COpenGLTexture::getOpenGLTextureName() const
{
return TextureName;
}
//! Returns whether this texture has mipmaps
bool COpenGLTexture::hasMipMaps() const
{
return HasMipMaps;
}
//! Regenerates the mip map levels of the texture. Useful after locking and
//! modifying the texture
void COpenGLTexture::regenerateMipMapLevels(void* mipmapData)
{
if (AutomaticMipmapUpdate || !HasMipMaps || !Image)
return;
if ((Image->getDimension().Width==1) && (Image->getDimension().Height==1))
return;
// Manually create mipmaps or use prepared version
u32 width=Image->getDimension().Width;
u32 height=Image->getDimension().Height;
u32 i=0;
u8* target = static_cast<u8*>(mipmapData);
do
{
if (width>1)
width>>=1;
if (height>1)
height>>=1;
++i;
if (!target)
target = new u8[width*height*Image->getBytesPerPixel()];
// create scaled version if no mipdata available
if (!mipmapData)
Image->copyToScaling(target, width, height, Image->getColorFormat());
glTexImage2D(GL_TEXTURE_2D, i, InternalFormat, width, height,
0, PixelFormat, PixelType, target);
// get next prepared mipmap data if available
if (mipmapData)
{
mipmapData = static_cast<u8*>(mipmapData)+width*height*Image->getBytesPerPixel();
target = static_cast<u8*>(mipmapData);
}
}
while (width!=1 || height!=1);
// cleanup
if (!mipmapData)
delete [] target;
}
bool COpenGLTexture::isRenderTarget() const
{
return IsRenderTarget;
}
void COpenGLTexture::setIsRenderTarget(bool isTarget)
{
IsRenderTarget = isTarget;
}
bool COpenGLTexture::isFrameBufferObject() const
{
return false;
}
//! Bind Render Target Texture
void COpenGLTexture::bindRTT()
{
}
//! Unbind Render Target Texture
void COpenGLTexture::unbindRTT()
{
Driver->setActiveTexture(0, this);
// Copy Our ViewPort To The Texture
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, getSize().Width, getSize().Height);
}
/* FBO Textures */
// helper function for render to texture
static bool checkFBOStatus(COpenGLDriver* Driver);
//! RTT ColorFrameBuffer constructor
COpenGLFBOTexture::COpenGLFBOTexture(const core::dimension2d<u32>& size,
const io::path& name, COpenGLDriver* driver,
const ECOLOR_FORMAT format)
: COpenGLTexture(name, driver), DepthTexture(0), ColorFrameBuffer(0)
{
#ifdef _DEBUG
setDebugName("COpenGLTexture_FBO");
#endif
ImageSize = size;
TextureSize = size;
GLint FilteringType;
InternalFormat = getOpenGLFormatAndParametersFromColorFormat(format, FilteringType, PixelFormat, PixelType);
HasMipMaps = false;
IsRenderTarget = true;
#ifdef GL_EXT_framebuffer_object
// generate frame buffer
Driver->extGlGenFramebuffers(1, &ColorFrameBuffer);
Driver->extGlBindFramebuffer(GL_FRAMEBUFFER_EXT, ColorFrameBuffer);
// generate color texture
glGenTextures(1, &TextureName);
Driver->setActiveTexture(0, this);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, FilteringType);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, InternalFormat, ImageSize.Width,
ImageSize.Height, 0, PixelFormat, PixelType, 0);
// attach color texture to frame buffer
Driver->extGlFramebufferTexture2D(GL_FRAMEBUFFER_EXT,
GL_COLOR_ATTACHMENT0_EXT,
GL_TEXTURE_2D,
TextureName,
0);
#endif
unbindRTT();
}
//! destructor
COpenGLFBOTexture::~COpenGLFBOTexture()
{
if (DepthTexture)
if (DepthTexture->drop())
Driver->removeDepthTexture(DepthTexture);
if (ColorFrameBuffer)
Driver->extGlDeleteFramebuffers(1, &ColorFrameBuffer);
}
bool COpenGLFBOTexture::isFrameBufferObject() const
{
return true;
}
//! Bind Render Target Texture
void COpenGLFBOTexture::bindRTT()
{
#ifdef GL_EXT_framebuffer_object
if (ColorFrameBuffer != 0)
Driver->extGlBindFramebuffer(GL_FRAMEBUFFER_EXT, ColorFrameBuffer);
#endif
}
//! Unbind Render Target Texture
void COpenGLFBOTexture::unbindRTT()
{
#ifdef GL_EXT_framebuffer_object
if (ColorFrameBuffer != 0)
Driver->extGlBindFramebuffer(GL_FRAMEBUFFER_EXT, 0);
#endif
}
/* FBO Depth Textures */
//! RTT DepthBuffer constructor
COpenGLFBODepthTexture::COpenGLFBODepthTexture(
const core::dimension2d<u32>& size,
const io::path& name,
COpenGLDriver* driver,
bool useStencil)
: COpenGLFBOTexture(size, name, driver), DepthRenderBuffer(0),
StencilRenderBuffer(0), UseStencil(useStencil)
{
#ifdef _DEBUG
setDebugName("COpenGLTextureFBO_Depth");
#endif
ImageSize = size;
TextureSize = size;
InternalFormat = GL_RGBA;
PixelFormat = GL_RGBA;
PixelType = GL_UNSIGNED_BYTE;
HasMipMaps = false;
if (useStencil)
{
glGenTextures(1, &DepthRenderBuffer);
glBindTexture(GL_TEXTURE_2D, DepthRenderBuffer);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
#ifdef GL_EXT_packed_depth_stencil
if (Driver->queryOpenGLFeature(COpenGLExtensionHandler::IRR_EXT_packed_depth_stencil))
{
// generate packed depth stencil texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_STENCIL_EXT, ImageSize.Width,
ImageSize.Height, 0, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT, 0);
StencilRenderBuffer = DepthRenderBuffer; // stencil is packed with depth
}
else // generate separate stencil and depth textures
#endif
{
// generate depth texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, ImageSize.Width,
ImageSize.Height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);
// we 're in trouble! the code below does not complete
// the FBO currently... stencil buffer is only
// supported with EXT_packed_depth_stencil extension
// (above)
// // generate stencil texture
// glGenTextures(1, &StencilRenderBuffer);
// glBindTexture(GL_TEXTURE_2D, StencilRenderBuffer);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_STENCIL_INDEX, ImageSize.Width,
// ImageSize.Height, 0, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, 0);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
}
#ifdef GL_EXT_framebuffer_object
else
{
// generate depth buffer
Driver->extGlGenRenderbuffers(1, &DepthRenderBuffer);
Driver->extGlBindRenderbuffer(GL_RENDERBUFFER_EXT, DepthRenderBuffer);
Driver->extGlRenderbufferStorage(GL_RENDERBUFFER_EXT,
GL_DEPTH_COMPONENT, ImageSize.Width,
ImageSize.Height);
}
#endif
}
//! destructor
COpenGLFBODepthTexture::~COpenGLFBODepthTexture()
{
if (DepthRenderBuffer && UseStencil)
glDeleteTextures(1, &DepthRenderBuffer);
else
Driver->extGlDeleteRenderbuffers(1, &DepthRenderBuffer);
if (StencilRenderBuffer && StencilRenderBuffer != DepthRenderBuffer)
glDeleteTextures(1, &StencilRenderBuffer);
}
//combine depth texture and rtt
bool COpenGLFBODepthTexture::attach(ITexture* renderTex)
{
if (!renderTex)
return false;
video::COpenGLFBOTexture* rtt = static_cast<video::COpenGLFBOTexture*>(renderTex);
rtt->bindRTT();
#ifdef GL_EXT_framebuffer_object
if (UseStencil)
{
// attach stencil texture to stencil buffer
Driver->extGlFramebufferTexture2D(GL_FRAMEBUFFER_EXT,
GL_STENCIL_ATTACHMENT_EXT,
GL_TEXTURE_2D,
StencilRenderBuffer,
0);
// attach depth texture to depth buffer
Driver->extGlFramebufferTexture2D(GL_FRAMEBUFFER_EXT,
GL_DEPTH_ATTACHMENT_EXT,
GL_TEXTURE_2D,
DepthRenderBuffer,
0);
}
else
{
// attach depth renderbuffer to depth buffer
Driver->extGlFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT,
GL_DEPTH_ATTACHMENT_EXT,
GL_RENDERBUFFER_EXT,
DepthRenderBuffer);
}
#endif
// check the status
if (!checkFBOStatus(Driver))
{
os::Printer::log("FBO incomplete");
return false;
}
rtt->DepthTexture=this;
grab(); // grab the depth buffer, not the RTT
rtt->unbindRTT();
return true;
}
//! Bind Render Target Texture
void COpenGLFBODepthTexture::bindRTT()
{
}
//! Unbind Render Target Texture
void COpenGLFBODepthTexture::unbindRTT()
{
}
bool checkFBOStatus(COpenGLDriver* Driver)
{
#ifdef GL_EXT_framebuffer_object
GLenum status = Driver->extGlCheckFramebufferStatus(GL_FRAMEBUFFER_EXT);
switch (status)
{
//Our FBO is perfect, return true
case GL_FRAMEBUFFER_COMPLETE_EXT:
return true;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
os::Printer::log("FBO has invalid read buffer", ELL_ERROR);
break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
os::Printer::log("FBO has invalid draw buffer", ELL_ERROR);
break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
os::Printer::log("FBO has one or several incomplete image attachments", ELL_ERROR);
break;
case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
os::Printer::log("FBO has one or several image attachments with different internal formats", ELL_ERROR);
break;
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
os::Printer::log("FBO has one or several image attachments with different dimensions", ELL_ERROR);
break;
// not part of fbo_object anymore, but won't harm as it is just a return value
#ifdef GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT
case GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT:
os::Printer::log("FBO has a duplicate image attachment", ELL_ERROR);
break;
#endif
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
os::Printer::log("FBO missing an image attachment", ELL_ERROR);
break;
#ifdef GL_EXT_framebuffer_multisample
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT:
os::Printer::log("FBO wrong multisample setup", ELL_ERROR);
break;
#endif
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
os::Printer::log("FBO format unsupported", ELL_ERROR);
break;
default:
break;
}
#endif
os::Printer::log("FBO error", ELL_ERROR);
return false;
}
} // end namespace video
} // end namespace irr
#endif // _IRR_COMPILE_WITH_OPENGL_
|
paupawsan/Irrlicht
|
4d1d0a34bdb9a2127a33cc9b630021582573455d
|
Prevent that X11 selects larger resolutions in fullscreen even when perfect fits are available.
|
diff --git a/changes.txt b/changes.txt
index 3033b4e..f3ca961 100644
--- a/changes.txt
+++ b/changes.txt
@@ -1,514 +1,516 @@
-----------------------------
Changes in 1.7.1 (17.02.2010)
+
+ - Prevent that X11 selects larger resolutions in fullscreen even when perfect fits are available.
- Ignore setResizable also on X11 when we're fullscreen to avoid messing up the window mode.
- Work around a crash when pressing ESC after closing a Messagebox (found by Acki)
- Prevent borland compile warnings in SColorHSL::FromRGB and in SVertexColorThresholdManipulator (found by mdeininger)
- Improve Windows version detection rules (Patch from brferreira)
- Make it compile on Borland compilers (thx to mdeininger)
- Make sure that CAnimatedMeshSceneNode::clone calls the virtual updateAbsolutePosition for the new object
- Fix that clones got dropped too often when SceneNodes without parent got cloned (found by Ulf)
- Make sure TAB is still recognized on X11 when shift+tab is pressed. This does also fix going to the previous tabstop on X11.
- Send EGET_ELEMENT_LEFT also when there won't be a new hovered element
- Update docs for EGET_ELEMENT_LEFT and EGET_ELEMENT_HOVERED
- Fix tooltips: Remove them when the element is hidden or removed (thx to seven for finding)
- Fix tooltips: Make (more) sure they don't get confused by gui-subelements
- Fix tooltips: Get faster relaunch times working
- Fix tooltips: Make sure hovered element is never the tooltip itself
- Fix string::remove which got in an endless loop when remove was called with an empty string (found and fixed by Ulf)
- Correctly release the GLSL shaders
- Make sure we only release an X11 atom when it was actually created
- Fix aabbox collision test, which not only broke the collision test routines, but also frustum culling, octree tests, etc.
- Fix compilation problem under OSX due to wrong glProgramParameteri usage
- mem leak in OBJ loader fixed
- Removed some default parameters to reduce ambigious situations
---------------------------
Changes in 1.7 (03.02.2010)
- Implement minimize and deminimize under OSX.
- Define sorting order for vector2d and vector3d in operators <, <=, > and >= to fix bugs 2783509 and 2783510. Operators order now by X,Y,Z and use float tolerances.
- Ogre mesh 32bit indices fixed.
- Fix tooltips for gui-elements with sub-element like IGUISpinBox (id: 2927079, found by ArakisTheKitsune)
- ITimer no longer stops when started twice
- wchar_t filesystem updates under Windows.
- Joystick POV fixed under Windows, ids fixed under OSX.
- Some updates to skinned mesh for better bones support and scaling animations.
- OSX supports external window id in creation parameters now.
- Fix bbox collision tests.
- Updates for win32 key handling
- new convenience method for flat plane creation.
- Sky dome and other meshes use VBOs by default now.
- Speed up b3d loading for files with many frames, material color flags and vertex color support enhanced.
- Add hasType to IGUIElement as a dynamic_cast substitute.
- Add another parameter to IGUISkin::draw3DWindowBackground to allow getting the client area without actually drawing
- Add function getClientRect to IGUIWindow for getting the draw-able area
- Fix bug that menus on IGUIWindows with titlebar got drawn too high (id: 2714400)
- Renamed OctTree to Octree
- Allow getting a ConstIterator from a non-const core:list
- Add swap functions to irrMath and to the core classes.
- Deprecate map::isEmpty() and replace it with map::empty() to make it similar to other base classes.
- Allow to set the logging level already in SIrrlichtCreationParameters.
- Add clearSystemMessages to devices (implemented only for Linux and Win32 so far).
- Support changing the render window from beginScene also with OpenGL driver.
- Add getMaterial2D which allows to alter the 2d render state settings, such as filtering, anti-aliasing, thickness, etc.
- Fix incorrect cursorpos for resizable windows on Windows Vista (found and patched by buffer)
- Change the beginScene window parameter from void* to SExposedVideoData&. This will allow to manage contexts for OpenGL at some point.
- Add bzip2 and LZMA decompression modes for zip loader.
- Add OBJ_TEXTURE_PATH and B3D_TEXTURE_PATH to SceneParameters to allow setting texture-paths for obj and b3d.
- Irrlicht keeps now filenames additionally to the internally used names, thereby fixing some problems with uppercase-filenames on Linux.
- Bugfix: Mousewheel no longer sends EMIE_MOUSE_WHEEL messages twice on Linux.
- Use latest jpeglib
- refactoring: E_ATTRIBUTE_TYPE and IAttribute have now own headers
- CStringWArrayAttribute speedup
- SceneNodeAnimatorFollowSpline can now loop and pingpong
- Meshviewer.example got some fast-scale buttons.
- Support AES-encrypted zip files. Should work with 128, 196, and 256 bit AES. This addition also adds a new PRNG, SHA, and other algorithms to the engine, though no interface is yet added for them. The implementation of the encryption algorithms is provided by Dr Brian Gladman.
- flattenFilename and getAbsolutePath fixed and properly added at several places.
- Added geometry shaders for OpenGL. A first version of the code was submitted by Matthew Kielan (devsh).
- Bugfix: irrArray should no longer crash when using other allocators.
- Add MaterialViewer example.
- Texture activation now back in setMaterial, which simplifies writing external material renderers (OpenGL only).
- Checkbox uses now disabled text color when disabled.
- Changed colors for window-title caption to keep them readable when not active.
- Draw sub-menus to left side if they would be outside main-window otherwise.
- Give ListBox better defaults for the ScrollBar stepsizes.
- Double and triple click events now for each mouse-button. Old events for that got removed.
- Fix adding archives twice, which caused multiple archives of the same name and type covering each other. This one required a texture name change from using backslashes to slashes under Windows.
- Give access to texture mipmaps. You can provide custom mipmap textures upon generation, regeneration, and locking.
Make sure the provided data is large enough and covers all miplevels. Also the returned pointer (from lock) will only cover the smaller data of the mipmap level dimension chosen (level 0 is the original texture).
- Separate TextureWrap mode into U and V fields
- Add mirror texture wrap modes
- windows show now active/inactive state
- remove unneeded drop/grab calls found by manik_sheeri
- fix rounding problem in IGUIElements which have EGUIA_SCALE alignments.
- MessageBox supports now automatic resizing and images.
Deprecated EGDS_MESSAGE_BOX_WIDTH and EGDS_MESSAGE_BOX_HEIGHT
- Let maya-cam animator react on a setTarget call to the camera which happened outside it's own control
- New contextmenue features:
automatic checking for checked flag.
close handling now customizable
serialization can handle incomplete xml's
setEventParent now in public interface
New function findItemWithCommandId
New function insertItem
- new vector3d::getSphericalCoordinateAngles method.
- new triangle3d::isTotalOutsideBox method.
- Newly introduced VertexManipulator interface. This allows for very easy creation of vertex manipulation algorithms. Several manipulators, e.g. vertex color changer and transformation algorithms are already available.
- createMeshWith1TCoords avoids vertex duplication
- getRotation now handles matrices with scaling as well
- Ogre format animations now supported.
- irrArray: Fixed issues with push_front and reallocation
Changed behavior for set_pointer and clear, when free_when_destroyed is false
- NPK (Nebula device archive) reader added, it's an uncompressed PAK-like format
- SSkinMeshBuffer::MoveTo* methods renamed to convertTo*
- Multiple Render Target (MRT) support added, including some enhanced blend features where supported
- Directory changing fixed for virtual file systems (Archives etc)
- Fix texture matrix init in scene manager and driver
- More draw2dimage support in software drivers
- Sphere node now properly chooses a good tesselation based on the parameters
- Active camera not registered twice anymore
- Parallax/normal map shader rotation bug under OpenGL fixed
- bump map handling for obj files fixed
- Fog serialization added
- New context menu features added
- Bounding Box updates for skinned meshes fixed
- The current FPS for an animated scene node can be queried now, added some variables to serialization
- Scrollbars fixed
- Fixed 2d vertex primitive method to correctly handle transparency
- Fullscreen handling has been enhanced for Windows, now proper resolution is restored on Alt-Tab etc.
- Cameras can now be added to the scene node without automatically activating them
Clone method added
- New video driver method getMaxTextureSize
- PAK archive reader fixed
- TRANSPARENT_ALPHA_CHANNEL_REF uses modulate to enable lighting
- LIGHTMAP_ADD now always uses add operator
- Some Unicode file system fixes
- destructor of irrString not virtual anymore, please don't derive from irrString
Some new methods added, for searching and splitting
Assignment operator optimized
- new lightness method for SColor
- draw3DTriangle now renders filled polygons, old behavior can be achieved by setting EMT_WIREFRAME
-----------------------------
Changes in 1.6.1 (13.01.2010)
- Fix pingpong for CSceneNodeAnimatorFlyStraight (found by gbox)
- Fix bug with IGUIEditBox where the cursor position is reset on text change.
- Make sure the window top-left corner on Windows is not negative on start so that Windows sytem-menu is always visible.
- Fix problem that the window did sometimes not get the keyboard focus in X11 in fullscreen. Add more debug output in case focus grabbing goes wrong.
- Fix screensize in videodriver when we didn't get the requested window size. This also prevents that gui-clicks are no longer synchronized with gui-drawing and elements can't be hit anymore.
- Bugfix: Prevent a crash when getTypeName was called for the guienvironment. EGUIET_ELEMENT got changed for this.
- Bugfix: Horizontal centered font with linebreaks draw now all lines. For example multiline TextSceneNodes work again.
- Bugfix: spinbox can no longer get in an endless loop due to floating point rounding error (found by slavik262)
- !!API change!! Disabled AntiAliasing of Lines in material default
Please enable this manually per material when sure that it won't lead to SW rendering.
- IGUIComboBox: clicking on the statictext displaying the active selection does now close and open listbox correctly. (Bug found by Reiko)
- Scrollbuttons in IGUITabControl adapt now to tab-height.
- Fix texturing of cylinder mesh
- Fix modal dialog position (found by LoneBoco: http://sourceforge.net/tracker/?func=detail&aid=2900266&group_id=74339&atid=540676)
- Fix DMF loading
- Fixing left+right special keys (ctrl, shift, alt) on Win32 (thanks to pc0de for good patch-ideas).
- Make stringarrays for enums in IGUISkin a little safer
- Add support for keys KEY_PRINT, KEY_HOME (on numpad) and KEY_NUMLOCK on Linux.
- Fix material handling in createMeshWith1TCoords
- Fix another (OldValue == NewValue) before drop()/grap(), this time in CTextureAttribute::setTexture.
- Fix LIGHTMAP_LIGHTING for D3D drivers.
- AntiAliasing disabled for debug render elements.
- Bugfix: CGUIToolBar::addButton does no longer mess up when no image is set and does now actually work with the text.
- Fix ninja animation range which got messed up a little when b3d animations got fixed (thx gbox for finding)
---------------------------
Changes in 1.6 (23.09.2009)
- Added IFileSystem::createEmptyFileList, exposed IFileList::sort, addItem and added getID
- Fix MAKE_IRR_ID so it can be used from outside the irr namespace (Micha's patch)
- Renamed some methods in ISkinnedMesh to match the official Irrlicht naming scheme according to createXXX()
- Change debug data to draw using lines instead of arrows, which is much faster. Patch by pc0de
- Fix a bug with FPS camera animator causing stutters. Patch by FuzzYspo0N
- Fix scrolling controls in CGUITabControl
- Fix a bug when getting optimal texture size in D3D drivers, by Jetro Lauha (tonic)
- Added EGDS_TITLEBARTEXT_DISTANCE_X and EGDS_TITLEBARTEXT_DISTANCE_Y to GUI, submitted by FuzzYspo0N
- Fix for UFT8 filenames displayed in file dialog, patch by MadHyde.
- Added const method for array::binary_search, potentially slow as it doesn't sort the list!
- Add support for scaling button images.
- Irrlicht can now come with multiple device types compiled in, the device to use is selected by SIrrlichtCreationParameters.DeviceType. This defaults to EIDT_BEST which automatically select the best device available starting with native, then X11, SDL and finally the console.
- Added support for EXP2 fog distribution. This required a change in the setFog parameters where now an enum value instead of the bool linear is given.
- IFileSystem changes:
- Renamed the following functions-
IFileArchive::getArchiveType to getType
IFileSystem::registerFileArchive to addFileArchive
IFileSystem::unregisterFileArchive to removeFileArchive
IFileArchive::openFile to createAndOpenFile
- New enum, E_FILE_ARCHIVE_TYPE. getType on IArchiveLoader and IFileArchive now both return this.
- IFileSystem::addFileArchive takes a parameter to specify the archive type rather always using the file extension. IFileSystem::addZipFileArchive, addFolderFileArchive and addPakFileArchive now use this but these functions are now marked as deprecated. Users should now use addFileArchive instead.
- Added TAR archive loader.
- The ZIP archive loader can now load gzip files, combined with the TAR loader this means Irrlicht now has native support for .tar.gz
Currently this must be done in two calls, for example:
fileSystem->addFileArchive("path/to/myArchive.tar.gz");
fileSystem->addFileArchive("myArchive.tar");
- Fix highlighting in IGUIEditBox where kerning pairs are used in the font. For example in future italic, OS or other custom fonts.
- IOSOperator::getTextFromClipboard returns now const c8* instead of c8*
- Support for copy&paste on linux (X11) added (fixing bug 2804014 found by Pan)
- bugfix for 2795321 found by egrath: Don't rely anymore on broken XkbSetDetectableAutoRepeat.
- bugfix: CMountPointReader::openFile no longer returns true for empty files. Corresponding test added.
- Direct3D now also uses screen coordinates in 2d mode, just like OpenGL. This means that screen coords are going from 0..ScreenWidth and 0..ScreenHeight instead of -1..1.
- ALT+F4 keypress now closes Windows SDL device
- Allow Direct3D drivers in SDL, patch by Halifax
- Added compiler error when attempting to compile with VC6.
- Use setWindowTextA in Windows device for WIN64 platform, posted by veegun
- ELL_ERROR log events are now created when shaders fail to compile or link, reported by Halan
- irrList now uses irrAllocator, fixed by Nox
- Added IGUIWindow::setDraggable and IGUIWindow::isDraggable, by Nox
- Added SGI RGB file reader by Gary Conway, for loading Silicon Graphics .rgb, .rgba, .sgi, .int and .inta textures
- Renamed setResizeAble to setResizable
- Added new device method minimizeWindow which minimizes the window (just as if the minimize button has been clicked).
- SkyDome is now serialized correctly
- Added PLY mesh reader and writer
- Ensure ListBox on combo box doesn't hang off the bottom of the GUI root, by Matthias Specht
- Made IGUIElements recalculate clipping rectangle after setNotClipped, reported by Aelis440
- Bug fix for the combo box where it showed white text instead of skin colour before being focused, fix posted by drewbacca
- EGDS_MESSAGE_BOX_HEIGHT is now honoured, bug reported by Spkka
- Fixed a bug in the edit box where events are sometimes sent to a null parent, reported by Sudi.
- Coordinate system fix for OpenGL in SDL device
- Added generic console device. You can now use Irrlicht to create and manipuate graphics on a shell where no graphics hardware
or windowing system is available. To enable it uncomment #define _IRR_USE_CONSOLE_DEVICE_ in IrrCompileConfig.h
- The console device can now present images from the software drivers and display them as ASCII art in the console
- By default it replaces the default font in the skin, to prevent fonts from being huge.
- Fixed problems with changing cursor visibility while mouse is pressed on windows
- Allow control of background drawing in listbox
- Allow control of drawing background and titlebar in windows
- Improved window serialization
- Add mouse events EMIE_MOUSE_DOUBLE_CLICK and EMIE_MOUSE_TRIPLE_CLICK (thx to Ulf for patch proposal)
- Set "ButtonStates" for mouse events also on Linux (was only for Windows formerly)
- Add Shift+Control states to mouse event
- bugfix (2003238): serialize modal screens
- allow stacking modal screens
- allowing hiding modals
- replace many IsVisible checks with virtual isVisible() checks in IGUIElement
- bugfix: reset selected row when clearing CGUITable
- adding events EGET_EDITBOX_CHANGED and EGET_EDITBOX_MARKING_CHANGED
- prevent editbox from recalculating its textbreaking each frame
- let spinbox react on each textchange without waiting for enter to prevent getting value changes without corresponding EGET_SPINBOX_CHANGED events.
- new test for zipreader
- prevent dropping objects accidentally in many set functions
- Reversed change in vector3d::normalize.
Works now again as documented and a corresponding test has been added.
Does fix bug 2770709 (https://sourceforge.net/tracker/?func=detail&aid=2770709&group_id=74339&atid=540676)
- Animations can now be paused by setting the fps to 0.
- Avoid fp-precision problem in getPickedNodeBB (see also http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=33838&highlight=).
This change might also fix the problem with picking nodes found by aanderse (http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=32890&highlight=)
- implemented isALoadableFileFormat ( File *file ) for the Archive Loader
- PixelBlend16 and PixelBlend16_simd are working for the new rules.
- bugfix. CLightSceneNode didn't correctly update it's attributes
- vector template and equals tests
also set the equal test for s32 to behave like the f32 routine.
The function equals always implements a weak test.
that means a tolerance MUST always be used if you use the equal function. default is 1.
- VideoDriver drawPixel
The HW renderes are using the alpha components for blending.
The Software Renderes and image loaders are using CImage::setPixel copy.
so setPixel is engaged to either blends or copy the pixel
default: false
- Burningvideo
added RenderMaterial EMT_SPHERE_MAP
pushed burningsvideo to 0.43
added RenderMaterial EMT_REFLECTION_2_LAYER
pushed burningsvideo to 0.44
set EMT_TRANSPARENT_ALPHA_CHANNEL_REF
to use AlphaRef 0.5 like Direct3D
One Note: in OpenGL there is know difference between sphere_map and reflection layer
both using GL_TEXTURE_GEN_MODE GL_SPHERE_MAP, whereas in d3d one time using camera_normal
on sphere and reflection on refletcion_layer.
The visual difference is that on sphere map the "image is not moving" when you rotate the
viewer. For Burning i took the opengl visual. always moving
- rename quake3 SEntity to IEntity to be confom with IShader
- fixed createMeshWith2TCoords, normals were missing during copy.
- added
//! Creates a copy of the mesh, which will only consist of S3DVertex vertices.
IMesh* CMeshManipulator::createMeshWith1TCoords(IMesh* mesh) const
- added io::IFileSystem* CSceneManager::getFileSystem()
- added virtual const c8* ISceneManager::getAnimatorTypeName(ESCENE_NODE_ANIMATOR_TYPE type);
- added CSceneNodeAnimatorFlyCircle::radiusEllipsoid.
if radiusEllipsoid == 0 the default circle animation is done
else radiusEllipsoid forms the b-axe of the ellipsoid.
-> gummiball bouncing
- added ISceneManager::createFlyStraightAnimator variable bool ping-pong
used in loop mode to device if start from beginning ( default ) or make ping-pong
-> straight bouncing
- changed IFileSystem::registerFileArchive
remove the index of the hierarchy and added a new interface method
//! move the hirarchy of the filesystem. moves sourceIndex relative up or down
virtual bool moveFileArchive( u32 sourceIndex, s32 relative ) = 0;
- bugfix and changes in SViewFrustum::SViewFrustum
wrong size of Matrices copy.
renamed E_TRANSFORMATION_STATE_2 to E_TRANSFORMATION_STATE_FRUSTUM
therefore also changed SViewFrustum::setTransformState to not tap
in the pitfall again of wrong memory...
- moved
//! EMT_ONETEXTURE_BLEND: has BlendFactor Alphablending
inline bool textureBlendFunc_hasAlpha ( E_BLEND_FACTOR factor ) const
from the material renderes ( 3x declared ) to SMaterial.h
- updated managed light example to use standard driver selection
- BurningsVideo
- LightModel reworked.
Point Light & Direction Light works for Diffuse Color as expected
Specular and Fog still have problems ( needs new pixel shader )
pushed burningsvideo to 0.42 for this major step
- removed obsolete matrix transformations
renamed E_TRANSFORMATION_STATE_2 to E_TRANSFORMATION_STATE_BURNING
diff --git a/source/Irrlicht/CIrrDeviceLinux.cpp b/source/Irrlicht/CIrrDeviceLinux.cpp
index 614d8b9..ec241e8 100644
--- a/source/Irrlicht/CIrrDeviceLinux.cpp
+++ b/source/Irrlicht/CIrrDeviceLinux.cpp
@@ -1,800 +1,805 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CIrrDeviceLinux.h"
#ifdef _IRR_COMPILE_WITH_X11_DEVICE_
#include <stdio.h>
#include <stdlib.h>
#include <sys/utsname.h>
#include <time.h>
#include "IEventReceiver.h"
#include "os.h"
#include "CTimer.h"
#include "irrString.h"
#include "Keycodes.h"
#include "COSOperator.h"
#include "CColorConverter.h"
#include "SIrrCreationParameters.h"
#include <X11/XKBlib.h>
#include <X11/Xatom.h>
#if defined _IRR_COMPILE_WITH_JOYSTICK_EVENTS_
#include <fcntl.h>
#include <unistd.h>
#ifdef __FREE_BSD_
#include <sys/joystick.h>
#else
// linux/joystick.h includes linux/input.h, which #defines values for various KEY_FOO keys.
// These override the irr::KEY_FOO equivalents, which stops key handling from working.
// As a workaround, defining _INPUT_H stops linux/input.h from being included; it
// doesn't actually seem to be necessary except to pull in sys/ioctl.h.
#define _INPUT_H
#include <sys/ioctl.h> // Would normally be included in linux/input.h
#include <linux/joystick.h>
#undef _INPUT_H
#endif
#endif // _IRR_COMPILE_WITH_JOYSTICK_EVENTS_
namespace irr
{
namespace video
{
IVideoDriver* createOpenGLDriver(const SIrrlichtCreationParameters& params,
io::IFileSystem* io, CIrrDeviceLinux* device);
}
} // end namespace irr
namespace
{
Atom X_ATOM_CLIPBOARD;
Atom X_ATOM_TARGETS;
Atom X_ATOM_UTF8_STRING;
Atom X_ATOM_TEXT;
};
namespace irr
{
const char* wmDeleteWindow = "WM_DELETE_WINDOW";
//! constructor
CIrrDeviceLinux::CIrrDeviceLinux(const SIrrlichtCreationParameters& param)
: CIrrDeviceStub(param),
#ifdef _IRR_COMPILE_WITH_X11_
display(0), visual(0), screennr(0), window(0), StdHints(0), SoftwareImage(0),
#ifdef _IRR_COMPILE_WITH_OPENGL_
glxWin(0),
Context(0),
#endif
#endif
Width(param.WindowSize.Width), Height(param.WindowSize.Height),
WindowHasFocus(false), WindowMinimized(false),
UseXVidMode(false), UseXRandR(false), UseGLXWindow(false),
ExternalWindow(false), AutorepeatSupport(0)
{
#ifdef _DEBUG
setDebugName("CIrrDeviceLinux");
#endif
// print version, distribution etc.
// thx to LynxLuna for pointing me to the uname function
core::stringc linuxversion;
struct utsname LinuxInfo;
uname(&LinuxInfo);
linuxversion += LinuxInfo.sysname;
linuxversion += " ";
linuxversion += LinuxInfo.release;
linuxversion += " ";
linuxversion += LinuxInfo.version;
linuxversion += " ";
linuxversion += LinuxInfo.machine;
Operator = new COSOperator(linuxversion.c_str(), this);
os::Printer::log(linuxversion.c_str(), ELL_INFORMATION);
// create keymap
createKeyMap();
// create window
if (CreationParams.DriverType != video::EDT_NULL)
{
// create the window, only if we do not use the null device
if (!createWindow())
return;
}
// create cursor control
CursorControl = new CCursorControl(this, CreationParams.DriverType == video::EDT_NULL);
// create driver
createDriver();
if (!VideoDriver)
return;
createGUIAndScene();
}
//! destructor
CIrrDeviceLinux::~CIrrDeviceLinux()
{
#ifdef _IRR_COMPILE_WITH_X11_
if (StdHints)
XFree(StdHints);
// Disable cursor and free it later on
CursorControl->setVisible(false);
if (display)
{
#ifdef _IRR_COMPILE_WITH_OPENGL_
if (Context)
{
if (glxWin)
{
if (!glXMakeContextCurrent(display, None, None, NULL))
os::Printer::log("Could not release glx context.", ELL_WARNING);
}
else
{
if (!glXMakeCurrent(display, None, NULL))
os::Printer::log("Could not release glx context.", ELL_WARNING);
}
glXDestroyContext(display, Context);
if (glxWin)
glXDestroyWindow(display, glxWin);
}
#endif // #ifdef _IRR_COMPILE_WITH_OPENGL_
// Reset fullscreen resolution change
switchToFullscreen(true);
if (SoftwareImage)
XDestroyImage(SoftwareImage);
if (!ExternalWindow)
{
XDestroyWindow(display,window);
XCloseDisplay(display);
}
}
if (visual)
XFree(visual);
#endif // #ifdef _IRR_COMPILE_WITH_X11_
#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_)
for(u32 joystick = 0; joystick < ActiveJoysticks.size(); ++joystick)
{
if(ActiveJoysticks[joystick].fd >= 0)
{
close(ActiveJoysticks[joystick].fd);
}
}
#endif
}
#if defined(_IRR_COMPILE_WITH_X11_) && defined(_DEBUG)
int IrrPrintXError(Display *display, XErrorEvent *event)
{
char msg[256];
char msg2[256];
snprintf(msg, 256, "%d", event->request_code);
XGetErrorDatabaseText(display, "XRequest", msg, "unknown", msg2, 256);
XGetErrorText(display, event->error_code, msg, 256);
os::Printer::log("X Error", msg, ELL_WARNING);
os::Printer::log("From call ", msg2, ELL_WARNING);
return 0;
}
#endif
bool CIrrDeviceLinux::switchToFullscreen(bool reset)
{
if (!CreationParams.Fullscreen)
return true;
if (reset)
{
#ifdef _IRR_LINUX_X11_VIDMODE_
if (UseXVidMode && CreationParams.Fullscreen)
{
XF86VidModeSwitchToMode(display, screennr, &oldVideoMode);
XF86VidModeSetViewPort(display, screennr, 0, 0);
}
#endif
#ifdef _IRR_LINUX_X11_RANDR_
if (UseXRandR && CreationParams.Fullscreen)
{
XRRScreenConfiguration *config=XRRGetScreenInfo(display,DefaultRootWindow(display));
XRRSetScreenConfig(display,config,DefaultRootWindow(display),oldRandrMode,oldRandrRotation,CurrentTime);
XRRFreeScreenConfigInfo(config);
}
#endif
return true;
}
getVideoModeList();
#if defined(_IRR_LINUX_X11_VIDMODE_) || defined(_IRR_LINUX_X11_RANDR_)
s32 eventbase, errorbase;
s32 bestMode = -1;
#endif
#ifdef _IRR_LINUX_X11_VIDMODE_
if (XF86VidModeQueryExtension(display, &eventbase, &errorbase))
{
// enumerate video modes
s32 modeCount;
XF86VidModeModeInfo** modes;
XF86VidModeGetAllModeLines(display, screennr, &modeCount, &modes);
// find fitting mode
for (s32 i = 0; i<modeCount; ++i)
{
if (bestMode==-1 && modes[i]->hdisplay >= Width && modes[i]->vdisplay >= Height)
bestMode = i;
else if (bestMode!=-1 &&
modes[i]->hdisplay >= Width &&
modes[i]->vdisplay >= Height &&
- modes[i]->hdisplay < modes[bestMode]->hdisplay &&
- modes[i]->vdisplay < modes[bestMode]->vdisplay)
+ modes[i]->hdisplay <= modes[bestMode]->hdisplay &&
+ modes[i]->vdisplay <= modes[bestMode]->vdisplay)
bestMode = i;
}
if (bestMode != -1)
{
- os::Printer::log("Starting fullscreen mode...", ELL_INFORMATION);
+ os::Printer::log("Starting vidmode fullscreen mode...", ELL_INFORMATION);
os::Printer::log("hdisplay: ", core::stringc(modes[bestMode]->hdisplay).c_str(), ELL_INFORMATION);
os::Printer::log("vdisplay: ", core::stringc(modes[bestMode]->vdisplay).c_str(), ELL_INFORMATION);
+
XF86VidModeSwitchToMode(display, screennr, modes[bestMode]);
XF86VidModeSetViewPort(display, screennr, 0, 0);
UseXVidMode=true;
}
else
{
os::Printer::log("Could not find specified video mode, running windowed.", ELL_WARNING);
CreationParams.Fullscreen = false;
}
XFree(modes);
}
else
#endif
#ifdef _IRR_LINUX_X11_RANDR_
if (XRRQueryExtension(display, &eventbase, &errorbase))
{
s32 modeCount;
XRRScreenConfiguration *config=XRRGetScreenInfo(display,DefaultRootWindow(display));
XRRScreenSize *modes=XRRConfigSizes(config,&modeCount);
for (s32 i = 0; i<modeCount; ++i)
{
if (bestMode==-1 && (u32)modes[i].width >= Width && (u32)modes[i].height >= Height)
bestMode = i;
else if (bestMode!=-1 &&
(u32)modes[i].width >= Width &&
(u32)modes[i].height >= Height &&
- modes[i].width < modes[bestMode].width &&
- modes[i].height < modes[bestMode].height)
+ modes[i].width <= modes[bestMode].width &&
+ modes[i].height <= modes[bestMode].height)
bestMode = i;
}
if (bestMode != -1)
{
+ os::Printer::log("Starting randr fullscreen mode...", ELL_INFORMATION);
+ os::Printer::log("width: ", core::stringc(modes[bestMode].width).c_str(), ELL_INFORMATION);
+ os::Printer::log("height: ", core::stringc(modes[bestMode].height).c_str(), ELL_INFORMATION);
+
XRRSetScreenConfig(display,config,DefaultRootWindow(display),bestMode,oldRandrRotation,CurrentTime);
UseXRandR=true;
}
XRRFreeScreenConfigInfo(config);
}
else
#endif
{
os::Printer::log("VidMode or RandR extension must be installed to allow Irrlicht "
"to switch to fullscreen mode. Running in windowed mode instead.", ELL_WARNING);
CreationParams.Fullscreen = false;
}
return CreationParams.Fullscreen;
}
#if defined(_IRR_COMPILE_WITH_X11_)
void IrrPrintXGrabError(int grabResult, const c8 * grabCommand )
{
if ( grabResult == GrabSuccess )
{
// os::Printer::log(grabCommand, ": GrabSuccess", ELL_INFORMATION);
return;
}
switch ( grabResult )
{
case AlreadyGrabbed:
os::Printer::log(grabCommand, ": AlreadyGrabbed", ELL_WARNING);
break;
case GrabNotViewable:
os::Printer::log(grabCommand, ": GrabNotViewable", ELL_WARNING);
break;
case GrabFrozen:
os::Printer::log(grabCommand, ": GrabFrozen", ELL_WARNING);
break;
case GrabInvalidTime:
os::Printer::log(grabCommand, ": GrabInvalidTime", ELL_WARNING);
break;
default:
os::Printer::log(grabCommand, ": grab failed with unknown problem", ELL_WARNING);
break;
}
}
#endif
bool CIrrDeviceLinux::createWindow()
{
#ifdef _IRR_COMPILE_WITH_X11_
#ifdef _DEBUG
os::Printer::log("Creating X window...", ELL_INFORMATION);
XSetErrorHandler(IrrPrintXError);
#endif
display = XOpenDisplay(0);
if (!display)
{
os::Printer::log("Error: Need running XServer to start Irrlicht Engine.", ELL_ERROR);
if (XDisplayName(0)[0])
os::Printer::log("Could not open display", XDisplayName(0), ELL_ERROR);
else
os::Printer::log("Could not open display, set DISPLAY variable", ELL_ERROR);
return false;
}
screennr = DefaultScreen(display);
switchToFullscreen();
#ifdef _IRR_COMPILE_WITH_OPENGL_
GLXFBConfig glxFBConfig;
int major, minor;
bool isAvailableGLX=false;
if (CreationParams.DriverType==video::EDT_OPENGL)
{
isAvailableGLX=glXQueryExtension(display,&major,&minor);
if (isAvailableGLX && glXQueryVersion(display, &major, &minor))
{
#ifdef GLX_VERSION_1_3
typedef GLXFBConfig * ( * PFNGLXCHOOSEFBCONFIGPROC) (Display *dpy, int screen, const int *attrib_list, int *nelements);
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
PFNGLXCHOOSEFBCONFIGPROC glxChooseFBConfig = (PFNGLXCHOOSEFBCONFIGPROC)glXGetProcAddress(reinterpret_cast<const GLubyte*>("glXChooseFBConfig"));
#else
PFNGLXCHOOSEFBCONFIGPROC glxChooseFBConfig=glXChooseFBConfig;
#endif
if (major==1 && minor>2 && glxChooseFBConfig)
{
// attribute array for the draw buffer
int visualAttrBuffer[] =
{
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_RED_SIZE, 4,
GLX_GREEN_SIZE, 4,
GLX_BLUE_SIZE, 4,
GLX_ALPHA_SIZE, CreationParams.WithAlphaChannel?1:0,
GLX_DEPTH_SIZE, CreationParams.ZBufferBits, //10,11
GLX_DOUBLEBUFFER, CreationParams.Doublebuffer?True:False,
GLX_STENCIL_SIZE, CreationParams.Stencilbuffer?1:0,
#if defined(GLX_VERSION_1_4) && defined(GLX_SAMPLE_BUFFERS) // we need to check the extension string!
GLX_SAMPLE_BUFFERS, 1,
GLX_SAMPLES, CreationParams.AntiAlias, // 18,19
#elif defined(GLX_ARB_multisample)
GLX_SAMPLE_BUFFERS_ARB, 1,
GLX_SAMPLES_ARB, CreationParams.AntiAlias, // 18,19
#elif defined(GLX_SGIS_multisample)
GLX_SAMPLE_BUFFERS_SGIS, 1,
GLX_SAMPLES_SGIS, CreationParams.AntiAlias, // 18,19
#endif
GLX_STEREO, CreationParams.Stereobuffer?True:False,
None
};
GLXFBConfig *configList=0;
int nitems=0;
if (CreationParams.AntiAlias<2)
{
visualAttrBuffer[17] = 0;
visualAttrBuffer[19] = 0;
}
// first round with unchanged values
{
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
if (!configList && CreationParams.AntiAlias)
{
while (!configList && (visualAttrBuffer[19]>1))
{
visualAttrBuffer[19] -= 1;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
}
if (!configList)
{
visualAttrBuffer[17] = 0;
visualAttrBuffer[19] = 0;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
if (configList)
{
os::Printer::log("No FSAA available.", ELL_WARNING);
CreationParams.AntiAlias=0;
}
else
{
//reenable multisampling
visualAttrBuffer[17] = 1;
visualAttrBuffer[19] = CreationParams.AntiAlias;
}
}
}
}
// Next try with flipped stencil buffer value
// If the first round was with stencil flag it's now without
// Other way round also makes sense because some configs
// only have depth buffer combined with stencil buffer
if (!configList)
{
if (CreationParams.Stencilbuffer)
os::Printer::log("No stencilbuffer available, disabling stencil shadows.", ELL_WARNING);
CreationParams.Stencilbuffer = !CreationParams.Stencilbuffer;
visualAttrBuffer[15]=CreationParams.Stencilbuffer?1:0;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
if (!configList && CreationParams.AntiAlias)
{
while (!configList && (visualAttrBuffer[19]>1))
{
visualAttrBuffer[19] -= 1;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
}
if (!configList)
{
visualAttrBuffer[17] = 0;
visualAttrBuffer[19] = 0;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
if (configList)
{
os::Printer::log("No FSAA available.", ELL_WARNING);
CreationParams.AntiAlias=0;
}
else
{
//reenable multisampling
visualAttrBuffer[17] = 1;
visualAttrBuffer[19] = CreationParams.AntiAlias;
}
}
}
}
// Next try without double buffer
if (!configList && CreationParams.Doublebuffer)
{
os::Printer::log("No doublebuffering available.", ELL_WARNING);
CreationParams.Doublebuffer=false;
visualAttrBuffer[13] = GLX_DONT_CARE;
CreationParams.Stencilbuffer = false;
visualAttrBuffer[15]=0;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
if (!configList && CreationParams.AntiAlias)
{
while (!configList && (visualAttrBuffer[19]>1))
{
visualAttrBuffer[19] -= 1;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
}
if (!configList)
{
visualAttrBuffer[17] = 0;
visualAttrBuffer[19] = 0;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
if (configList)
{
os::Printer::log("No FSAA available.", ELL_WARNING);
CreationParams.AntiAlias=0;
}
else
{
//reenable multisampling
visualAttrBuffer[17] = 1;
visualAttrBuffer[19] = CreationParams.AntiAlias;
}
}
}
}
if (configList)
{
glxFBConfig=configList[0];
XFree(configList);
UseGLXWindow=true;
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
typedef XVisualInfo * ( * PFNGLXGETVISUALFROMFBCONFIGPROC) (Display *dpy, GLXFBConfig config);
PFNGLXGETVISUALFROMFBCONFIGPROC glxGetVisualFromFBConfig= (PFNGLXGETVISUALFROMFBCONFIGPROC)glXGetProcAddress(reinterpret_cast<const GLubyte*>("glXGetVisualFromFBConfig"));
if (glxGetVisualFromFBConfig)
visual = glxGetVisualFromFBConfig(display,glxFBConfig);
#else
visual = glXGetVisualFromFBConfig(display,glxFBConfig);
#endif
}
}
else
#endif
{
// attribute array for the draw buffer
int visualAttrBuffer[] =
{
GLX_RGBA, GL_TRUE,
GLX_RED_SIZE, 4,
GLX_GREEN_SIZE, 4,
GLX_BLUE_SIZE, 4,
GLX_ALPHA_SIZE, CreationParams.WithAlphaChannel?1:0,
GLX_DEPTH_SIZE, CreationParams.ZBufferBits,
GLX_STENCIL_SIZE, CreationParams.Stencilbuffer?1:0, // 12,13
// The following attributes have no flags, but are
// either present or not. As a no-op we use
// GLX_USE_GL, which is silently ignored by glXChooseVisual
CreationParams.Doublebuffer?GLX_DOUBLEBUFFER:GLX_USE_GL, // 14
CreationParams.Stereobuffer?GLX_STEREO:GLX_USE_GL, // 15
None
};
visual=glXChooseVisual(display, screennr, visualAttrBuffer);
if (!visual)
{
if (CreationParams.Stencilbuffer)
os::Printer::log("No stencilbuffer available, disabling.", ELL_WARNING);
CreationParams.Stencilbuffer = !CreationParams.Stencilbuffer;
visualAttrBuffer[13]=CreationParams.Stencilbuffer?1:0;
visual=glXChooseVisual(display, screennr, visualAttrBuffer);
if (!visual && CreationParams.Doublebuffer)
{
os::Printer::log("No doublebuffering available.", ELL_WARNING);
CreationParams.Doublebuffer=false;
visualAttrBuffer[14] = GLX_USE_GL;
visual=glXChooseVisual(display, screennr, visualAttrBuffer);
}
}
}
}
else
os::Printer::log("No GLX support available. OpenGL driver will not work.", ELL_WARNING);
}
// don't use the XVisual with OpenGL, because it ignores all requested
// properties of the CreationParams
else if (!visual)
#endif // _IRR_COMPILE_WITH_OPENGL_
// create visual with standard X methods
{
os::Printer::log("Using plain X visual");
XVisualInfo visTempl; //Template to hold requested values
int visNumber; // Return value of available visuals
visTempl.screen = screennr;
// ARGB visuals should be avoided for usual applications
visTempl.depth = CreationParams.WithAlphaChannel?32:24;
while ((!visual) && (visTempl.depth>=16))
{
visual = XGetVisualInfo(display, VisualScreenMask|VisualDepthMask,
&visTempl, &visNumber);
visTempl.depth -= 8;
}
}
if (!visual)
{
os::Printer::log("Fatal error, could not get visual.", ELL_ERROR);
XCloseDisplay(display);
display=0;
return false;
}
#ifdef _DEBUG
else
os::Printer::log("Visual chosen: ", core::stringc(static_cast<u32>(visual->visualid)).c_str(), ELL_INFORMATION);
#endif
// create color map
Colormap colormap;
colormap = XCreateColormap(display,
RootWindow(display, visual->screen),
visual->visual, AllocNone);
attributes.colormap = colormap;
attributes.border_pixel = 0;
attributes.event_mask = StructureNotifyMask | FocusChangeMask | ExposureMask;
if (!CreationParams.IgnoreInput)
attributes.event_mask |= PointerMotionMask |
ButtonPressMask | KeyPressMask |
ButtonReleaseMask | KeyReleaseMask;
if (!CreationParams.WindowId)
{
// create new Window
// Remove window manager decoration in fullscreen
attributes.override_redirect = CreationParams.Fullscreen;
window = XCreateWindow(display,
RootWindow(display, visual->screen),
0, 0, Width, Height, 0, visual->depth,
InputOutput, visual->visual,
CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect,
&attributes);
XMapRaised(display, window);
CreationParams.WindowId = (void*)window;
Atom wmDelete;
wmDelete = XInternAtom(display, wmDeleteWindow, True);
XSetWMProtocols(display, window, &wmDelete, 1);
if (CreationParams.Fullscreen)
{
XSetInputFocus(display, window, RevertToParent, CurrentTime);
int grabKb = XGrabKeyboard(display, window, True, GrabModeAsync,
GrabModeAsync, CurrentTime);
IrrPrintXGrabError(grabKb, "XGrabKeyboard");
int grabPointer = XGrabPointer(display, window, True, ButtonPressMask,
GrabModeAsync, GrabModeAsync, window, None, CurrentTime);
IrrPrintXGrabError(grabPointer, "XGrabPointer");
XWarpPointer(display, None, window, 0, 0, 0, 0, 0, 0);
}
}
else
{
// attach external window
window = (Window)CreationParams.WindowId;
if (!CreationParams.IgnoreInput)
{
XCreateWindow(display,
window,
0, 0, Width, Height, 0, visual->depth,
InputOutput, visual->visual,
CWBorderPixel | CWColormap | CWEventMask,
&attributes);
}
XWindowAttributes wa;
XGetWindowAttributes(display, window, &wa);
CreationParams.WindowSize.Width = wa.width;
CreationParams.WindowSize.Height = wa.height;
CreationParams.Fullscreen = false;
ExternalWindow = true;
}
WindowMinimized=false;
// Currently broken in X, see Bug ID 2795321
// XkbSetDetectableAutoRepeat(display, True, &AutorepeatSupport);
#ifdef _IRR_COMPILE_WITH_OPENGL_
// connect glx context to window
Context=0;
if (isAvailableGLX && CreationParams.DriverType==video::EDT_OPENGL)
{
if (UseGLXWindow)
{
glxWin=glXCreateWindow(display,glxFBConfig,window,NULL);
if (glxWin)
{
// create glx context
Context = glXCreateNewContext(display, glxFBConfig, GLX_RGBA_TYPE, NULL, True);
if (Context)
{
if (!glXMakeContextCurrent(display, glxWin, glxWin, Context))
{
os::Printer::log("Could not make context current.", ELL_WARNING);
glXDestroyContext(display, Context);
}
}
else
{
os::Printer::log("Could not create GLX rendering context.", ELL_WARNING);
}
}
else
{
os::Printer::log("Could not create GLX window.", ELL_WARNING);
}
}
else
{
Context = glXCreateContext(display, visual, NULL, True);
if (Context)
{
if (!glXMakeCurrent(display, window, Context))
{
os::Printer::log("Could not make context current.", ELL_WARNING);
glXDestroyContext(display, Context);
}
}
else
{
os::Printer::log("Could not create GLX rendering context.", ELL_WARNING);
}
}
}
#endif // _IRR_COMPILE_WITH_OPENGL_
Window tmp;
u32 borderWidth;
int x,y;
unsigned int bits;
XGetGeometry(display, window, &tmp, &x, &y, &Width, &Height, &borderWidth, &bits);
CreationParams.Bits = bits;
CreationParams.WindowSize.Width = Width;
CreationParams.WindowSize.Height = Height;
StdHints = XAllocSizeHints();
long num;
XGetWMNormalHints(display, window, StdHints, &num);
// create an XImage for the software renderer
//(thx to Nadav for some clues on how to do that!)
if (CreationParams.DriverType == video::EDT_SOFTWARE || CreationParams.DriverType == video::EDT_BURNINGSVIDEO)
{
SoftwareImage = XCreateImage(display,
visual->visual, visual->depth,
ZPixmap, 0, 0, Width, Height,
BitmapPad(display), 0);
// use malloc because X will free it later on
if (SoftwareImage)
SoftwareImage->data = (char*) malloc(SoftwareImage->bytes_per_line * SoftwareImage->height * sizeof(char));
}
initXAtoms();
#endif // #ifdef _IRR_COMPILE_WITH_X11_
return true;
}
//! create the driver
void CIrrDeviceLinux::createDriver()
{
switch(CreationParams.DriverType)
{
#ifdef _IRR_COMPILE_WITH_X11_
case video::EDT_SOFTWARE:
#ifdef _IRR_COMPILE_WITH_SOFTWARE_
VideoDriver = video::createSoftwareDriver(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this);
#else
os::Printer::log("No Software driver support compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_BURNINGSVIDEO:
#ifdef _IRR_COMPILE_WITH_BURNINGSVIDEO_
VideoDriver = video::createSoftwareDriver2(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this);
#else
os::Printer::log("Burning's video driver was not compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_OPENGL:
#ifdef _IRR_COMPILE_WITH_OPENGL_
if (Context)
VideoDriver = video::createOpenGLDriver(CreationParams, FileSystem, this);
#else
os::Printer::log("No OpenGL support compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_DIRECT3D8:
case video::EDT_DIRECT3D9:
os::Printer::log("This driver is not available in Linux. Try OpenGL or Software renderer.",
ELL_ERROR);
break;
case video::EDT_NULL:
VideoDriver = video::createNullDriver(FileSystem, CreationParams.WindowSize);
break;
default:
|
paupawsan/Irrlicht
|
b604df103134693f00516ab4e19d7da5b3ee7cb9
|
Add some logging about chosen fullscreen resolution in X11.
|
diff --git a/source/Irrlicht/CIrrDeviceLinux.cpp b/source/Irrlicht/CIrrDeviceLinux.cpp
index f473918..614d8b9 100644
--- a/source/Irrlicht/CIrrDeviceLinux.cpp
+++ b/source/Irrlicht/CIrrDeviceLinux.cpp
@@ -1,765 +1,767 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CIrrDeviceLinux.h"
#ifdef _IRR_COMPILE_WITH_X11_DEVICE_
#include <stdio.h>
#include <stdlib.h>
#include <sys/utsname.h>
#include <time.h>
#include "IEventReceiver.h"
#include "os.h"
#include "CTimer.h"
#include "irrString.h"
#include "Keycodes.h"
#include "COSOperator.h"
#include "CColorConverter.h"
#include "SIrrCreationParameters.h"
#include <X11/XKBlib.h>
#include <X11/Xatom.h>
#if defined _IRR_COMPILE_WITH_JOYSTICK_EVENTS_
#include <fcntl.h>
#include <unistd.h>
#ifdef __FREE_BSD_
#include <sys/joystick.h>
#else
// linux/joystick.h includes linux/input.h, which #defines values for various KEY_FOO keys.
// These override the irr::KEY_FOO equivalents, which stops key handling from working.
// As a workaround, defining _INPUT_H stops linux/input.h from being included; it
// doesn't actually seem to be necessary except to pull in sys/ioctl.h.
#define _INPUT_H
#include <sys/ioctl.h> // Would normally be included in linux/input.h
#include <linux/joystick.h>
#undef _INPUT_H
#endif
#endif // _IRR_COMPILE_WITH_JOYSTICK_EVENTS_
namespace irr
{
namespace video
{
IVideoDriver* createOpenGLDriver(const SIrrlichtCreationParameters& params,
io::IFileSystem* io, CIrrDeviceLinux* device);
}
} // end namespace irr
namespace
{
Atom X_ATOM_CLIPBOARD;
Atom X_ATOM_TARGETS;
Atom X_ATOM_UTF8_STRING;
Atom X_ATOM_TEXT;
};
namespace irr
{
const char* wmDeleteWindow = "WM_DELETE_WINDOW";
//! constructor
CIrrDeviceLinux::CIrrDeviceLinux(const SIrrlichtCreationParameters& param)
: CIrrDeviceStub(param),
#ifdef _IRR_COMPILE_WITH_X11_
display(0), visual(0), screennr(0), window(0), StdHints(0), SoftwareImage(0),
#ifdef _IRR_COMPILE_WITH_OPENGL_
glxWin(0),
Context(0),
#endif
#endif
Width(param.WindowSize.Width), Height(param.WindowSize.Height),
WindowHasFocus(false), WindowMinimized(false),
UseXVidMode(false), UseXRandR(false), UseGLXWindow(false),
ExternalWindow(false), AutorepeatSupport(0)
{
#ifdef _DEBUG
setDebugName("CIrrDeviceLinux");
#endif
// print version, distribution etc.
// thx to LynxLuna for pointing me to the uname function
core::stringc linuxversion;
struct utsname LinuxInfo;
uname(&LinuxInfo);
linuxversion += LinuxInfo.sysname;
linuxversion += " ";
linuxversion += LinuxInfo.release;
linuxversion += " ";
linuxversion += LinuxInfo.version;
linuxversion += " ";
linuxversion += LinuxInfo.machine;
Operator = new COSOperator(linuxversion.c_str(), this);
os::Printer::log(linuxversion.c_str(), ELL_INFORMATION);
// create keymap
createKeyMap();
// create window
if (CreationParams.DriverType != video::EDT_NULL)
{
// create the window, only if we do not use the null device
if (!createWindow())
return;
}
// create cursor control
CursorControl = new CCursorControl(this, CreationParams.DriverType == video::EDT_NULL);
// create driver
createDriver();
if (!VideoDriver)
return;
createGUIAndScene();
}
//! destructor
CIrrDeviceLinux::~CIrrDeviceLinux()
{
#ifdef _IRR_COMPILE_WITH_X11_
if (StdHints)
XFree(StdHints);
// Disable cursor and free it later on
CursorControl->setVisible(false);
if (display)
{
#ifdef _IRR_COMPILE_WITH_OPENGL_
if (Context)
{
if (glxWin)
{
if (!glXMakeContextCurrent(display, None, None, NULL))
os::Printer::log("Could not release glx context.", ELL_WARNING);
}
else
{
if (!glXMakeCurrent(display, None, NULL))
os::Printer::log("Could not release glx context.", ELL_WARNING);
}
glXDestroyContext(display, Context);
if (glxWin)
glXDestroyWindow(display, glxWin);
}
#endif // #ifdef _IRR_COMPILE_WITH_OPENGL_
// Reset fullscreen resolution change
switchToFullscreen(true);
if (SoftwareImage)
XDestroyImage(SoftwareImage);
if (!ExternalWindow)
{
XDestroyWindow(display,window);
XCloseDisplay(display);
}
}
if (visual)
XFree(visual);
#endif // #ifdef _IRR_COMPILE_WITH_X11_
#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_)
for(u32 joystick = 0; joystick < ActiveJoysticks.size(); ++joystick)
{
if(ActiveJoysticks[joystick].fd >= 0)
{
close(ActiveJoysticks[joystick].fd);
}
}
#endif
}
#if defined(_IRR_COMPILE_WITH_X11_) && defined(_DEBUG)
int IrrPrintXError(Display *display, XErrorEvent *event)
{
char msg[256];
char msg2[256];
snprintf(msg, 256, "%d", event->request_code);
XGetErrorDatabaseText(display, "XRequest", msg, "unknown", msg2, 256);
XGetErrorText(display, event->error_code, msg, 256);
os::Printer::log("X Error", msg, ELL_WARNING);
os::Printer::log("From call ", msg2, ELL_WARNING);
return 0;
}
#endif
bool CIrrDeviceLinux::switchToFullscreen(bool reset)
{
if (!CreationParams.Fullscreen)
return true;
if (reset)
{
#ifdef _IRR_LINUX_X11_VIDMODE_
if (UseXVidMode && CreationParams.Fullscreen)
{
XF86VidModeSwitchToMode(display, screennr, &oldVideoMode);
XF86VidModeSetViewPort(display, screennr, 0, 0);
}
#endif
#ifdef _IRR_LINUX_X11_RANDR_
if (UseXRandR && CreationParams.Fullscreen)
{
XRRScreenConfiguration *config=XRRGetScreenInfo(display,DefaultRootWindow(display));
XRRSetScreenConfig(display,config,DefaultRootWindow(display),oldRandrMode,oldRandrRotation,CurrentTime);
XRRFreeScreenConfigInfo(config);
}
#endif
return true;
}
getVideoModeList();
#if defined(_IRR_LINUX_X11_VIDMODE_) || defined(_IRR_LINUX_X11_RANDR_)
s32 eventbase, errorbase;
s32 bestMode = -1;
#endif
#ifdef _IRR_LINUX_X11_VIDMODE_
if (XF86VidModeQueryExtension(display, &eventbase, &errorbase))
{
// enumerate video modes
s32 modeCount;
XF86VidModeModeInfo** modes;
XF86VidModeGetAllModeLines(display, screennr, &modeCount, &modes);
// find fitting mode
for (s32 i = 0; i<modeCount; ++i)
{
if (bestMode==-1 && modes[i]->hdisplay >= Width && modes[i]->vdisplay >= Height)
bestMode = i;
else if (bestMode!=-1 &&
modes[i]->hdisplay >= Width &&
modes[i]->vdisplay >= Height &&
modes[i]->hdisplay < modes[bestMode]->hdisplay &&
modes[i]->vdisplay < modes[bestMode]->vdisplay)
bestMode = i;
}
if (bestMode != -1)
{
os::Printer::log("Starting fullscreen mode...", ELL_INFORMATION);
+ os::Printer::log("hdisplay: ", core::stringc(modes[bestMode]->hdisplay).c_str(), ELL_INFORMATION);
+ os::Printer::log("vdisplay: ", core::stringc(modes[bestMode]->vdisplay).c_str(), ELL_INFORMATION);
XF86VidModeSwitchToMode(display, screennr, modes[bestMode]);
XF86VidModeSetViewPort(display, screennr, 0, 0);
UseXVidMode=true;
}
else
{
os::Printer::log("Could not find specified video mode, running windowed.", ELL_WARNING);
CreationParams.Fullscreen = false;
}
XFree(modes);
}
else
#endif
#ifdef _IRR_LINUX_X11_RANDR_
if (XRRQueryExtension(display, &eventbase, &errorbase))
{
s32 modeCount;
XRRScreenConfiguration *config=XRRGetScreenInfo(display,DefaultRootWindow(display));
XRRScreenSize *modes=XRRConfigSizes(config,&modeCount);
for (s32 i = 0; i<modeCount; ++i)
{
if (bestMode==-1 && (u32)modes[i].width >= Width && (u32)modes[i].height >= Height)
bestMode = i;
else if (bestMode!=-1 &&
(u32)modes[i].width >= Width &&
(u32)modes[i].height >= Height &&
modes[i].width < modes[bestMode].width &&
modes[i].height < modes[bestMode].height)
bestMode = i;
}
if (bestMode != -1)
{
XRRSetScreenConfig(display,config,DefaultRootWindow(display),bestMode,oldRandrRotation,CurrentTime);
UseXRandR=true;
}
XRRFreeScreenConfigInfo(config);
}
else
#endif
{
os::Printer::log("VidMode or RandR extension must be installed to allow Irrlicht "
"to switch to fullscreen mode. Running in windowed mode instead.", ELL_WARNING);
CreationParams.Fullscreen = false;
}
return CreationParams.Fullscreen;
}
#if defined(_IRR_COMPILE_WITH_X11_)
void IrrPrintXGrabError(int grabResult, const c8 * grabCommand )
{
if ( grabResult == GrabSuccess )
{
// os::Printer::log(grabCommand, ": GrabSuccess", ELL_INFORMATION);
return;
}
switch ( grabResult )
{
case AlreadyGrabbed:
os::Printer::log(grabCommand, ": AlreadyGrabbed", ELL_WARNING);
break;
case GrabNotViewable:
os::Printer::log(grabCommand, ": GrabNotViewable", ELL_WARNING);
break;
case GrabFrozen:
os::Printer::log(grabCommand, ": GrabFrozen", ELL_WARNING);
break;
case GrabInvalidTime:
os::Printer::log(grabCommand, ": GrabInvalidTime", ELL_WARNING);
break;
default:
os::Printer::log(grabCommand, ": grab failed with unknown problem", ELL_WARNING);
break;
}
}
#endif
bool CIrrDeviceLinux::createWindow()
{
#ifdef _IRR_COMPILE_WITH_X11_
#ifdef _DEBUG
os::Printer::log("Creating X window...", ELL_INFORMATION);
XSetErrorHandler(IrrPrintXError);
#endif
display = XOpenDisplay(0);
if (!display)
{
os::Printer::log("Error: Need running XServer to start Irrlicht Engine.", ELL_ERROR);
if (XDisplayName(0)[0])
os::Printer::log("Could not open display", XDisplayName(0), ELL_ERROR);
else
os::Printer::log("Could not open display, set DISPLAY variable", ELL_ERROR);
return false;
}
screennr = DefaultScreen(display);
switchToFullscreen();
#ifdef _IRR_COMPILE_WITH_OPENGL_
GLXFBConfig glxFBConfig;
int major, minor;
bool isAvailableGLX=false;
if (CreationParams.DriverType==video::EDT_OPENGL)
{
isAvailableGLX=glXQueryExtension(display,&major,&minor);
if (isAvailableGLX && glXQueryVersion(display, &major, &minor))
{
#ifdef GLX_VERSION_1_3
typedef GLXFBConfig * ( * PFNGLXCHOOSEFBCONFIGPROC) (Display *dpy, int screen, const int *attrib_list, int *nelements);
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
PFNGLXCHOOSEFBCONFIGPROC glxChooseFBConfig = (PFNGLXCHOOSEFBCONFIGPROC)glXGetProcAddress(reinterpret_cast<const GLubyte*>("glXChooseFBConfig"));
#else
PFNGLXCHOOSEFBCONFIGPROC glxChooseFBConfig=glXChooseFBConfig;
#endif
if (major==1 && minor>2 && glxChooseFBConfig)
{
// attribute array for the draw buffer
int visualAttrBuffer[] =
{
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_RED_SIZE, 4,
GLX_GREEN_SIZE, 4,
GLX_BLUE_SIZE, 4,
GLX_ALPHA_SIZE, CreationParams.WithAlphaChannel?1:0,
GLX_DEPTH_SIZE, CreationParams.ZBufferBits, //10,11
GLX_DOUBLEBUFFER, CreationParams.Doublebuffer?True:False,
GLX_STENCIL_SIZE, CreationParams.Stencilbuffer?1:0,
#if defined(GLX_VERSION_1_4) && defined(GLX_SAMPLE_BUFFERS) // we need to check the extension string!
GLX_SAMPLE_BUFFERS, 1,
GLX_SAMPLES, CreationParams.AntiAlias, // 18,19
#elif defined(GLX_ARB_multisample)
GLX_SAMPLE_BUFFERS_ARB, 1,
GLX_SAMPLES_ARB, CreationParams.AntiAlias, // 18,19
#elif defined(GLX_SGIS_multisample)
GLX_SAMPLE_BUFFERS_SGIS, 1,
GLX_SAMPLES_SGIS, CreationParams.AntiAlias, // 18,19
#endif
GLX_STEREO, CreationParams.Stereobuffer?True:False,
None
};
GLXFBConfig *configList=0;
int nitems=0;
if (CreationParams.AntiAlias<2)
{
visualAttrBuffer[17] = 0;
visualAttrBuffer[19] = 0;
}
// first round with unchanged values
{
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
if (!configList && CreationParams.AntiAlias)
{
while (!configList && (visualAttrBuffer[19]>1))
{
visualAttrBuffer[19] -= 1;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
}
if (!configList)
{
visualAttrBuffer[17] = 0;
visualAttrBuffer[19] = 0;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
if (configList)
{
os::Printer::log("No FSAA available.", ELL_WARNING);
CreationParams.AntiAlias=0;
}
else
{
//reenable multisampling
visualAttrBuffer[17] = 1;
visualAttrBuffer[19] = CreationParams.AntiAlias;
}
}
}
}
// Next try with flipped stencil buffer value
// If the first round was with stencil flag it's now without
// Other way round also makes sense because some configs
// only have depth buffer combined with stencil buffer
if (!configList)
{
if (CreationParams.Stencilbuffer)
os::Printer::log("No stencilbuffer available, disabling stencil shadows.", ELL_WARNING);
CreationParams.Stencilbuffer = !CreationParams.Stencilbuffer;
visualAttrBuffer[15]=CreationParams.Stencilbuffer?1:0;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
if (!configList && CreationParams.AntiAlias)
{
while (!configList && (visualAttrBuffer[19]>1))
{
visualAttrBuffer[19] -= 1;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
}
if (!configList)
{
visualAttrBuffer[17] = 0;
visualAttrBuffer[19] = 0;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
if (configList)
{
os::Printer::log("No FSAA available.", ELL_WARNING);
CreationParams.AntiAlias=0;
}
else
{
//reenable multisampling
visualAttrBuffer[17] = 1;
visualAttrBuffer[19] = CreationParams.AntiAlias;
}
}
}
}
// Next try without double buffer
if (!configList && CreationParams.Doublebuffer)
{
os::Printer::log("No doublebuffering available.", ELL_WARNING);
CreationParams.Doublebuffer=false;
visualAttrBuffer[13] = GLX_DONT_CARE;
CreationParams.Stencilbuffer = false;
visualAttrBuffer[15]=0;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
if (!configList && CreationParams.AntiAlias)
{
while (!configList && (visualAttrBuffer[19]>1))
{
visualAttrBuffer[19] -= 1;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
}
if (!configList)
{
visualAttrBuffer[17] = 0;
visualAttrBuffer[19] = 0;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
if (configList)
{
os::Printer::log("No FSAA available.", ELL_WARNING);
CreationParams.AntiAlias=0;
}
else
{
//reenable multisampling
visualAttrBuffer[17] = 1;
visualAttrBuffer[19] = CreationParams.AntiAlias;
}
}
}
}
if (configList)
{
glxFBConfig=configList[0];
XFree(configList);
UseGLXWindow=true;
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
typedef XVisualInfo * ( * PFNGLXGETVISUALFROMFBCONFIGPROC) (Display *dpy, GLXFBConfig config);
PFNGLXGETVISUALFROMFBCONFIGPROC glxGetVisualFromFBConfig= (PFNGLXGETVISUALFROMFBCONFIGPROC)glXGetProcAddress(reinterpret_cast<const GLubyte*>("glXGetVisualFromFBConfig"));
if (glxGetVisualFromFBConfig)
visual = glxGetVisualFromFBConfig(display,glxFBConfig);
#else
visual = glXGetVisualFromFBConfig(display,glxFBConfig);
#endif
}
}
else
#endif
{
// attribute array for the draw buffer
int visualAttrBuffer[] =
{
GLX_RGBA, GL_TRUE,
GLX_RED_SIZE, 4,
GLX_GREEN_SIZE, 4,
GLX_BLUE_SIZE, 4,
GLX_ALPHA_SIZE, CreationParams.WithAlphaChannel?1:0,
GLX_DEPTH_SIZE, CreationParams.ZBufferBits,
GLX_STENCIL_SIZE, CreationParams.Stencilbuffer?1:0, // 12,13
// The following attributes have no flags, but are
// either present or not. As a no-op we use
// GLX_USE_GL, which is silently ignored by glXChooseVisual
CreationParams.Doublebuffer?GLX_DOUBLEBUFFER:GLX_USE_GL, // 14
CreationParams.Stereobuffer?GLX_STEREO:GLX_USE_GL, // 15
None
};
visual=glXChooseVisual(display, screennr, visualAttrBuffer);
if (!visual)
{
if (CreationParams.Stencilbuffer)
os::Printer::log("No stencilbuffer available, disabling.", ELL_WARNING);
CreationParams.Stencilbuffer = !CreationParams.Stencilbuffer;
visualAttrBuffer[13]=CreationParams.Stencilbuffer?1:0;
visual=glXChooseVisual(display, screennr, visualAttrBuffer);
if (!visual && CreationParams.Doublebuffer)
{
os::Printer::log("No doublebuffering available.", ELL_WARNING);
CreationParams.Doublebuffer=false;
visualAttrBuffer[14] = GLX_USE_GL;
visual=glXChooseVisual(display, screennr, visualAttrBuffer);
}
}
}
}
else
os::Printer::log("No GLX support available. OpenGL driver will not work.", ELL_WARNING);
}
// don't use the XVisual with OpenGL, because it ignores all requested
// properties of the CreationParams
else if (!visual)
#endif // _IRR_COMPILE_WITH_OPENGL_
// create visual with standard X methods
{
os::Printer::log("Using plain X visual");
XVisualInfo visTempl; //Template to hold requested values
int visNumber; // Return value of available visuals
visTempl.screen = screennr;
// ARGB visuals should be avoided for usual applications
visTempl.depth = CreationParams.WithAlphaChannel?32:24;
while ((!visual) && (visTempl.depth>=16))
{
visual = XGetVisualInfo(display, VisualScreenMask|VisualDepthMask,
&visTempl, &visNumber);
visTempl.depth -= 8;
}
}
if (!visual)
{
os::Printer::log("Fatal error, could not get visual.", ELL_ERROR);
XCloseDisplay(display);
display=0;
return false;
}
#ifdef _DEBUG
else
os::Printer::log("Visual chosen: ", core::stringc(static_cast<u32>(visual->visualid)).c_str(), ELL_INFORMATION);
#endif
// create color map
Colormap colormap;
colormap = XCreateColormap(display,
RootWindow(display, visual->screen),
visual->visual, AllocNone);
attributes.colormap = colormap;
attributes.border_pixel = 0;
attributes.event_mask = StructureNotifyMask | FocusChangeMask | ExposureMask;
if (!CreationParams.IgnoreInput)
attributes.event_mask |= PointerMotionMask |
ButtonPressMask | KeyPressMask |
ButtonReleaseMask | KeyReleaseMask;
if (!CreationParams.WindowId)
{
// create new Window
// Remove window manager decoration in fullscreen
attributes.override_redirect = CreationParams.Fullscreen;
window = XCreateWindow(display,
RootWindow(display, visual->screen),
0, 0, Width, Height, 0, visual->depth,
InputOutput, visual->visual,
CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect,
&attributes);
XMapRaised(display, window);
CreationParams.WindowId = (void*)window;
Atom wmDelete;
wmDelete = XInternAtom(display, wmDeleteWindow, True);
XSetWMProtocols(display, window, &wmDelete, 1);
if (CreationParams.Fullscreen)
{
XSetInputFocus(display, window, RevertToParent, CurrentTime);
int grabKb = XGrabKeyboard(display, window, True, GrabModeAsync,
GrabModeAsync, CurrentTime);
IrrPrintXGrabError(grabKb, "XGrabKeyboard");
int grabPointer = XGrabPointer(display, window, True, ButtonPressMask,
GrabModeAsync, GrabModeAsync, window, None, CurrentTime);
IrrPrintXGrabError(grabPointer, "XGrabPointer");
XWarpPointer(display, None, window, 0, 0, 0, 0, 0, 0);
}
}
else
{
// attach external window
window = (Window)CreationParams.WindowId;
if (!CreationParams.IgnoreInput)
{
XCreateWindow(display,
window,
0, 0, Width, Height, 0, visual->depth,
InputOutput, visual->visual,
CWBorderPixel | CWColormap | CWEventMask,
&attributes);
}
XWindowAttributes wa;
XGetWindowAttributes(display, window, &wa);
CreationParams.WindowSize.Width = wa.width;
CreationParams.WindowSize.Height = wa.height;
CreationParams.Fullscreen = false;
ExternalWindow = true;
}
WindowMinimized=false;
// Currently broken in X, see Bug ID 2795321
// XkbSetDetectableAutoRepeat(display, True, &AutorepeatSupport);
#ifdef _IRR_COMPILE_WITH_OPENGL_
// connect glx context to window
Context=0;
if (isAvailableGLX && CreationParams.DriverType==video::EDT_OPENGL)
{
if (UseGLXWindow)
{
glxWin=glXCreateWindow(display,glxFBConfig,window,NULL);
if (glxWin)
{
// create glx context
Context = glXCreateNewContext(display, glxFBConfig, GLX_RGBA_TYPE, NULL, True);
if (Context)
{
if (!glXMakeContextCurrent(display, glxWin, glxWin, Context))
{
os::Printer::log("Could not make context current.", ELL_WARNING);
glXDestroyContext(display, Context);
}
}
else
{
os::Printer::log("Could not create GLX rendering context.", ELL_WARNING);
}
}
else
{
os::Printer::log("Could not create GLX window.", ELL_WARNING);
}
}
else
{
Context = glXCreateContext(display, visual, NULL, True);
if (Context)
{
if (!glXMakeCurrent(display, window, Context))
{
os::Printer::log("Could not make context current.", ELL_WARNING);
glXDestroyContext(display, Context);
}
}
else
{
os::Printer::log("Could not create GLX rendering context.", ELL_WARNING);
}
}
}
#endif // _IRR_COMPILE_WITH_OPENGL_
Window tmp;
u32 borderWidth;
int x,y;
unsigned int bits;
XGetGeometry(display, window, &tmp, &x, &y, &Width, &Height, &borderWidth, &bits);
CreationParams.Bits = bits;
CreationParams.WindowSize.Width = Width;
CreationParams.WindowSize.Height = Height;
StdHints = XAllocSizeHints();
long num;
XGetWMNormalHints(display, window, StdHints, &num);
// create an XImage for the software renderer
//(thx to Nadav for some clues on how to do that!)
if (CreationParams.DriverType == video::EDT_SOFTWARE || CreationParams.DriverType == video::EDT_BURNINGSVIDEO)
{
SoftwareImage = XCreateImage(display,
visual->visual, visual->depth,
ZPixmap, 0, 0, Width, Height,
BitmapPad(display), 0);
// use malloc because X will free it later on
if (SoftwareImage)
SoftwareImage->data = (char*) malloc(SoftwareImage->bytes_per_line * SoftwareImage->height * sizeof(char));
}
initXAtoms();
#endif // #ifdef _IRR_COMPILE_WITH_X11_
return true;
}
//! create the driver
void CIrrDeviceLinux::createDriver()
{
switch(CreationParams.DriverType)
{
#ifdef _IRR_COMPILE_WITH_X11_
case video::EDT_SOFTWARE:
#ifdef _IRR_COMPILE_WITH_SOFTWARE_
VideoDriver = video::createSoftwareDriver(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this);
|
paupawsan/Irrlicht
|
1031ae736491ff6718076b7c74b98fa2bb299b10
|
Ignore setResizable also on X11 when we're fullscreen to avoid messing up the window mode.
|
diff --git a/changes.txt b/changes.txt
index fa5c75a..3033b4e 100644
--- a/changes.txt
+++ b/changes.txt
@@ -1,515 +1,519 @@
-----------------------------
Changes in 1.7.1 (17.02.2010)
+ - Ignore setResizable also on X11 when we're fullscreen to avoid messing up the window mode.
+
+ - Work around a crash when pressing ESC after closing a Messagebox (found by Acki)
+
- Prevent borland compile warnings in SColorHSL::FromRGB and in SVertexColorThresholdManipulator (found by mdeininger)
- Improve Windows version detection rules (Patch from brferreira)
- Make it compile on Borland compilers (thx to mdeininger)
- Make sure that CAnimatedMeshSceneNode::clone calls the virtual updateAbsolutePosition for the new object
- Fix that clones got dropped too often when SceneNodes without parent got cloned (found by Ulf)
- Make sure TAB is still recognized on X11 when shift+tab is pressed. This does also fix going to the previous tabstop on X11.
- Send EGET_ELEMENT_LEFT also when there won't be a new hovered element
- Update docs for EGET_ELEMENT_LEFT and EGET_ELEMENT_HOVERED
- Fix tooltips: Remove them when the element is hidden or removed (thx to seven for finding)
- Fix tooltips: Make (more) sure they don't get confused by gui-subelements
- Fix tooltips: Get faster relaunch times working
- Fix tooltips: Make sure hovered element is never the tooltip itself
- Fix string::remove which got in an endless loop when remove was called with an empty string (found and fixed by Ulf)
- Correctly release the GLSL shaders
- Make sure we only release an X11 atom when it was actually created
- Fix aabbox collision test, which not only broke the collision test routines, but also frustum culling, octree tests, etc.
- Fix compilation problem under OSX due to wrong glProgramParameteri usage
- mem leak in OBJ loader fixed
- Removed some default parameters to reduce ambigious situations
---------------------------
Changes in 1.7 (03.02.2010)
- Implement minimize and deminimize under OSX.
- Define sorting order for vector2d and vector3d in operators <, <=, > and >= to fix bugs 2783509 and 2783510. Operators order now by X,Y,Z and use float tolerances.
- Ogre mesh 32bit indices fixed.
- Fix tooltips for gui-elements with sub-element like IGUISpinBox (id: 2927079, found by ArakisTheKitsune)
- ITimer no longer stops when started twice
- wchar_t filesystem updates under Windows.
- Joystick POV fixed under Windows, ids fixed under OSX.
- Some updates to skinned mesh for better bones support and scaling animations.
- OSX supports external window id in creation parameters now.
- Fix bbox collision tests.
- Updates for win32 key handling
- new convenience method for flat plane creation.
- Sky dome and other meshes use VBOs by default now.
- Speed up b3d loading for files with many frames, material color flags and vertex color support enhanced.
- Add hasType to IGUIElement as a dynamic_cast substitute.
- Add another parameter to IGUISkin::draw3DWindowBackground to allow getting the client area without actually drawing
- Add function getClientRect to IGUIWindow for getting the draw-able area
- Fix bug that menus on IGUIWindows with titlebar got drawn too high (id: 2714400)
- Renamed OctTree to Octree
- Allow getting a ConstIterator from a non-const core:list
- Add swap functions to irrMath and to the core classes.
- Deprecate map::isEmpty() and replace it with map::empty() to make it similar to other base classes.
- Allow to set the logging level already in SIrrlichtCreationParameters.
- Add clearSystemMessages to devices (implemented only for Linux and Win32 so far).
- Support changing the render window from beginScene also with OpenGL driver.
- Add getMaterial2D which allows to alter the 2d render state settings, such as filtering, anti-aliasing, thickness, etc.
- Fix incorrect cursorpos for resizable windows on Windows Vista (found and patched by buffer)
- Change the beginScene window parameter from void* to SExposedVideoData&. This will allow to manage contexts for OpenGL at some point.
- Add bzip2 and LZMA decompression modes for zip loader.
- Add OBJ_TEXTURE_PATH and B3D_TEXTURE_PATH to SceneParameters to allow setting texture-paths for obj and b3d.
- Irrlicht keeps now filenames additionally to the internally used names, thereby fixing some problems with uppercase-filenames on Linux.
- Bugfix: Mousewheel no longer sends EMIE_MOUSE_WHEEL messages twice on Linux.
- Use latest jpeglib
- refactoring: E_ATTRIBUTE_TYPE and IAttribute have now own headers
- CStringWArrayAttribute speedup
- SceneNodeAnimatorFollowSpline can now loop and pingpong
- Meshviewer.example got some fast-scale buttons.
- Support AES-encrypted zip files. Should work with 128, 196, and 256 bit AES. This addition also adds a new PRNG, SHA, and other algorithms to the engine, though no interface is yet added for them. The implementation of the encryption algorithms is provided by Dr Brian Gladman.
- flattenFilename and getAbsolutePath fixed and properly added at several places.
- Added geometry shaders for OpenGL. A first version of the code was submitted by Matthew Kielan (devsh).
- Bugfix: irrArray should no longer crash when using other allocators.
- Add MaterialViewer example.
- Texture activation now back in setMaterial, which simplifies writing external material renderers (OpenGL only).
- Checkbox uses now disabled text color when disabled.
- Changed colors for window-title caption to keep them readable when not active.
- Draw sub-menus to left side if they would be outside main-window otherwise.
- Give ListBox better defaults for the ScrollBar stepsizes.
- Double and triple click events now for each mouse-button. Old events for that got removed.
- Fix adding archives twice, which caused multiple archives of the same name and type covering each other. This one required a texture name change from using backslashes to slashes under Windows.
- Give access to texture mipmaps. You can provide custom mipmap textures upon generation, regeneration, and locking.
Make sure the provided data is large enough and covers all miplevels. Also the returned pointer (from lock) will only cover the smaller data of the mipmap level dimension chosen (level 0 is the original texture).
- Separate TextureWrap mode into U and V fields
- Add mirror texture wrap modes
- windows show now active/inactive state
- remove unneeded drop/grab calls found by manik_sheeri
- fix rounding problem in IGUIElements which have EGUIA_SCALE alignments.
- MessageBox supports now automatic resizing and images.
Deprecated EGDS_MESSAGE_BOX_WIDTH and EGDS_MESSAGE_BOX_HEIGHT
- Let maya-cam animator react on a setTarget call to the camera which happened outside it's own control
- New contextmenue features:
automatic checking for checked flag.
close handling now customizable
serialization can handle incomplete xml's
setEventParent now in public interface
New function findItemWithCommandId
New function insertItem
- new vector3d::getSphericalCoordinateAngles method.
- new triangle3d::isTotalOutsideBox method.
- Newly introduced VertexManipulator interface. This allows for very easy creation of vertex manipulation algorithms. Several manipulators, e.g. vertex color changer and transformation algorithms are already available.
- createMeshWith1TCoords avoids vertex duplication
- getRotation now handles matrices with scaling as well
- Ogre format animations now supported.
- irrArray: Fixed issues with push_front and reallocation
Changed behavior for set_pointer and clear, when free_when_destroyed is false
- NPK (Nebula device archive) reader added, it's an uncompressed PAK-like format
- SSkinMeshBuffer::MoveTo* methods renamed to convertTo*
- Multiple Render Target (MRT) support added, including some enhanced blend features where supported
- Directory changing fixed for virtual file systems (Archives etc)
- Fix texture matrix init in scene manager and driver
- More draw2dimage support in software drivers
- Sphere node now properly chooses a good tesselation based on the parameters
- Active camera not registered twice anymore
- Parallax/normal map shader rotation bug under OpenGL fixed
- bump map handling for obj files fixed
- Fog serialization added
- New context menu features added
- Bounding Box updates for skinned meshes fixed
- The current FPS for an animated scene node can be queried now, added some variables to serialization
- Scrollbars fixed
- Fixed 2d vertex primitive method to correctly handle transparency
- Fullscreen handling has been enhanced for Windows, now proper resolution is restored on Alt-Tab etc.
- Cameras can now be added to the scene node without automatically activating them
Clone method added
- New video driver method getMaxTextureSize
- PAK archive reader fixed
- TRANSPARENT_ALPHA_CHANNEL_REF uses modulate to enable lighting
- LIGHTMAP_ADD now always uses add operator
- Some Unicode file system fixes
- destructor of irrString not virtual anymore, please don't derive from irrString
Some new methods added, for searching and splitting
Assignment operator optimized
- new lightness method for SColor
- draw3DTriangle now renders filled polygons, old behavior can be achieved by setting EMT_WIREFRAME
-----------------------------
Changes in 1.6.1 (13.01.2010)
- Fix pingpong for CSceneNodeAnimatorFlyStraight (found by gbox)
- Fix bug with IGUIEditBox where the cursor position is reset on text change.
- Make sure the window top-left corner on Windows is not negative on start so that Windows sytem-menu is always visible.
- Fix problem that the window did sometimes not get the keyboard focus in X11 in fullscreen. Add more debug output in case focus grabbing goes wrong.
- Fix screensize in videodriver when we didn't get the requested window size. This also prevents that gui-clicks are no longer synchronized with gui-drawing and elements can't be hit anymore.
- Bugfix: Prevent a crash when getTypeName was called for the guienvironment. EGUIET_ELEMENT got changed for this.
- Bugfix: Horizontal centered font with linebreaks draw now all lines. For example multiline TextSceneNodes work again.
- Bugfix: spinbox can no longer get in an endless loop due to floating point rounding error (found by slavik262)
- !!API change!! Disabled AntiAliasing of Lines in material default
Please enable this manually per material when sure that it won't lead to SW rendering.
- IGUIComboBox: clicking on the statictext displaying the active selection does now close and open listbox correctly. (Bug found by Reiko)
- Scrollbuttons in IGUITabControl adapt now to tab-height.
- Fix texturing of cylinder mesh
- Fix modal dialog position (found by LoneBoco: http://sourceforge.net/tracker/?func=detail&aid=2900266&group_id=74339&atid=540676)
- Fix DMF loading
- Fixing left+right special keys (ctrl, shift, alt) on Win32 (thanks to pc0de for good patch-ideas).
- Make stringarrays for enums in IGUISkin a little safer
- Add support for keys KEY_PRINT, KEY_HOME (on numpad) and KEY_NUMLOCK on Linux.
- Fix material handling in createMeshWith1TCoords
- Fix another (OldValue == NewValue) before drop()/grap(), this time in CTextureAttribute::setTexture.
- Fix LIGHTMAP_LIGHTING for D3D drivers.
- AntiAliasing disabled for debug render elements.
- Bugfix: CGUIToolBar::addButton does no longer mess up when no image is set and does now actually work with the text.
- Fix ninja animation range which got messed up a little when b3d animations got fixed (thx gbox for finding)
---------------------------
Changes in 1.6 (23.09.2009)
- Added IFileSystem::createEmptyFileList, exposed IFileList::sort, addItem and added getID
- Fix MAKE_IRR_ID so it can be used from outside the irr namespace (Micha's patch)
- Renamed some methods in ISkinnedMesh to match the official Irrlicht naming scheme according to createXXX()
- Change debug data to draw using lines instead of arrows, which is much faster. Patch by pc0de
- Fix a bug with FPS camera animator causing stutters. Patch by FuzzYspo0N
- Fix scrolling controls in CGUITabControl
- Fix a bug when getting optimal texture size in D3D drivers, by Jetro Lauha (tonic)
- Added EGDS_TITLEBARTEXT_DISTANCE_X and EGDS_TITLEBARTEXT_DISTANCE_Y to GUI, submitted by FuzzYspo0N
- Fix for UFT8 filenames displayed in file dialog, patch by MadHyde.
- Added const method for array::binary_search, potentially slow as it doesn't sort the list!
- Add support for scaling button images.
- Irrlicht can now come with multiple device types compiled in, the device to use is selected by SIrrlichtCreationParameters.DeviceType. This defaults to EIDT_BEST which automatically select the best device available starting with native, then X11, SDL and finally the console.
- Added support for EXP2 fog distribution. This required a change in the setFog parameters where now an enum value instead of the bool linear is given.
- IFileSystem changes:
- Renamed the following functions-
IFileArchive::getArchiveType to getType
IFileSystem::registerFileArchive to addFileArchive
IFileSystem::unregisterFileArchive to removeFileArchive
IFileArchive::openFile to createAndOpenFile
- New enum, E_FILE_ARCHIVE_TYPE. getType on IArchiveLoader and IFileArchive now both return this.
- IFileSystem::addFileArchive takes a parameter to specify the archive type rather always using the file extension. IFileSystem::addZipFileArchive, addFolderFileArchive and addPakFileArchive now use this but these functions are now marked as deprecated. Users should now use addFileArchive instead.
- Added TAR archive loader.
- The ZIP archive loader can now load gzip files, combined with the TAR loader this means Irrlicht now has native support for .tar.gz
Currently this must be done in two calls, for example:
fileSystem->addFileArchive("path/to/myArchive.tar.gz");
fileSystem->addFileArchive("myArchive.tar");
- Fix highlighting in IGUIEditBox where kerning pairs are used in the font. For example in future italic, OS or other custom fonts.
- IOSOperator::getTextFromClipboard returns now const c8* instead of c8*
- Support for copy&paste on linux (X11) added (fixing bug 2804014 found by Pan)
- bugfix for 2795321 found by egrath: Don't rely anymore on broken XkbSetDetectableAutoRepeat.
- bugfix: CMountPointReader::openFile no longer returns true for empty files. Corresponding test added.
- Direct3D now also uses screen coordinates in 2d mode, just like OpenGL. This means that screen coords are going from 0..ScreenWidth and 0..ScreenHeight instead of -1..1.
- ALT+F4 keypress now closes Windows SDL device
- Allow Direct3D drivers in SDL, patch by Halifax
- Added compiler error when attempting to compile with VC6.
- Use setWindowTextA in Windows device for WIN64 platform, posted by veegun
- ELL_ERROR log events are now created when shaders fail to compile or link, reported by Halan
- irrList now uses irrAllocator, fixed by Nox
- Added IGUIWindow::setDraggable and IGUIWindow::isDraggable, by Nox
- Added SGI RGB file reader by Gary Conway, for loading Silicon Graphics .rgb, .rgba, .sgi, .int and .inta textures
- Renamed setResizeAble to setResizable
- Added new device method minimizeWindow which minimizes the window (just as if the minimize button has been clicked).
- SkyDome is now serialized correctly
- Added PLY mesh reader and writer
- Ensure ListBox on combo box doesn't hang off the bottom of the GUI root, by Matthias Specht
- Made IGUIElements recalculate clipping rectangle after setNotClipped, reported by Aelis440
- Bug fix for the combo box where it showed white text instead of skin colour before being focused, fix posted by drewbacca
- EGDS_MESSAGE_BOX_HEIGHT is now honoured, bug reported by Spkka
- Fixed a bug in the edit box where events are sometimes sent to a null parent, reported by Sudi.
- Coordinate system fix for OpenGL in SDL device
- Added generic console device. You can now use Irrlicht to create and manipuate graphics on a shell where no graphics hardware
or windowing system is available. To enable it uncomment #define _IRR_USE_CONSOLE_DEVICE_ in IrrCompileConfig.h
- The console device can now present images from the software drivers and display them as ASCII art in the console
- By default it replaces the default font in the skin, to prevent fonts from being huge.
- Fixed problems with changing cursor visibility while mouse is pressed on windows
- Allow control of background drawing in listbox
- Allow control of drawing background and titlebar in windows
- Improved window serialization
- Add mouse events EMIE_MOUSE_DOUBLE_CLICK and EMIE_MOUSE_TRIPLE_CLICK (thx to Ulf for patch proposal)
- Set "ButtonStates" for mouse events also on Linux (was only for Windows formerly)
- Add Shift+Control states to mouse event
- bugfix (2003238): serialize modal screens
- allow stacking modal screens
- allowing hiding modals
- replace many IsVisible checks with virtual isVisible() checks in IGUIElement
- bugfix: reset selected row when clearing CGUITable
- adding events EGET_EDITBOX_CHANGED and EGET_EDITBOX_MARKING_CHANGED
- prevent editbox from recalculating its textbreaking each frame
- let spinbox react on each textchange without waiting for enter to prevent getting value changes without corresponding EGET_SPINBOX_CHANGED events.
- new test for zipreader
- prevent dropping objects accidentally in many set functions
- Reversed change in vector3d::normalize.
Works now again as documented and a corresponding test has been added.
Does fix bug 2770709 (https://sourceforge.net/tracker/?func=detail&aid=2770709&group_id=74339&atid=540676)
- Animations can now be paused by setting the fps to 0.
- Avoid fp-precision problem in getPickedNodeBB (see also http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=33838&highlight=).
This change might also fix the problem with picking nodes found by aanderse (http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=32890&highlight=)
- implemented isALoadableFileFormat ( File *file ) for the Archive Loader
- PixelBlend16 and PixelBlend16_simd are working for the new rules.
- bugfix. CLightSceneNode didn't correctly update it's attributes
- vector template and equals tests
also set the equal test for s32 to behave like the f32 routine.
The function equals always implements a weak test.
that means a tolerance MUST always be used if you use the equal function. default is 1.
- VideoDriver drawPixel
The HW renderes are using the alpha components for blending.
The Software Renderes and image loaders are using CImage::setPixel copy.
so setPixel is engaged to either blends or copy the pixel
default: false
- Burningvideo
added RenderMaterial EMT_SPHERE_MAP
pushed burningsvideo to 0.43
added RenderMaterial EMT_REFLECTION_2_LAYER
pushed burningsvideo to 0.44
set EMT_TRANSPARENT_ALPHA_CHANNEL_REF
to use AlphaRef 0.5 like Direct3D
One Note: in OpenGL there is know difference between sphere_map and reflection layer
both using GL_TEXTURE_GEN_MODE GL_SPHERE_MAP, whereas in d3d one time using camera_normal
on sphere and reflection on refletcion_layer.
The visual difference is that on sphere map the "image is not moving" when you rotate the
viewer. For Burning i took the opengl visual. always moving
- rename quake3 SEntity to IEntity to be confom with IShader
- fixed createMeshWith2TCoords, normals were missing during copy.
- added
//! Creates a copy of the mesh, which will only consist of S3DVertex vertices.
IMesh* CMeshManipulator::createMeshWith1TCoords(IMesh* mesh) const
- added io::IFileSystem* CSceneManager::getFileSystem()
- added virtual const c8* ISceneManager::getAnimatorTypeName(ESCENE_NODE_ANIMATOR_TYPE type);
- added CSceneNodeAnimatorFlyCircle::radiusEllipsoid.
if radiusEllipsoid == 0 the default circle animation is done
else radiusEllipsoid forms the b-axe of the ellipsoid.
-> gummiball bouncing
- added ISceneManager::createFlyStraightAnimator variable bool ping-pong
used in loop mode to device if start from beginning ( default ) or make ping-pong
-> straight bouncing
- changed IFileSystem::registerFileArchive
remove the index of the hierarchy and added a new interface method
//! move the hirarchy of the filesystem. moves sourceIndex relative up or down
virtual bool moveFileArchive( u32 sourceIndex, s32 relative ) = 0;
- bugfix and changes in SViewFrustum::SViewFrustum
wrong size of Matrices copy.
renamed E_TRANSFORMATION_STATE_2 to E_TRANSFORMATION_STATE_FRUSTUM
therefore also changed SViewFrustum::setTransformState to not tap
in the pitfall again of wrong memory...
- moved
//! EMT_ONETEXTURE_BLEND: has BlendFactor Alphablending
inline bool textureBlendFunc_hasAlpha ( E_BLEND_FACTOR factor ) const
from the material renderes ( 3x declared ) to SMaterial.h
- updated managed light example to use standard driver selection
- BurningsVideo
- LightModel reworked.
Point Light & Direction Light works for Diffuse Color as expected
Specular and Fog still have problems ( needs new pixel shader )
pushed burningsvideo to 0.42 for this major step
- removed obsolete matrix transformations
renamed E_TRANSFORMATION_STATE_2 to E_TRANSFORMATION_STATE_BURNING
- cleaned line3d.h vector3d.h template behavior.
many mixed f32/f64 implementations are here. i'm not sure if this should be
the default behavior to use f64 for example for 1.0/x value, because they
benefit from more precisions, but in my point of view the user is responsible
of choosing a vector3d<f32> or vector3d<f64>.
diff --git a/source/Irrlicht/CIrrDeviceLinux.cpp b/source/Irrlicht/CIrrDeviceLinux.cpp
index b465222..f473918 100644
--- a/source/Irrlicht/CIrrDeviceLinux.cpp
+++ b/source/Irrlicht/CIrrDeviceLinux.cpp
@@ -727,1025 +727,1025 @@ bool CIrrDeviceLinux::createWindow()
CreationParams.WindowSize.Width = Width;
CreationParams.WindowSize.Height = Height;
StdHints = XAllocSizeHints();
long num;
XGetWMNormalHints(display, window, StdHints, &num);
// create an XImage for the software renderer
//(thx to Nadav for some clues on how to do that!)
if (CreationParams.DriverType == video::EDT_SOFTWARE || CreationParams.DriverType == video::EDT_BURNINGSVIDEO)
{
SoftwareImage = XCreateImage(display,
visual->visual, visual->depth,
ZPixmap, 0, 0, Width, Height,
BitmapPad(display), 0);
// use malloc because X will free it later on
if (SoftwareImage)
SoftwareImage->data = (char*) malloc(SoftwareImage->bytes_per_line * SoftwareImage->height * sizeof(char));
}
initXAtoms();
#endif // #ifdef _IRR_COMPILE_WITH_X11_
return true;
}
//! create the driver
void CIrrDeviceLinux::createDriver()
{
switch(CreationParams.DriverType)
{
#ifdef _IRR_COMPILE_WITH_X11_
case video::EDT_SOFTWARE:
#ifdef _IRR_COMPILE_WITH_SOFTWARE_
VideoDriver = video::createSoftwareDriver(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this);
#else
os::Printer::log("No Software driver support compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_BURNINGSVIDEO:
#ifdef _IRR_COMPILE_WITH_BURNINGSVIDEO_
VideoDriver = video::createSoftwareDriver2(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this);
#else
os::Printer::log("Burning's video driver was not compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_OPENGL:
#ifdef _IRR_COMPILE_WITH_OPENGL_
if (Context)
VideoDriver = video::createOpenGLDriver(CreationParams, FileSystem, this);
#else
os::Printer::log("No OpenGL support compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_DIRECT3D8:
case video::EDT_DIRECT3D9:
os::Printer::log("This driver is not available in Linux. Try OpenGL or Software renderer.",
ELL_ERROR);
break;
case video::EDT_NULL:
VideoDriver = video::createNullDriver(FileSystem, CreationParams.WindowSize);
break;
default:
os::Printer::log("Unable to create video driver of unknown type.", ELL_ERROR);
break;
#else
case video::EDT_NULL:
VideoDriver = video::createNullDriver(FileSystem, CreationParams.WindowSize);
break;
default:
os::Printer::log("No X11 support compiled in. Only Null driver available.", ELL_ERROR);
break;
#endif
}
}
//! runs the device. Returns false if device wants to be deleted
bool CIrrDeviceLinux::run()
{
os::Timer::tick();
#ifdef _IRR_COMPILE_WITH_X11_
if ((CreationParams.DriverType != video::EDT_NULL) && display)
{
SEvent irrevent;
irrevent.MouseInput.ButtonStates = 0xffffffff;
while (XPending(display) > 0 && !Close)
{
XEvent event;
XNextEvent(display, &event);
switch (event.type)
{
case ConfigureNotify:
// check for changed window size
if ((event.xconfigure.width != (int) Width) ||
(event.xconfigure.height != (int) Height))
{
Width = event.xconfigure.width;
Height = event.xconfigure.height;
// resize image data
if (SoftwareImage)
{
XDestroyImage(SoftwareImage);
SoftwareImage = XCreateImage(display,
visual->visual, visual->depth,
ZPixmap, 0, 0, Width, Height,
BitmapPad(display), 0);
// use malloc because X will free it later on
if (SoftwareImage)
SoftwareImage->data = (char*) malloc(SoftwareImage->bytes_per_line * SoftwareImage->height * sizeof(char));
}
if (VideoDriver)
VideoDriver->OnResize(core::dimension2d<u32>(Width, Height));
}
break;
case MapNotify:
WindowMinimized=false;
break;
case UnmapNotify:
WindowMinimized=true;
break;
case FocusIn:
WindowHasFocus=true;
break;
case FocusOut:
WindowHasFocus=false;
break;
case MotionNotify:
irrevent.EventType = irr::EET_MOUSE_INPUT_EVENT;
irrevent.MouseInput.Event = irr::EMIE_MOUSE_MOVED;
irrevent.MouseInput.X = event.xbutton.x;
irrevent.MouseInput.Y = event.xbutton.y;
irrevent.MouseInput.Control = (event.xkey.state & ControlMask) != 0;
irrevent.MouseInput.Shift = (event.xkey.state & ShiftMask) != 0;
// mouse button states
irrevent.MouseInput.ButtonStates = (event.xbutton.state & Button1Mask) ? irr::EMBSM_LEFT : 0;
irrevent.MouseInput.ButtonStates |= (event.xbutton.state & Button3Mask) ? irr::EMBSM_RIGHT : 0;
irrevent.MouseInput.ButtonStates |= (event.xbutton.state & Button2Mask) ? irr::EMBSM_MIDDLE : 0;
postEventFromUser(irrevent);
break;
case ButtonPress:
case ButtonRelease:
irrevent.EventType = irr::EET_MOUSE_INPUT_EVENT;
irrevent.MouseInput.X = event.xbutton.x;
irrevent.MouseInput.Y = event.xbutton.y;
irrevent.MouseInput.Control = (event.xkey.state & ControlMask) != 0;
irrevent.MouseInput.Shift = (event.xkey.state & ShiftMask) != 0;
// mouse button states
// This sets the state which the buttons had _prior_ to the event.
// So unlike on Windows the button which just got changed has still the old state here.
// We handle that below by flipping the corresponding bit later.
irrevent.MouseInput.ButtonStates = (event.xbutton.state & Button1Mask) ? irr::EMBSM_LEFT : 0;
irrevent.MouseInput.ButtonStates |= (event.xbutton.state & Button3Mask) ? irr::EMBSM_RIGHT : 0;
irrevent.MouseInput.ButtonStates |= (event.xbutton.state & Button2Mask) ? irr::EMBSM_MIDDLE : 0;
irrevent.MouseInput.Event = irr::EMIE_COUNT;
switch(event.xbutton.button)
{
case Button1:
irrevent.MouseInput.Event =
(event.type == ButtonPress) ? irr::EMIE_LMOUSE_PRESSED_DOWN : irr::EMIE_LMOUSE_LEFT_UP;
irrevent.MouseInput.ButtonStates ^= irr::EMBSM_LEFT;
break;
case Button3:
irrevent.MouseInput.Event =
(event.type == ButtonPress) ? irr::EMIE_RMOUSE_PRESSED_DOWN : irr::EMIE_RMOUSE_LEFT_UP;
irrevent.MouseInput.ButtonStates ^= irr::EMBSM_RIGHT;
break;
case Button2:
irrevent.MouseInput.Event =
(event.type == ButtonPress) ? irr::EMIE_MMOUSE_PRESSED_DOWN : irr::EMIE_MMOUSE_LEFT_UP;
irrevent.MouseInput.ButtonStates ^= irr::EMBSM_MIDDLE;
break;
case Button4:
if (event.type == ButtonPress)
{
irrevent.MouseInput.Event = EMIE_MOUSE_WHEEL;
irrevent.MouseInput.Wheel = 1.0f;
}
break;
case Button5:
if (event.type == ButtonPress)
{
irrevent.MouseInput.Event = EMIE_MOUSE_WHEEL;
irrevent.MouseInput.Wheel = -1.0f;
}
break;
}
if (irrevent.MouseInput.Event != irr::EMIE_COUNT)
{
postEventFromUser(irrevent);
if ( irrevent.MouseInput.Event >= EMIE_LMOUSE_PRESSED_DOWN && irrevent.MouseInput.Event <= EMIE_MMOUSE_PRESSED_DOWN )
{
u32 clicks = checkSuccessiveClicks(irrevent.MouseInput.X, irrevent.MouseInput.Y, irrevent.MouseInput.Event);
if ( clicks == 2 )
{
irrevent.MouseInput.Event = (EMOUSE_INPUT_EVENT)(EMIE_LMOUSE_DOUBLE_CLICK + irrevent.MouseInput.Event-EMIE_LMOUSE_PRESSED_DOWN);
postEventFromUser(irrevent);
}
else if ( clicks == 3 )
{
irrevent.MouseInput.Event = (EMOUSE_INPUT_EVENT)(EMIE_LMOUSE_TRIPLE_CLICK + irrevent.MouseInput.Event-EMIE_LMOUSE_PRESSED_DOWN);
postEventFromUser(irrevent);
}
}
}
break;
case MappingNotify:
XRefreshKeyboardMapping (&event.xmapping) ;
break;
case KeyRelease:
if (0 == AutorepeatSupport && (XPending( display ) > 0) )
{
// check for Autorepeat manually
// We'll do the same as Windows does: Only send KeyPressed
// So every KeyRelease is a real release
XEvent next_event;
XPeekEvent (event.xkey.display, &next_event);
if ((next_event.type == KeyPress) &&
(next_event.xkey.keycode == event.xkey.keycode) &&
(next_event.xkey.time - event.xkey.time) < 2) // usually same time, but on some systems a difference of 1 is possible
{
/* Ignore the key release event */
break;
}
}
// fall-through in case the release should be handled
case KeyPress:
{
SKeyMap mp;
char buf[8]={0};
XLookupString(&event.xkey, buf, sizeof(buf), &mp.X11Key, NULL);
const s32 idx = KeyMap.binary_search(mp);
if (idx != -1)
irrevent.KeyInput.Key = (EKEY_CODE)KeyMap[idx].Win32Key;
else
{
// Usually you will check keysymdef.h and add the corresponding key to createKeyMap.
irrevent.KeyInput.Key = (EKEY_CODE)0;
os::Printer::log("Could not find win32 key for x11 key.", core::stringc((int)mp.X11Key).c_str(), ELL_WARNING);
}
irrevent.EventType = irr::EET_KEY_INPUT_EVENT;
irrevent.KeyInput.PressedDown = (event.type == KeyPress);
// mbtowc(&irrevent.KeyInput.Char, buf, sizeof(buf));
irrevent.KeyInput.Char = ((wchar_t*)(buf))[0];
irrevent.KeyInput.Control = (event.xkey.state & ControlMask) != 0;
irrevent.KeyInput.Shift = (event.xkey.state & ShiftMask) != 0;
postEventFromUser(irrevent);
}
break;
case ClientMessage:
{
char *atom = XGetAtomName(display, event.xclient.message_type);
if (*atom == *wmDeleteWindow)
{
os::Printer::log("Quit message received.", ELL_INFORMATION);
Close = true;
}
else
{
// we assume it's a user message
irrevent.EventType = irr::EET_USER_EVENT;
irrevent.UserEvent.UserData1 = (s32)event.xclient.data.l[0];
irrevent.UserEvent.UserData2 = (s32)event.xclient.data.l[1];
postEventFromUser(irrevent);
}
XFree(atom);
}
break;
case SelectionRequest:
{
XEvent respond;
XSelectionRequestEvent *req = &(event.xselectionrequest);
if ( req->target == XA_STRING)
{
XChangeProperty (display,
req->requestor,
req->property, req->target,
8, // format
PropModeReplace,
(unsigned char*) Clipboard.c_str(),
Clipboard.size());
respond.xselection.property = req->property;
}
else if ( req->target == X_ATOM_TARGETS )
{
long data[2];
data[0] = X_ATOM_TEXT;
data[1] = XA_STRING;
XChangeProperty (display, req->requestor,
req->property, req->target,
8, PropModeReplace,
(unsigned char *) &data,
sizeof (data));
respond.xselection.property = req->property;
}
else
{
respond.xselection.property= None;
}
respond.xselection.type= SelectionNotify;
respond.xselection.display= req->display;
respond.xselection.requestor= req->requestor;
respond.xselection.selection=req->selection;
respond.xselection.target= req->target;
respond.xselection.time = req->time;
XSendEvent (display, req->requestor,0,0,&respond);
XFlush (display);
}
break;
default:
break;
} // end switch
} // end while
}
#endif //_IRR_COMPILE_WITH_X11_
if(!Close)
pollJoysticks();
return !Close;
}
//! Pause the current process for the minimum time allowed only to allow other processes to execute
void CIrrDeviceLinux::yield()
{
struct timespec ts = {0,0};
nanosleep(&ts, NULL);
}
//! Pause execution and let other processes to run for a specified amount of time.
void CIrrDeviceLinux::sleep(u32 timeMs, bool pauseTimer=false)
{
const bool wasStopped = Timer ? Timer->isStopped() : true;
struct timespec ts;
ts.tv_sec = (time_t) (timeMs / 1000);
ts.tv_nsec = (long) (timeMs % 1000) * 1000000;
if (pauseTimer && !wasStopped)
Timer->stop();
nanosleep(&ts, NULL);
if (pauseTimer && !wasStopped)
Timer->start();
}
//! sets the caption of the window
void CIrrDeviceLinux::setWindowCaption(const wchar_t* text)
{
#ifdef _IRR_COMPILE_WITH_X11_
if (CreationParams.DriverType == video::EDT_NULL)
return;
XTextProperty txt;
if (Success==XwcTextListToTextProperty(display, const_cast<wchar_t**>(&text),
1, XStdICCTextStyle, &txt))
{
XSetWMName(display, window, &txt);
XSetWMIconName(display, window, &txt);
XFree(txt.value);
}
#endif
}
//! presents a surface in the client area
bool CIrrDeviceLinux::present(video::IImage* image, void* windowId, core::rect<s32>* srcRect)
{
#ifdef _IRR_COMPILE_WITH_X11_
// this is only necessary for software drivers.
if (!SoftwareImage)
return true;
// thx to Nadav, who send me some clues of how to display the image
// to the X Server.
const u32 destwidth = SoftwareImage->width;
const u32 minWidth = core::min_(image->getDimension().Width, destwidth);
const u32 destPitch = SoftwareImage->bytes_per_line;
video::ECOLOR_FORMAT destColor;
switch (SoftwareImage->bits_per_pixel)
{
case 16:
if (SoftwareImage->depth==16)
destColor = video::ECF_R5G6B5;
else
destColor = video::ECF_A1R5G5B5;
break;
case 24: destColor = video::ECF_R8G8B8; break;
case 32: destColor = video::ECF_A8R8G8B8; break;
default:
os::Printer::log("Unsupported screen depth.");
return false;
}
u8* srcdata = reinterpret_cast<u8*>(image->lock());
u8* destData = reinterpret_cast<u8*>(SoftwareImage->data);
const u32 destheight = SoftwareImage->height;
const u32 srcheight = core::min_(image->getDimension().Height, destheight);
const u32 srcPitch = image->getPitch();
for (u32 y=0; y!=srcheight; ++y)
{
video::CColorConverter::convert_viaFormat(srcdata,image->getColorFormat(), minWidth, destData, destColor);
srcdata+=srcPitch;
destData+=destPitch;
}
image->unlock();
GC gc = DefaultGC(display, DefaultScreen(display));
Window myWindow=window;
if (windowId)
myWindow = reinterpret_cast<Window>(windowId);
XPutImage(display, myWindow, gc, SoftwareImage, 0, 0, 0, 0, destwidth, destheight);
#endif
return true;
}
//! notifies the device that it should close itself
void CIrrDeviceLinux::closeDevice()
{
Close = true;
}
//! returns if window is active. if not, nothing need to be drawn
bool CIrrDeviceLinux::isWindowActive() const
{
return (WindowHasFocus && !WindowMinimized);
}
//! returns if window has focus.
bool CIrrDeviceLinux::isWindowFocused() const
{
return WindowHasFocus;
}
//! returns if window is minimized.
bool CIrrDeviceLinux::isWindowMinimized() const
{
return WindowMinimized;
}
//! returns color format of the window.
video::ECOLOR_FORMAT CIrrDeviceLinux::getColorFormat() const
{
#ifdef _IRR_COMPILE_WITH_X11_
if (visual && (visual->depth != 16))
return video::ECF_R8G8B8;
else
#endif
return video::ECF_R5G6B5;
}
//! Sets if the window should be resizable in windowed mode.
void CIrrDeviceLinux::setResizable(bool resize)
{
#ifdef _IRR_COMPILE_WITH_X11_
- if (CreationParams.DriverType == video::EDT_NULL)
+ if (CreationParams.DriverType == video::EDT_NULL || CreationParams.Fullscreen )
return;
XUnmapWindow(display, window);
if ( !resize )
{
// Must be heap memory because data size depends on X Server
XSizeHints *hints = XAllocSizeHints();
hints->flags=PSize|PMinSize|PMaxSize;
hints->min_width=hints->max_width=hints->base_width=Width;
hints->min_height=hints->max_height=hints->base_height=Height;
XSetWMNormalHints(display, window, hints);
XFree(hints);
}
else
{
XSetWMNormalHints(display, window, StdHints);
}
XMapWindow(display, window);
XFlush(display);
#endif // #ifdef _IRR_COMPILE_WITH_X11_
}
//! Return pointer to a list with all video modes supported by the gfx adapter.
video::IVideoModeList* CIrrDeviceLinux::getVideoModeList()
{
#ifdef _IRR_COMPILE_WITH_X11_
if (!VideoModeList.getVideoModeCount())
{
bool temporaryDisplay = false;
if (!display)
{
display = XOpenDisplay(0);
temporaryDisplay=true;
}
if (display)
{
#if defined(_IRR_LINUX_X11_VIDMODE_) || defined(_IRR_LINUX_X11_RANDR_)
s32 eventbase, errorbase;
s32 defaultDepth=DefaultDepth(display,screennr);
#endif
#ifdef _IRR_LINUX_X11_VIDMODE_
if (XF86VidModeQueryExtension(display, &eventbase, &errorbase))
{
// enumerate video modes
int modeCount;
XF86VidModeModeInfo** modes;
XF86VidModeGetAllModeLines(display, screennr, &modeCount, &modes);
// save current video mode
oldVideoMode = *modes[0];
// find fitting mode
VideoModeList.setDesktop(defaultDepth, core::dimension2d<u32>(
modes[0]->hdisplay, modes[0]->vdisplay));
for (int i = 0; i<modeCount; ++i)
{
VideoModeList.addMode(core::dimension2d<u32>(
modes[i]->hdisplay, modes[i]->vdisplay), defaultDepth);
}
XFree(modes);
}
else
#endif
#ifdef _IRR_LINUX_X11_RANDR_
if (XRRQueryExtension(display, &eventbase, &errorbase))
{
int modeCount;
XRRScreenConfiguration *config=XRRGetScreenInfo(display,DefaultRootWindow(display));
oldRandrMode=XRRConfigCurrentConfiguration(config,&oldRandrRotation);
XRRScreenSize *modes=XRRConfigSizes(config,&modeCount);
VideoModeList.setDesktop(defaultDepth, core::dimension2d<u32>(
modes[oldRandrMode].width, modes[oldRandrMode].height));
for (int i = 0; i<modeCount; ++i)
{
VideoModeList.addMode(core::dimension2d<u32>(
modes[i].width, modes[i].height), defaultDepth);
}
XRRFreeScreenConfigInfo(config);
}
else
#endif
{
os::Printer::log("VidMode or RandR X11 extension requireed for VideoModeList." , ELL_WARNING);
}
}
if (display && temporaryDisplay)
{
XCloseDisplay(display);
display=0;
}
}
#endif
return &VideoModeList;
}
//! Minimize window
void CIrrDeviceLinux::minimizeWindow()
{
#ifdef _IRR_COMPILE_WITH_X11_
XIconifyWindow(display, window, screennr);
#endif
}
//! Maximize window
void CIrrDeviceLinux::maximizeWindow()
{
#ifdef _IRR_COMPILE_WITH_X11_
XMapWindow(display, window);
#endif
}
//! Restore original window size
void CIrrDeviceLinux::restoreWindow()
{
#ifdef _IRR_COMPILE_WITH_X11_
XMapWindow(display, window);
#endif
}
void CIrrDeviceLinux::createKeyMap()
{
// I don't know if this is the best method to create
// the lookuptable, but I'll leave it like that until
// I find a better version.
#ifdef _IRR_COMPILE_WITH_X11_
KeyMap.reallocate(84);
KeyMap.push_back(SKeyMap(XK_BackSpace, KEY_BACK));
KeyMap.push_back(SKeyMap(XK_Tab, KEY_TAB));
KeyMap.push_back(SKeyMap(XK_ISO_Left_Tab, KEY_TAB));
KeyMap.push_back(SKeyMap(XK_Linefeed, 0)); // ???
KeyMap.push_back(SKeyMap(XK_Clear, KEY_CLEAR));
KeyMap.push_back(SKeyMap(XK_Return, KEY_RETURN));
KeyMap.push_back(SKeyMap(XK_Pause, KEY_PAUSE));
KeyMap.push_back(SKeyMap(XK_Scroll_Lock, KEY_SCROLL));
KeyMap.push_back(SKeyMap(XK_Sys_Req, 0)); // ???
KeyMap.push_back(SKeyMap(XK_Escape, KEY_ESCAPE));
KeyMap.push_back(SKeyMap(XK_Insert, KEY_INSERT));
KeyMap.push_back(SKeyMap(XK_Delete, KEY_DELETE));
KeyMap.push_back(SKeyMap(XK_Home, KEY_HOME));
KeyMap.push_back(SKeyMap(XK_Left, KEY_LEFT));
KeyMap.push_back(SKeyMap(XK_Up, KEY_UP));
KeyMap.push_back(SKeyMap(XK_Right, KEY_RIGHT));
KeyMap.push_back(SKeyMap(XK_Down, KEY_DOWN));
KeyMap.push_back(SKeyMap(XK_Prior, KEY_PRIOR));
KeyMap.push_back(SKeyMap(XK_Page_Up, KEY_PRIOR));
KeyMap.push_back(SKeyMap(XK_Next, KEY_NEXT));
KeyMap.push_back(SKeyMap(XK_Page_Down, KEY_NEXT));
KeyMap.push_back(SKeyMap(XK_End, KEY_END));
KeyMap.push_back(SKeyMap(XK_Begin, KEY_HOME));
KeyMap.push_back(SKeyMap(XK_Num_Lock, KEY_NUMLOCK));
KeyMap.push_back(SKeyMap(XK_KP_Space, KEY_SPACE));
KeyMap.push_back(SKeyMap(XK_KP_Tab, KEY_TAB));
KeyMap.push_back(SKeyMap(XK_KP_Enter, KEY_RETURN));
KeyMap.push_back(SKeyMap(XK_KP_F1, KEY_F1));
KeyMap.push_back(SKeyMap(XK_KP_F2, KEY_F2));
KeyMap.push_back(SKeyMap(XK_KP_F3, KEY_F3));
KeyMap.push_back(SKeyMap(XK_KP_F4, KEY_F4));
KeyMap.push_back(SKeyMap(XK_KP_Home, KEY_HOME));
KeyMap.push_back(SKeyMap(XK_KP_Left, KEY_LEFT));
KeyMap.push_back(SKeyMap(XK_KP_Up, KEY_UP));
KeyMap.push_back(SKeyMap(XK_KP_Right, KEY_RIGHT));
KeyMap.push_back(SKeyMap(XK_KP_Down, KEY_DOWN));
KeyMap.push_back(SKeyMap(XK_Print, KEY_PRINT));
KeyMap.push_back(SKeyMap(XK_KP_Prior, KEY_PRIOR));
KeyMap.push_back(SKeyMap(XK_KP_Page_Up, KEY_PRIOR));
KeyMap.push_back(SKeyMap(XK_KP_Next, KEY_NEXT));
KeyMap.push_back(SKeyMap(XK_KP_Page_Down, KEY_NEXT));
KeyMap.push_back(SKeyMap(XK_KP_End, KEY_END));
KeyMap.push_back(SKeyMap(XK_KP_Begin, KEY_HOME));
KeyMap.push_back(SKeyMap(XK_KP_Insert, KEY_INSERT));
KeyMap.push_back(SKeyMap(XK_KP_Delete, KEY_DELETE));
KeyMap.push_back(SKeyMap(XK_KP_Equal, 0)); // ???
KeyMap.push_back(SKeyMap(XK_KP_Multiply, KEY_MULTIPLY));
KeyMap.push_back(SKeyMap(XK_KP_Add, KEY_ADD));
KeyMap.push_back(SKeyMap(XK_KP_Separator, KEY_SEPARATOR));
KeyMap.push_back(SKeyMap(XK_KP_Subtract, KEY_SUBTRACT));
KeyMap.push_back(SKeyMap(XK_KP_Decimal, KEY_DECIMAL));
KeyMap.push_back(SKeyMap(XK_KP_Divide, KEY_DIVIDE));
KeyMap.push_back(SKeyMap(XK_KP_0, KEY_KEY_0));
KeyMap.push_back(SKeyMap(XK_KP_1, KEY_KEY_1));
KeyMap.push_back(SKeyMap(XK_KP_2, KEY_KEY_2));
KeyMap.push_back(SKeyMap(XK_KP_3, KEY_KEY_3));
KeyMap.push_back(SKeyMap(XK_KP_4, KEY_KEY_4));
KeyMap.push_back(SKeyMap(XK_KP_5, KEY_KEY_5));
KeyMap.push_back(SKeyMap(XK_KP_6, KEY_KEY_6));
KeyMap.push_back(SKeyMap(XK_KP_7, KEY_KEY_7));
KeyMap.push_back(SKeyMap(XK_KP_8, KEY_KEY_8));
KeyMap.push_back(SKeyMap(XK_KP_9, KEY_KEY_9));
KeyMap.push_back(SKeyMap(XK_F1, KEY_F1));
KeyMap.push_back(SKeyMap(XK_F2, KEY_F2));
KeyMap.push_back(SKeyMap(XK_F3, KEY_F3));
KeyMap.push_back(SKeyMap(XK_F4, KEY_F4));
KeyMap.push_back(SKeyMap(XK_F5, KEY_F5));
KeyMap.push_back(SKeyMap(XK_F6, KEY_F6));
KeyMap.push_back(SKeyMap(XK_F7, KEY_F7));
KeyMap.push_back(SKeyMap(XK_F8, KEY_F8));
KeyMap.push_back(SKeyMap(XK_F9, KEY_F9));
KeyMap.push_back(SKeyMap(XK_F10, KEY_F10));
KeyMap.push_back(SKeyMap(XK_F11, KEY_F11));
KeyMap.push_back(SKeyMap(XK_F12, KEY_F12));
KeyMap.push_back(SKeyMap(XK_Shift_L, KEY_LSHIFT));
KeyMap.push_back(SKeyMap(XK_Shift_R, KEY_RSHIFT));
KeyMap.push_back(SKeyMap(XK_Control_L, KEY_LCONTROL));
KeyMap.push_back(SKeyMap(XK_Control_R, KEY_RCONTROL));
KeyMap.push_back(SKeyMap(XK_Caps_Lock, KEY_CAPITAL));
KeyMap.push_back(SKeyMap(XK_Shift_Lock, KEY_CAPITAL));
KeyMap.push_back(SKeyMap(XK_Meta_L, KEY_LWIN));
KeyMap.push_back(SKeyMap(XK_Meta_R, KEY_RWIN));
KeyMap.push_back(SKeyMap(XK_Alt_L, KEY_LMENU));
KeyMap.push_back(SKeyMap(XK_Alt_R, KEY_RMENU));
KeyMap.push_back(SKeyMap(XK_ISO_Level3_Shift, KEY_RMENU));
KeyMap.push_back(SKeyMap(XK_Menu, KEY_MENU));
KeyMap.push_back(SKeyMap(XK_space, KEY_SPACE));
KeyMap.push_back(SKeyMap(XK_exclam, 0)); //?
KeyMap.push_back(SKeyMap(XK_quotedbl, 0)); //?
KeyMap.push_back(SKeyMap(XK_section, 0)); //?
KeyMap.push_back(SKeyMap(XK_numbersign, 0)); //?
KeyMap.push_back(SKeyMap(XK_dollar, 0)); //?
KeyMap.push_back(SKeyMap(XK_percent, 0)); //?
KeyMap.push_back(SKeyMap(XK_ampersand, 0)); //?
KeyMap.push_back(SKeyMap(XK_apostrophe, 0)); //?
KeyMap.push_back(SKeyMap(XK_parenleft, 0)); //?
KeyMap.push_back(SKeyMap(XK_parenright, 0)); //?
KeyMap.push_back(SKeyMap(XK_asterisk, 0)); //?
KeyMap.push_back(SKeyMap(XK_plus, KEY_PLUS)); //?
KeyMap.push_back(SKeyMap(XK_comma, KEY_COMMA)); //?
KeyMap.push_back(SKeyMap(XK_minus, KEY_MINUS)); //?
KeyMap.push_back(SKeyMap(XK_period, KEY_PERIOD)); //?
KeyMap.push_back(SKeyMap(XK_slash, 0)); //?
KeyMap.push_back(SKeyMap(XK_0, KEY_KEY_0));
KeyMap.push_back(SKeyMap(XK_1, KEY_KEY_1));
KeyMap.push_back(SKeyMap(XK_2, KEY_KEY_2));
KeyMap.push_back(SKeyMap(XK_3, KEY_KEY_3));
KeyMap.push_back(SKeyMap(XK_4, KEY_KEY_4));
KeyMap.push_back(SKeyMap(XK_5, KEY_KEY_5));
KeyMap.push_back(SKeyMap(XK_6, KEY_KEY_6));
KeyMap.push_back(SKeyMap(XK_7, KEY_KEY_7));
KeyMap.push_back(SKeyMap(XK_8, KEY_KEY_8));
KeyMap.push_back(SKeyMap(XK_9, KEY_KEY_9));
KeyMap.push_back(SKeyMap(XK_colon, 0)); //?
KeyMap.push_back(SKeyMap(XK_semicolon, 0)); //?
KeyMap.push_back(SKeyMap(XK_less, 0)); //?
KeyMap.push_back(SKeyMap(XK_equal, 0)); //?
KeyMap.push_back(SKeyMap(XK_greater, 0)); //?
KeyMap.push_back(SKeyMap(XK_question, 0)); //?
KeyMap.push_back(SKeyMap(XK_at, 0)); //?
KeyMap.push_back(SKeyMap(XK_mu, 0)); //?
KeyMap.push_back(SKeyMap(XK_EuroSign, 0)); //?
KeyMap.push_back(SKeyMap(XK_A, KEY_KEY_A));
KeyMap.push_back(SKeyMap(XK_B, KEY_KEY_B));
KeyMap.push_back(SKeyMap(XK_C, KEY_KEY_C));
KeyMap.push_back(SKeyMap(XK_D, KEY_KEY_D));
KeyMap.push_back(SKeyMap(XK_E, KEY_KEY_E));
KeyMap.push_back(SKeyMap(XK_F, KEY_KEY_F));
KeyMap.push_back(SKeyMap(XK_G, KEY_KEY_G));
KeyMap.push_back(SKeyMap(XK_H, KEY_KEY_H));
KeyMap.push_back(SKeyMap(XK_I, KEY_KEY_I));
KeyMap.push_back(SKeyMap(XK_J, KEY_KEY_J));
KeyMap.push_back(SKeyMap(XK_K, KEY_KEY_K));
KeyMap.push_back(SKeyMap(XK_L, KEY_KEY_L));
KeyMap.push_back(SKeyMap(XK_M, KEY_KEY_M));
KeyMap.push_back(SKeyMap(XK_N, KEY_KEY_N));
KeyMap.push_back(SKeyMap(XK_O, KEY_KEY_O));
KeyMap.push_back(SKeyMap(XK_P, KEY_KEY_P));
KeyMap.push_back(SKeyMap(XK_Q, KEY_KEY_Q));
KeyMap.push_back(SKeyMap(XK_R, KEY_KEY_R));
KeyMap.push_back(SKeyMap(XK_S, KEY_KEY_S));
KeyMap.push_back(SKeyMap(XK_T, KEY_KEY_T));
KeyMap.push_back(SKeyMap(XK_U, KEY_KEY_U));
KeyMap.push_back(SKeyMap(XK_V, KEY_KEY_V));
KeyMap.push_back(SKeyMap(XK_W, KEY_KEY_W));
KeyMap.push_back(SKeyMap(XK_X, KEY_KEY_X));
KeyMap.push_back(SKeyMap(XK_Y, KEY_KEY_Y));
KeyMap.push_back(SKeyMap(XK_Z, KEY_KEY_Z));
KeyMap.push_back(SKeyMap(XK_Adiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_Odiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_Udiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_bracketleft, 0)); //?
KeyMap.push_back(SKeyMap(XK_backslash, 0)); //?
KeyMap.push_back(SKeyMap(XK_bracketright, 0)); //?
KeyMap.push_back(SKeyMap(XK_asciicircum, 0)); //?
KeyMap.push_back(SKeyMap(XK_degree, 0)); //?
KeyMap.push_back(SKeyMap(XK_underscore, 0)); //?
KeyMap.push_back(SKeyMap(XK_grave, 0)); //?
KeyMap.push_back(SKeyMap(XK_acute, 0)); //?
KeyMap.push_back(SKeyMap(XK_quoteleft, 0)); //?
KeyMap.push_back(SKeyMap(XK_a, KEY_KEY_A));
KeyMap.push_back(SKeyMap(XK_b, KEY_KEY_B));
KeyMap.push_back(SKeyMap(XK_c, KEY_KEY_C));
KeyMap.push_back(SKeyMap(XK_d, KEY_KEY_D));
KeyMap.push_back(SKeyMap(XK_e, KEY_KEY_E));
KeyMap.push_back(SKeyMap(XK_f, KEY_KEY_F));
KeyMap.push_back(SKeyMap(XK_g, KEY_KEY_G));
KeyMap.push_back(SKeyMap(XK_h, KEY_KEY_H));
KeyMap.push_back(SKeyMap(XK_i, KEY_KEY_I));
KeyMap.push_back(SKeyMap(XK_j, KEY_KEY_J));
KeyMap.push_back(SKeyMap(XK_k, KEY_KEY_K));
KeyMap.push_back(SKeyMap(XK_l, KEY_KEY_L));
KeyMap.push_back(SKeyMap(XK_m, KEY_KEY_M));
KeyMap.push_back(SKeyMap(XK_n, KEY_KEY_N));
KeyMap.push_back(SKeyMap(XK_o, KEY_KEY_O));
KeyMap.push_back(SKeyMap(XK_p, KEY_KEY_P));
KeyMap.push_back(SKeyMap(XK_q, KEY_KEY_Q));
KeyMap.push_back(SKeyMap(XK_r, KEY_KEY_R));
KeyMap.push_back(SKeyMap(XK_s, KEY_KEY_S));
KeyMap.push_back(SKeyMap(XK_t, KEY_KEY_T));
KeyMap.push_back(SKeyMap(XK_u, KEY_KEY_U));
KeyMap.push_back(SKeyMap(XK_v, KEY_KEY_V));
KeyMap.push_back(SKeyMap(XK_w, KEY_KEY_W));
KeyMap.push_back(SKeyMap(XK_x, KEY_KEY_X));
KeyMap.push_back(SKeyMap(XK_y, KEY_KEY_Y));
KeyMap.push_back(SKeyMap(XK_z, KEY_KEY_Z));
KeyMap.push_back(SKeyMap(XK_ssharp, 0)); //?
KeyMap.push_back(SKeyMap(XK_adiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_odiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_udiaeresis, 0)); //?
KeyMap.sort();
#endif
}
bool CIrrDeviceLinux::activateJoysticks(core::array<SJoystickInfo> & joystickInfo)
{
#if defined (_IRR_COMPILE_WITH_JOYSTICK_EVENTS_)
joystickInfo.clear();
u32 joystick;
for(joystick = 0; joystick < 32; ++joystick)
{
// The joystick device could be here...
core::stringc devName = "/dev/js";
devName += joystick;
SJoystickInfo returnInfo;
JoystickInfo info;
info.fd = open(devName.c_str(), O_RDONLY);
if(-1 == info.fd)
{
// ...but Ubuntu and possibly other distros
// create the devices in /dev/input
devName = "/dev/input/js";
devName += joystick;
info.fd = open(devName.c_str(), O_RDONLY);
if(-1 == info.fd)
{
// and BSD here
devName = "/dev/joy";
devName += joystick;
info.fd = open(devName.c_str(), O_RDONLY);
}
}
if(-1 == info.fd)
continue;
#ifdef __FREE_BSD_
info.axes=2;
info.buttons=2;
#else
ioctl( info.fd, JSIOCGAXES, &(info.axes) );
ioctl( info.fd, JSIOCGBUTTONS, &(info.buttons) );
fcntl( info.fd, F_SETFL, O_NONBLOCK );
#endif
(void)memset(&info.persistentData, 0, sizeof(info.persistentData));
info.persistentData.EventType = irr::EET_JOYSTICK_INPUT_EVENT;
info.persistentData.JoystickEvent.Joystick = ActiveJoysticks.size();
// There's no obvious way to determine which (if any) axes represent a POV
// hat, so we'll just set it to "not used" and forget about it.
info.persistentData.JoystickEvent.POV = 65535;
ActiveJoysticks.push_back(info);
returnInfo.Joystick = joystick;
returnInfo.PovHat = SJoystickInfo::POV_HAT_UNKNOWN;
returnInfo.Axes = info.axes;
returnInfo.Buttons = info.buttons;
#ifndef __FREE_BSD_
char name[80];
ioctl( info.fd, JSIOCGNAME(80), name);
returnInfo.Name = name;
#endif
joystickInfo.push_back(returnInfo);
}
for(joystick = 0; joystick < joystickInfo.size(); ++joystick)
{
char logString[256];
(void)sprintf(logString, "Found joystick %u, %u axes, %u buttons '%s'",
joystick, joystickInfo[joystick].Axes,
joystickInfo[joystick].Buttons, joystickInfo[joystick].Name.c_str());
os::Printer::log(logString, ELL_INFORMATION);
}
return true;
#else
return false;
#endif // _IRR_COMPILE_WITH_JOYSTICK_EVENTS_
}
void CIrrDeviceLinux::pollJoysticks()
{
#if defined (_IRR_COMPILE_WITH_JOYSTICK_EVENTS_)
if(0 == ActiveJoysticks.size())
return;
u32 j;
for(j= 0; j< ActiveJoysticks.size(); ++j)
{
JoystickInfo & info = ActiveJoysticks[j];
#ifdef __FREE_BSD_
struct joystick js;
if( read( info.fd, &js, JS_RETURN ) == JS_RETURN )
{
info.persistentData.JoystickEvent.ButtonStates = js.buttons; /* should be a two-bit field */
info.persistentData.JoystickEvent.Axis[0] = js.x; /* X axis */
info.persistentData.JoystickEvent.Axis[1] = js.y; /* Y axis */
#else
struct js_event event;
while(sizeof(event) == read(info.fd, &event, sizeof(event)))
{
switch(event.type & ~JS_EVENT_INIT)
{
case JS_EVENT_BUTTON:
if (event.value)
info.persistentData.JoystickEvent.ButtonStates |= (1 << event.number);
else
info.persistentData.JoystickEvent.ButtonStates &= ~(1 << event.number);
break;
case JS_EVENT_AXIS:
info.persistentData.JoystickEvent.Axis[event.number] = event.value;
break;
default:
break;
}
}
#endif
// Send an irrlicht joystick event once per ::run() even if no new data were received.
(void)postEventFromUser(info.persistentData);
}
#endif // _IRR_COMPILE_WITH_JOYSTICK_EVENTS_
}
//! Set the current Gamma Value for the Display
bool CIrrDeviceLinux::setGammaRamp( f32 red, f32 green, f32 blue, f32 brightness, f32 contrast )
{
#if defined(_IRR_LINUX_X11_VIDMODE_) || defined(_IRR_LINUX_X11_RANDR_)
s32 eventbase, errorbase;
#ifdef _IRR_LINUX_X11_VIDMODE_
if (XF86VidModeQueryExtension(display, &eventbase, &errorbase))
{
XF86VidModeGamma gamma;
gamma.red=red;
gamma.green=green;
gamma.blue=blue;
XF86VidModeSetGamma(display, screennr, &gamma);
return true;
}
#endif
#if defined(_IRR_LINUX_X11_VIDMODE_) && defined(_IRR_LINUX_X11_RANDR_)
else
#endif
#ifdef _IRR_LINUX_X11_RANDR_
if (XRRQueryExtension(display, &eventbase, &errorbase))
{
XRRQueryVersion(display, &eventbase, &errorbase); // major, minor
if (eventbase>=1 && errorbase>1)
{
#if (RANDR_MAJOR>1 || RANDR_MINOR>1)
XRRCrtcGamma *gamma = XRRGetCrtcGamma(display, screennr);
if (gamma)
{
*gamma->red=(u16)red;
*gamma->green=(u16)green;
*gamma->blue=(u16)blue;
XRRSetCrtcGamma(display, screennr, gamma);
XRRFreeGamma(gamma);
return true;
}
#endif
}
}
#endif
#endif
return false;
}
//! Get the current Gamma Value for the Display
bool CIrrDeviceLinux::getGammaRamp( f32 &red, f32 &green, f32 &blue, f32 &brightness, f32 &contrast )
|
paupawsan/Irrlicht
|
0d378d519f87a521afe02df74dbab26e32152e60
|
Work around a crash when pressing ESC after closing a Messagebox (found by Acki)
|
diff --git a/source/Irrlicht/CGUIMessageBox.cpp b/source/Irrlicht/CGUIMessageBox.cpp
index d9ec694..c4a8314 100644
--- a/source/Irrlicht/CGUIMessageBox.cpp
+++ b/source/Irrlicht/CGUIMessageBox.cpp
@@ -1,447 +1,463 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CGUIMessageBox.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include "IGUISkin.h"
#include "IGUIEnvironment.h"
#include "IGUIButton.h"
#include "IGUIFont.h"
#include "ITexture.h"
namespace irr
{
namespace gui
{
//! constructor
CGUIMessageBox::CGUIMessageBox(IGUIEnvironment* environment, const wchar_t* caption,
const wchar_t* text, s32 flags,
IGUIElement* parent, s32 id, core::rect<s32> rectangle, video::ITexture* image)
: CGUIWindow(environment, parent, id, rectangle),
OkButton(0), CancelButton(0), YesButton(0), NoButton(0), StaticText(0),
Icon(0), IconTexture(image),
Flags(flags), MessageText(text), Pressed(false)
{
#ifdef _DEBUG
setDebugName("CGUIMessageBox");
#endif
// set element type
Type = EGUIET_MESSAGE_BOX;
// remove focus
Environment->setFocus(0);
// remove buttons
getMaximizeButton()->remove();
getMinimizeButton()->remove();
if (caption)
setText(caption);
Environment->setFocus(this);
if ( IconTexture )
IconTexture->grab();
refreshControls();
}
//! destructor
CGUIMessageBox::~CGUIMessageBox()
{
if (StaticText)
StaticText->drop();
if (OkButton)
OkButton->drop();
if (CancelButton)
CancelButton->drop();
if (YesButton)
YesButton->drop();
if (NoButton)
NoButton->drop();
if (Icon)
Icon->drop();
if ( IconTexture )
IconTexture->drop();
}
void CGUIMessageBox::setButton(IGUIButton*& button, bool isAvailable, const core::rect<s32> & btnRect, const wchar_t * text, IGUIElement*& focusMe)
{
// add/remove ok button
if (isAvailable)
{
if (!button)
{
button = Environment->addButton(btnRect, this);
button->setSubElement(true);
button->grab();
}
else
button->setRelativePosition(btnRect);
button->setText(text);
focusMe = button;
}
else if (button)
{
button->drop();
button->remove();
button =0;
}
}
void CGUIMessageBox::refreshControls()
{
// Layout can be seen as 4 boxes (a layoutmanager would be nice)
// One box at top over the whole width for title
// Two boxes with same height at the middle beside each other for icon and for text
// One box at the bottom for the buttons
const IGUISkin* skin = Environment->getSkin();
const s32 buttonHeight = skin->getSize(EGDS_BUTTON_HEIGHT);
const s32 buttonWidth = skin->getSize(EGDS_BUTTON_WIDTH);
const s32 titleHeight = skin->getSize(EGDS_WINDOW_BUTTON_WIDTH)+2; // titlebar has no own constant
const s32 buttonDistance = skin->getSize(EGDS_WINDOW_BUTTON_WIDTH);
const s32 borderWidth = skin->getSize(EGDS_MESSAGE_BOX_GAP_SPACE);
// add the static text for the message
core::rect<s32> staticRect;
staticRect.UpperLeftCorner.X = borderWidth;
staticRect.UpperLeftCorner.Y = titleHeight + borderWidth;
staticRect.LowerRightCorner.X = staticRect.UpperLeftCorner.X + skin->getSize(EGDS_MESSAGE_BOX_MAX_TEST_WIDTH);
staticRect.LowerRightCorner.Y = staticRect.UpperLeftCorner.Y + skin->getSize(EGDS_MESSAGE_BOX_MAX_TEXT_HEIGHT);
if (!StaticText)
{
StaticText = Environment->addStaticText(MessageText.c_str(), staticRect, false, false, this);
StaticText->setWordWrap(true);
StaticText->setSubElement(true);
StaticText->grab();
}
else
{
StaticText->setRelativePosition(staticRect);
StaticText->setText(MessageText.c_str());
}
s32 textHeight = StaticText->getTextHeight();
s32 textWidth = StaticText->getTextWidth() + 6; // +6 because the static itself needs that
const s32 iconHeight = IconTexture ? IconTexture->getOriginalSize().Height : 0;
if ( textWidth < skin->getSize(EGDS_MESSAGE_BOX_MIN_TEXT_WIDTH) )
textWidth = skin->getSize(EGDS_MESSAGE_BOX_MIN_TEXT_WIDTH) + 6;
// no neeed to check for max because it couldn't get larger due to statictextbox.
if ( textHeight < skin->getSize(EGDS_MESSAGE_BOX_MIN_TEXT_HEIGHT) )
textHeight = skin->getSize(EGDS_MESSAGE_BOX_MIN_TEXT_HEIGHT);
if ( textHeight > skin->getSize(EGDS_MESSAGE_BOX_MAX_TEXT_HEIGHT) )
textHeight = skin->getSize(EGDS_MESSAGE_BOX_MAX_TEXT_HEIGHT);
// content is text + icons + borders (but not titlebar)
s32 contentHeight = textHeight > iconHeight ? textHeight : iconHeight;
contentHeight += borderWidth;
s32 contentWidth = 0;
// add icon
if ( IconTexture )
{
core::position2d<s32> iconPos;
iconPos.Y = titleHeight + borderWidth;
if ( iconHeight < textHeight )
iconPos.Y += (textHeight-iconHeight) / 2;
iconPos.X = borderWidth;
if (!Icon)
{
Icon = Environment->addImage(IconTexture, iconPos, true, this);
Icon->setSubElement(true);
Icon->grab();
}
else
{
core::rect<s32> iconRect( iconPos.X, iconPos.Y, iconPos.X + IconTexture->getOriginalSize().Width, iconPos.Y + IconTexture->getOriginalSize().Height );
Icon->setRelativePosition(iconRect);
}
contentWidth += borderWidth + IconTexture->getOriginalSize().Width;
}
else if ( Icon )
{
Icon->drop();
Icon->remove();
Icon = 0;
}
// position text
core::rect<s32> textRect;
textRect.UpperLeftCorner.X = contentWidth + borderWidth;
textRect.UpperLeftCorner.Y = titleHeight + borderWidth;
if ( textHeight < iconHeight )
textRect.UpperLeftCorner.Y += (iconHeight-textHeight) / 2;
textRect.LowerRightCorner.X = textRect.UpperLeftCorner.X + textWidth;
textRect.LowerRightCorner.Y = textRect.UpperLeftCorner.Y + textHeight;
contentWidth += 2*borderWidth + textWidth;
StaticText->setRelativePosition( textRect );
// find out button size needs
s32 countButtons = 0;
if (Flags & EMBF_OK)
++countButtons;
if (Flags & EMBF_CANCEL)
++countButtons;
if (Flags & EMBF_YES)
++countButtons;
if (Flags & EMBF_NO)
++countButtons;
s32 buttonBoxWidth = countButtons * buttonWidth + 2 * borderWidth;
if ( countButtons > 1 )
buttonBoxWidth += (countButtons-1) * buttonDistance;
s32 buttonBoxHeight = buttonHeight + 2 * borderWidth;
// calc new message box sizes
core::rect<s32> tmp = getRelativePosition();
s32 msgBoxHeight = titleHeight + contentHeight + buttonBoxHeight;
s32 msgBoxWidth = contentWidth > buttonBoxWidth ? contentWidth : buttonBoxWidth;
// adjust message box position
tmp.UpperLeftCorner.Y = (Parent->getAbsolutePosition().getHeight() - msgBoxHeight) / 2;
tmp.LowerRightCorner.Y = tmp.UpperLeftCorner.Y + msgBoxHeight;
tmp.UpperLeftCorner.X = (Parent->getAbsolutePosition().getWidth() - msgBoxWidth) / 2;
tmp.LowerRightCorner.X = tmp.UpperLeftCorner.X + msgBoxWidth;
setRelativePosition(tmp);
// add buttons
core::rect<s32> btnRect;
btnRect.UpperLeftCorner.Y = titleHeight + contentHeight + borderWidth;
btnRect.LowerRightCorner.Y = btnRect.UpperLeftCorner.Y + buttonHeight;
btnRect.UpperLeftCorner.X = borderWidth;
if ( contentWidth > buttonBoxWidth )
btnRect.UpperLeftCorner.X += (contentWidth - buttonBoxWidth) / 2; // center buttons
btnRect.LowerRightCorner.X = btnRect.UpperLeftCorner.X + buttonWidth;
IGUIElement* focusMe = 0;
setButton(OkButton, (Flags & EMBF_OK) != 0, btnRect, skin->getDefaultText(EGDT_MSG_BOX_OK), focusMe);
if ( Flags & EMBF_OK )
btnRect += core::position2d<s32>(buttonWidth + buttonDistance, 0);
setButton(CancelButton, (Flags & EMBF_CANCEL) != 0, btnRect, skin->getDefaultText(EGDT_MSG_BOX_CANCEL), focusMe);
if ( Flags & EMBF_CANCEL )
btnRect += core::position2d<s32>(buttonWidth + buttonDistance, 0);
setButton(YesButton, (Flags & EMBF_YES) != 0, btnRect, skin->getDefaultText(EGDT_MSG_BOX_YES), focusMe);
if ( Flags & EMBF_YES )
btnRect += core::position2d<s32>(buttonWidth + buttonDistance, 0);
setButton(NoButton, (Flags & EMBF_NO) != 0, btnRect, skin->getDefaultText(EGDT_MSG_BOX_NO), focusMe);
if (Environment->hasFocus(this) && focusMe)
Environment->setFocus(focusMe);
}
//! called if an event happened.
bool CGUIMessageBox::OnEvent(const SEvent& event)
{
if (IsEnabled)
{
SEvent outevent;
outevent.EventType = EET_GUI_EVENT;
outevent.GUIEvent.Caller = this;
outevent.GUIEvent.Element = 0;
switch(event.EventType)
{
case EET_KEY_INPUT_EVENT:
if (event.KeyInput.PressedDown)
{
switch (event.KeyInput.Key)
{
case KEY_RETURN:
if (OkButton)
{
OkButton->setPressed(true);
Pressed = true;
}
break;
case KEY_KEY_Y:
if (YesButton)
{
YesButton->setPressed(true);
Pressed = true;
}
break;
case KEY_KEY_N:
if (NoButton)
{
NoButton->setPressed(true);
Pressed = true;
}
break;
case KEY_ESCAPE:
if (Pressed)
{
// cancel press
if (OkButton) OkButton->setPressed(false);
if (YesButton) YesButton->setPressed(false);
if (NoButton) NoButton->setPressed(false);
Pressed = false;
}
else
if (CancelButton)
{
CancelButton->setPressed(true);
Pressed = true;
}
else
if (CloseButton && CloseButton->isVisible())
{
CloseButton->setPressed(true);
Pressed = true;
}
break;
default: // no other key is handled here
break;
}
}
else
if (Pressed)
{
if (OkButton && event.KeyInput.Key == KEY_RETURN)
{
+ setVisible(false); // this is a workaround to make sure it's no longer the hovered element, crashes on pressing 1-2 times ESC
+ Environment->setFocus(0);
outevent.GUIEvent.EventType = EGET_MESSAGEBOX_OK;
Parent->OnEvent(outevent);
remove();
return true;
}
else
if ((CancelButton || CloseButton) && event.KeyInput.Key == KEY_ESCAPE)
{
+ setVisible(false); // this is a workaround to make sure it's no longer the hovered element, crashes on pressing 1-2 times ESC
+ Environment->setFocus(0);
outevent.GUIEvent.EventType = EGET_MESSAGEBOX_CANCEL;
Parent->OnEvent(outevent);
remove();
return true;
}
else
if (YesButton && event.KeyInput.Key == KEY_KEY_Y)
{
+ setVisible(false); // this is a workaround to make sure it's no longer the hovered element, crashes on pressing 1-2 times ESC
+ Environment->setFocus(0);
outevent.GUIEvent.EventType = EGET_MESSAGEBOX_YES;
Parent->OnEvent(outevent);
remove();
return true;
}
else
if (NoButton && event.KeyInput.Key == KEY_KEY_N)
{
+ setVisible(false); // this is a workaround to make sure it's no longer the hovered element, crashes on pressing 1-2 times ESC
+ Environment->setFocus(0);
outevent.GUIEvent.EventType = EGET_MESSAGEBOX_NO;
Parent->OnEvent(outevent);
remove();
return true;
}
}
break;
case EET_GUI_EVENT:
if (event.GUIEvent.EventType == EGET_BUTTON_CLICKED)
{
if (event.GUIEvent.Caller == OkButton)
{
+ setVisible(false); // this is a workaround to make sure it's no longer the hovered element, crashes on pressing 1-2 times ESC
+ Environment->setFocus(0);
outevent.GUIEvent.EventType = EGET_MESSAGEBOX_OK;
Parent->OnEvent(outevent);
remove();
return true;
}
else
if (event.GUIEvent.Caller == CancelButton ||
event.GUIEvent.Caller == CloseButton)
{
+ setVisible(false); // this is a workaround to make sure it's no longer the hovered element, crashes on pressing 1-2 times ESC
+ Environment->setFocus(0);
outevent.GUIEvent.EventType = EGET_MESSAGEBOX_CANCEL;
Parent->OnEvent(outevent);
remove();
return true;
}
else
if (event.GUIEvent.Caller == YesButton)
{
+ setVisible(false); // this is a workaround to make sure it's no longer the hovered element, crashes on pressing 1-2 times ESC
+ Environment->setFocus(0);
outevent.GUIEvent.EventType = EGET_MESSAGEBOX_YES;
Parent->OnEvent(outevent);
remove();
return true;
}
else
if (event.GUIEvent.Caller == NoButton)
{
+ setVisible(false); // this is a workaround to make sure it's no longer the hovered element, crashes on pressing 1-2 times ESC
+ Environment->setFocus(0);
outevent.GUIEvent.EventType = EGET_MESSAGEBOX_NO;
Parent->OnEvent(outevent);
remove();
return true;
}
}
break;
default:
break;
}
}
return CGUIWindow::OnEvent(event);
}
//! Writes attributes of the element.
void CGUIMessageBox::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const
{
CGUIWindow::serializeAttributes(out,options);
out->addBool ("OkayButton", (Flags & EMBF_OK) != 0 );
out->addBool ("CancelButton", (Flags & EMBF_CANCEL) != 0 );
out->addBool ("YesButton", (Flags & EMBF_YES) != 0 );
out->addBool ("NoButton", (Flags & EMBF_NO) != 0 );
out->addTexture ("Texture", IconTexture);
out->addString ("MessageText", MessageText.c_str());
}
//! Reads attributes of the element
void CGUIMessageBox::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0)
{
Flags = 0;
Flags = in->getAttributeAsBool("OkayButton") ? EMBF_OK : 0;
Flags |= in->getAttributeAsBool("CancelButton")? EMBF_CANCEL : 0;
Flags |= in->getAttributeAsBool("YesButton") ? EMBF_YES : 0;
Flags |= in->getAttributeAsBool("NoButton") ? EMBF_NO : 0;
if ( IconTexture )
{
IconTexture->drop();
IconTexture = NULL;
}
IconTexture = in->getAttributeAsTexture("Texture");
if ( IconTexture )
IconTexture->grab();
MessageText = in->getAttributeAsStringW("MessageText").c_str();
CGUIWindow::deserializeAttributes(in,options);
refreshControls();
}
} // end namespace gui
} // end namespace irr
#endif // _IRR_COMPILE_WITH_GUI_
|
paupawsan/Irrlicht
|
056033b719acd310bab22dba1425c4686dc91952
|
Documentation clarification (noticed by a.reichl)
|
diff --git a/include/IrrCompileConfig.h b/include/IrrCompileConfig.h
index fa9d408..ac61788 100644
--- a/include/IrrCompileConfig.h
+++ b/include/IrrCompileConfig.h
@@ -1,505 +1,505 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __IRR_COMPILE_CONFIG_H_INCLUDED__
#define __IRR_COMPILE_CONFIG_H_INCLUDED__
//! Irrlicht SDK Version
#define IRRLICHT_VERSION_MAJOR 1
#define IRRLICHT_VERSION_MINOR 7
#define IRRLICHT_VERSION_REVISION 1
// This flag will be defined only in SVN, the official release code will have
// it undefined
#define IRRLICHT_VERSION_SVN -beta
#define IRRLICHT_SDK_VERSION "1.7.1-beta"
#include <stdio.h> // TODO: Although included elsewhere this is required at least for mingw
//! The defines for different operating system are:
//! _IRR_XBOX_PLATFORM_ for XBox
//! _IRR_WINDOWS_ for all irrlicht supported Windows versions
//! _IRR_WINDOWS_CE_PLATFORM_ for Windows CE
//! _IRR_WINDOWS_API_ for Windows or XBox
//! _IRR_LINUX_PLATFORM_ for Linux (it is defined here if no other os is defined)
//! _IRR_SOLARIS_PLATFORM_ for Solaris
//! _IRR_OSX_PLATFORM_ for Apple systems running OSX
//! _IRR_POSIX_API_ for Posix compatible systems
//! Note: PLATFORM defines the OS specific layer, API can group several platforms
//! DEVICE is the windowing system used, several PLATFORMs support more than one DEVICE
//! Irrlicht can be compiled with more than one device
//! _IRR_COMPILE_WITH_WINDOWS_DEVICE_ for Windows API based device
//! _IRR_COMPILE_WITH_WINDOWS_CE_DEVICE_ for Windows CE API based device
//! _IRR_COMPILE_WITH_OSX_DEVICE_ for Cocoa native windowing on OSX
//! _IRR_COMPILE_WITH_X11_DEVICE_ for Linux X11 based device
//! _IRR_COMPILE_WITH_SDL_DEVICE_ for platform independent SDL framework
//! _IRR_COMPILE_WITH_CONSOLE_DEVICE_ for no windowing system, used as a fallback
//! _IRR_COMPILE_WITH_FB_DEVICE_ for framebuffer systems
//! Uncomment this line to compile with the SDL device
//#define _IRR_COMPILE_WITH_SDL_DEVICE_
//! Comment this line to compile without the fallback console device.
#define _IRR_COMPILE_WITH_CONSOLE_DEVICE_
//! WIN32 for Windows32
//! WIN64 for Windows64
// The windows platform and API support SDL and WINDOW device
#if defined(_WIN32) || defined(_WIN64) || defined(WIN32) || defined(WIN64)
#define _IRR_WINDOWS_
#define _IRR_WINDOWS_API_
#define _IRR_COMPILE_WITH_WINDOWS_DEVICE_
#endif
//! WINCE is a very restricted environment for mobile devices
#if defined(_WIN32_WCE)
#define _IRR_WINDOWS_
#define _IRR_WINDOWS_API_
#define _IRR_WINDOWS_CE_PLATFORM_
#define _IRR_COMPILE_WITH_WINDOWS_CE_DEVICE_
#endif
#if defined(_MSC_VER) && (_MSC_VER < 1300)
# error "Only Microsoft Visual Studio 7.0 and later are supported."
#endif
// XBox only suppots the native Window stuff
#if defined(_XBOX)
#undef _IRR_WINDOWS_
#define _IRR_XBOX_PLATFORM_
#define _IRR_WINDOWS_API_
//#define _IRR_COMPILE_WITH_WINDOWS_DEVICE_
#undef _IRR_COMPILE_WITH_WINDOWS_DEVICE_
//#define _IRR_COMPILE_WITH_SDL_DEVICE_
#include <xtl.h>
#endif
#if defined(__APPLE__) || defined(MACOSX)
#if !defined(MACOSX)
#define MACOSX // legacy support
#endif
#define _IRR_OSX_PLATFORM_
#define _IRR_COMPILE_WITH_OSX_DEVICE_
#endif
#if !defined(_IRR_WINDOWS_API_) && !defined(_IRR_OSX_PLATFORM_)
#ifndef _IRR_SOLARIS_PLATFORM_
#define _IRR_LINUX_PLATFORM_
#endif
#define _IRR_POSIX_API_
#define _IRR_COMPILE_WITH_X11_DEVICE_
#endif
//! Define _IRR_COMPILE_WITH_JOYSTICK_SUPPORT_ if you want joystick events.
#define _IRR_COMPILE_WITH_JOYSTICK_EVENTS_
//! Maximum number of texture an SMaterial can have, up to 8 are supported by Irrlicht.
#define _IRR_MATERIAL_MAX_TEXTURES_ 4
//! Define _IRR_COMPILE_WITH_DIRECT3D_8_ and _IRR_COMPILE_WITH_DIRECT3D_9_ to
//! compile the Irrlicht engine with Direct3D8 and/or DIRECT3D9.
-/** If you only want to use the software device or opengl this can be useful.
+/** If you only want to use the software device or opengl you can disable those defines.
This switch is mostly disabled because people do not get the g++ compiler compile
-directX header files, and directX is only available on windows platforms. If you
+directX header files, and directX is only available on Windows platforms. If you
are using Dev-Cpp, and want to compile this using a DX dev pack, you can define
_IRR_COMPILE_WITH_DX9_DEV_PACK_. So you simply need to add something like this
to the compiler settings: -DIRR_COMPILE_WITH_DX9_DEV_PACK
and this to the linker settings: -ld3dx9 -ld3dx8
Microsoft have chosen to remove D3D8 headers from their recent DXSDKs, and
so D3D8 support is now disabled by default. If you really want to build
with D3D8 support, then you will have to source a DXSDK with the appropriate
headers, e.g. Summer 2004. This is a Microsoft issue, not an Irrlicht one.
*/
#if defined(_IRR_WINDOWS_API_) && (!defined(__GNUC__) || defined(IRR_COMPILE_WITH_DX9_DEV_PACK))
//! Only define _IRR_COMPILE_WITH_DIRECT3D_8_ if you have an appropriate DXSDK, e.g. Summer 2004
//#define _IRR_COMPILE_WITH_DIRECT3D_8_
#define _IRR_COMPILE_WITH_DIRECT3D_9_
#endif
//! Define _IRR_COMPILE_WITH_OPENGL_ to compile the Irrlicht engine with OpenGL.
/** If you do not wish the engine to be compiled with OpenGL, comment this
define out. */
#define _IRR_COMPILE_WITH_OPENGL_
//! Define _IRR_COMPILE_WITH_SOFTWARE_ to compile the Irrlicht engine with software driver
/** If you do not need the software driver, or want to use Burning's Video instead,
comment this define out */
#define _IRR_COMPILE_WITH_SOFTWARE_
//! Define _IRR_COMPILE_WITH_BURNINGSVIDEO_ to compile the Irrlicht engine with Burning's video driver
/** If you do not need this software driver, you can comment this define out. */
#define _IRR_COMPILE_WITH_BURNINGSVIDEO_
//! Define _IRR_COMPILE_WITH_X11_ to compile the Irrlicht engine with X11 support.
/** If you do not wish the engine to be compiled with X11, comment this
define out. */
// Only used in LinuxDevice.
#define _IRR_COMPILE_WITH_X11_
//! Define _IRR_OPENGL_USE_EXTPOINTER_ if the OpenGL renderer should use OpenGL extensions via function pointers.
/** On some systems there is no support for the dynamic extension of OpenGL
via function pointers such that this has to be undef'ed. */
#if !defined(_IRR_OSX_PLATFORM_) && !defined(_IRR_SOLARIS_PLATFORM_)
#define _IRR_OPENGL_USE_EXTPOINTER_
#endif
//! On some Linux systems the XF86 vidmode extension or X11 RandR are missing. Use these flags
//! to remove the dependencies such that Irrlicht will compile on those systems, too.
#if defined(_IRR_LINUX_PLATFORM_) && defined(_IRR_COMPILE_WITH_X11_)
#define _IRR_LINUX_X11_VIDMODE_
//#define _IRR_LINUX_X11_RANDR_
#endif
//! Define _IRR_COMPILE_WITH_GUI_ to compile the engine with the built-in GUI
/** Disable this if you are using an external library to draw the GUI. If you disable this then
you will not be able to use anything provided by the GUI Environment, including loading fonts. */
#define _IRR_COMPILE_WITH_GUI_
//! Define _IRR_WCHAR_FILESYSTEM to enable unicode filesystem support for the engine.
/** This enables the engine to read/write from unicode filesystem. If you
disable this feature, the engine behave as before (ansi). This is currently only supported
for Windows based systems. */
//#define _IRR_WCHAR_FILESYSTEM
//! Define _IRR_COMPILE_WITH_JPEGLIB_ to enable compiling the engine using libjpeg.
/** This enables the engine to read jpeg images. If you comment this out,
the engine will no longer read .jpeg images. */
#define _IRR_COMPILE_WITH_LIBJPEG_
//! Define _IRR_USE_NON_SYSTEM_JPEG_LIB_ to let irrlicht use the jpeglib which comes with irrlicht.
/** If this is commented out, Irrlicht will try to compile using the jpeg lib installed in the system.
This is only used when _IRR_COMPILE_WITH_LIBJPEG_ is defined. */
#define _IRR_USE_NON_SYSTEM_JPEG_LIB_
//! Define _IRR_COMPILE_WITH_LIBPNG_ to enable compiling the engine using libpng.
/** This enables the engine to read png images. If you comment this out,
the engine will no longer read .png images. */
#define _IRR_COMPILE_WITH_LIBPNG_
//! Define _IRR_USE_NON_SYSTEM_LIBPNG_ to let irrlicht use the libpng which comes with irrlicht.
/** If this is commented out, Irrlicht will try to compile using the libpng installed in the system.
This is only used when _IRR_COMPILE_WITH_LIBPNG_ is defined. */
#define _IRR_USE_NON_SYSTEM_LIB_PNG_
//! Define _IRR_D3D_NO_SHADER_DEBUGGING to disable shader debugging in D3D9
/** If _IRR_D3D_NO_SHADER_DEBUGGING is undefined in IrrCompileConfig.h,
it is possible to debug all D3D9 shaders in VisualStudio. All shaders
(which have been generated in memory or read from archives for example) will be emitted
into a temporary file at runtime for this purpose. To debug your shaders, choose
Debug->Direct3D->StartWithDirect3DDebugging in Visual Studio, and for every shader a
file named 'irr_dbg_shader_%%.vsh' or 'irr_dbg_shader_%%.psh' will be created. Drag'n'drop
the file you want to debug into visual studio. That's it. You can now set breakpoints and
watch registers, variables etc. This works with ASM, HLSL, and both with pixel and vertex shaders.
Note that the engine will run in D3D REF for this, which is a lot slower than HAL. */
#define _IRR_D3D_NO_SHADER_DEBUGGING
//! Define _IRR_D3D_USE_LEGACY_HLSL_COMPILER to enable the old HLSL compiler in recent DX SDKs
/** This enables support for ps_1_x shaders for recent DX SDKs. Otherwise, support
for this shader model is not available anymore in SDKs after Oct2006. You need to
distribute the OCT2006_d3dx9_31_x86.cab or OCT2006_d3dx9_31_x64.cab though, in order
to provide the user with the proper DLL. That's why it's disabled by default. */
//#define _IRR_D3D_USE_LEGACY_HLSL_COMPILER
//! Define _IRR_USE_NVIDIA_PERFHUD_ to opt-in to using the nVidia PerHUD tool
/** Enable, by opting-in, to use the nVidia PerfHUD performance analysis driver
tool <http://developer.nvidia.com/object/nvperfhud_home.html>. */
#undef _IRR_USE_NVIDIA_PERFHUD_
//! Define one of the three setting for Burning's Video Software Rasterizer
/** So if we were marketing guys we could say Irrlicht has 4 Software-Rasterizers.
In a Nutshell:
All Burnings Rasterizers use 32 Bit Backbuffer, 32Bit Texture & 32 Bit Z or WBuffer,
16 Bit/32 Bit can be adjusted on a global flag.
BURNINGVIDEO_RENDERER_BEAUTIFUL
32 Bit + Vertexcolor + Lighting + Per Pixel Perspective Correct + SubPixel/SubTexel Correct +
Bilinear Texturefiltering + WBuffer
BURNINGVIDEO_RENDERER_FAST
32 Bit + Per Pixel Perspective Correct + SubPixel/SubTexel Correct + WBuffer +
Bilinear Dithering TextureFiltering + WBuffer
BURNINGVIDEO_RENDERER_ULTRA_FAST
16Bit + SubPixel/SubTexel Correct + ZBuffer
*/
#define BURNINGVIDEO_RENDERER_BEAUTIFUL
//#define BURNINGVIDEO_RENDERER_FAST
//#define BURNINGVIDEO_RENDERER_ULTRA_FAST
//#define BURNINGVIDEO_RENDERER_CE
//! Uncomment the following line if you want to ignore the deprecated warnings
//#define IGNORE_DEPRECATED_WARNING
//! Define _IRR_COMPILE_WITH_SKINNED_MESH_SUPPORT_ if you want to use bone based
/** animated meshes. If you compile without this, you will be unable to load
B3D, MS3D or X meshes */
#define _IRR_COMPILE_WITH_SKINNED_MESH_SUPPORT_
#ifdef _IRR_COMPILE_WITH_SKINNED_MESH_SUPPORT_
//! Define _IRR_COMPILE_WITH_B3D_LOADER_ if you want to use Blitz3D files
#define _IRR_COMPILE_WITH_B3D_LOADER_
//! Define _IRR_COMPILE_WITH_MS3D_LOADER_ if you want to Milkshape files
#define _IRR_COMPILE_WITH_MS3D_LOADER_
//! Define _IRR_COMPILE_WITH_X_LOADER_ if you want to use Microsoft X files
#define _IRR_COMPILE_WITH_X_LOADER_
//! Define _IRR_COMPILE_WITH_OGRE_LOADER_ if you want to load Ogre 3D files
#define _IRR_COMPILE_WITH_OGRE_LOADER_
#endif
//! Define _IRR_COMPILE_WITH_IRR_MESH_LOADER_ if you want to load Irrlicht Engine .irrmesh files
#define _IRR_COMPILE_WITH_IRR_MESH_LOADER_
//! Define _IRR_COMPILE_WITH_MD2_LOADER_ if you want to load Quake 2 animated files
#define _IRR_COMPILE_WITH_MD2_LOADER_
//! Define _IRR_COMPILE_WITH_MD3_LOADER_ if you want to load Quake 3 animated files
#define _IRR_COMPILE_WITH_MD3_LOADER_
//! Define _IRR_COMPILE_WITH_3DS_LOADER_ if you want to load 3D Studio Max files
#define _IRR_COMPILE_WITH_3DS_LOADER_
//! Define _IRR_COMPILE_WITH_COLLADA_LOADER_ if you want to load Collada files
#define _IRR_COMPILE_WITH_COLLADA_LOADER_
//! Define _IRR_COMPILE_WITH_CSM_LOADER_ if you want to load Cartography Shop files
#define _IRR_COMPILE_WITH_CSM_LOADER_
//! Define _IRR_COMPILE_WITH_BSP_LOADER_ if you want to load Quake 3 BSP files
#define _IRR_COMPILE_WITH_BSP_LOADER_
//! Define _IRR_COMPILE_WITH_DMF_LOADER_ if you want to load DeleD files
#define _IRR_COMPILE_WITH_DMF_LOADER_
//! Define _IRR_COMPILE_WITH_LMTS_LOADER_ if you want to load LMTools files
#define _IRR_COMPILE_WITH_LMTS_LOADER_
//! Define _IRR_COMPILE_WITH_MY3D_LOADER_ if you want to load MY3D files
#define _IRR_COMPILE_WITH_MY3D_LOADER_
//! Define _IRR_COMPILE_WITH_OBJ_LOADER_ if you want to load Wavefront OBJ files
#define _IRR_COMPILE_WITH_OBJ_LOADER_
//! Define _IRR_COMPILE_WITH_OCT_LOADER_ if you want to load FSRad OCT files
#define _IRR_COMPILE_WITH_OCT_LOADER_
//! Define _IRR_COMPILE_WITH_LWO_LOADER_ if you want to load Lightwave3D files
#define _IRR_COMPILE_WITH_LWO_LOADER_
//! Define _IRR_COMPILE_WITH_STL_LOADER_ if you want to load stereolithography files
#define _IRR_COMPILE_WITH_STL_LOADER_
//! Define _IRR_COMPILE_WITH_PLY_LOADER_ if you want to load Polygon (Stanford Triangle) files
#define _IRR_COMPILE_WITH_PLY_LOADER_
//! Define _IRR_COMPILE_WITH_IRR_WRITER_ if you want to write static .irrMesh files
#define _IRR_COMPILE_WITH_IRR_WRITER_
//! Define _IRR_COMPILE_WITH_COLLADA_WRITER_ if you want to write Collada files
#define _IRR_COMPILE_WITH_COLLADA_WRITER_
//! Define _IRR_COMPILE_WITH_STL_WRITER_ if you want to write .stl files
#define _IRR_COMPILE_WITH_STL_WRITER_
//! Define _IRR_COMPILE_WITH_OBJ_WRITER_ if you want to write .obj files
#define _IRR_COMPILE_WITH_OBJ_WRITER_
//! Define _IRR_COMPILE_WITH_PLY_WRITER_ if you want to write .ply files
#define _IRR_COMPILE_WITH_PLY_WRITER_
//! Define _IRR_COMPILE_WITH_BMP_LOADER_ if you want to load .bmp files
//! Disabling this loader will also disable the built-in font
#define _IRR_COMPILE_WITH_BMP_LOADER_
//! Define _IRR_COMPILE_WITH_JPG_LOADER_ if you want to load .jpg files
#define _IRR_COMPILE_WITH_JPG_LOADER_
//! Define _IRR_COMPILE_WITH_PCX_LOADER_ if you want to load .pcx files
#define _IRR_COMPILE_WITH_PCX_LOADER_
//! Define _IRR_COMPILE_WITH_PNG_LOADER_ if you want to load .png files
#define _IRR_COMPILE_WITH_PNG_LOADER_
//! Define _IRR_COMPILE_WITH_PPM_LOADER_ if you want to load .ppm/.pgm/.pbm files
#define _IRR_COMPILE_WITH_PPM_LOADER_
//! Define _IRR_COMPILE_WITH_PSD_LOADER_ if you want to load .psd files
#define _IRR_COMPILE_WITH_PSD_LOADER_
//! Define _IRR_COMPILE_WITH_TGA_LOADER_ if you want to load .tga files
#define _IRR_COMPILE_WITH_TGA_LOADER_
//! Define _IRR_COMPILE_WITH_WAL_LOADER_ if you want to load .wal files
#define _IRR_COMPILE_WITH_WAL_LOADER_
//! Define _IRR_COMPILE_WITH_RGB_LOADER_ if you want to load Silicon Graphics .rgb/.rgba/.sgi/.int/.inta/.bw files
#define _IRR_COMPILE_WITH_RGB_LOADER_
//! Define _IRR_COMPILE_WITH_BMP_WRITER_ if you want to write .bmp files
#define _IRR_COMPILE_WITH_BMP_WRITER_
//! Define _IRR_COMPILE_WITH_JPG_WRITER_ if you want to write .jpg files
#define _IRR_COMPILE_WITH_JPG_WRITER_
//! Define _IRR_COMPILE_WITH_PCX_WRITER_ if you want to write .pcx files
#define _IRR_COMPILE_WITH_PCX_WRITER_
//! Define _IRR_COMPILE_WITH_PNG_WRITER_ if you want to write .png files
#define _IRR_COMPILE_WITH_PNG_WRITER_
//! Define _IRR_COMPILE_WITH_PPM_WRITER_ if you want to write .ppm files
#define _IRR_COMPILE_WITH_PPM_WRITER_
//! Define _IRR_COMPILE_WITH_PSD_WRITER_ if you want to write .psd files
#define _IRR_COMPILE_WITH_PSD_WRITER_
//! Define _IRR_COMPILE_WITH_TGA_WRITER_ if you want to write .tga files
#define _IRR_COMPILE_WITH_TGA_WRITER_
//! Define __IRR_COMPILE_WITH_ZIP_ARCHIVE_LOADER_ if you want to open ZIP and GZIP archives
/** ZIP reading has several more options below to configure. */
#define __IRR_COMPILE_WITH_ZIP_ARCHIVE_LOADER_
#ifdef __IRR_COMPILE_WITH_ZIP_ARCHIVE_LOADER_
//! Define _IRR_COMPILE_WITH_ZLIB_ to enable compiling the engine using zlib.
/** This enables the engine to read from compressed .zip archives. If you
disable this feature, the engine can still read archives, but only uncompressed
ones. */
#define _IRR_COMPILE_WITH_ZLIB_
//! Define _IRR_USE_NON_SYSTEM_ZLIB_ to let irrlicht use the zlib which comes with irrlicht.
/** If this is commented out, Irrlicht will try to compile using the zlib
installed on the system. This is only used when _IRR_COMPILE_WITH_ZLIB_ is
defined. */
#define _IRR_USE_NON_SYSTEM_ZLIB_
//! Define _IRR_COMPILE_WITH_ZIP_ENCRYPTION_ if you want to read AES-encrypted ZIP archives
#define _IRR_COMPILE_WITH_ZIP_ENCRYPTION_
//! Define _IRR_COMPILE_WITH_BZIP2_ if you want to support bzip2 compressed zip archives
-/** bzip2 is superior to the original zip file compression modes, but requires
+/** bzip2 is superior to the original zip file compression modes, but requires
a certain amount of memory for decompression and adds several files to the
library. */
#define _IRR_COMPILE_WITH_BZIP2_
//! Define _IRR_USE_NON_SYSTEM_BZLIB_ to let irrlicht use the bzlib which comes with irrlicht.
/** If this is commented out, Irrlicht will try to compile using the bzlib
installed on the system. This is only used when _IRR_COMPILE_WITH_BZLIB_ is
defined. */
#define _IRR_USE_NON_SYSTEM_BZLIB_
//! Define _IRR_COMPILE_WITH_LZMA_ if you want to use LZMA compressed zip files.
/** LZMA is a very efficient compression code, known from 7zip. Irrlicht
currently only supports zip archives, though. */
#define _IRR_COMPILE_WITH_LZMA_
#endif
//! Define __IRR_COMPILE_WITH_MOUNT_ARCHIVE_LOADER_ if you want to mount folders as archives
#define __IRR_COMPILE_WITH_MOUNT_ARCHIVE_LOADER_
//! Define __IRR_COMPILE_WITH_PAK_ARCHIVE_LOADER_ if you want to open ID software PAK archives
#define __IRR_COMPILE_WITH_PAK_ARCHIVE_LOADER_
//! Define __IRR_COMPILE_WITH_NPK_ARCHIVE_LOADER_ if you want to open Nebula Device NPK archives
#define __IRR_COMPILE_WITH_NPK_ARCHIVE_LOADER_
//! Define __IRR_COMPILE_WITH_TAR_ARCHIVE_LOADER_ if you want to open TAR archives
#define __IRR_COMPILE_WITH_TAR_ARCHIVE_LOADER_
//! Set FPU settings
/** Irrlicht should use approximate float and integer fpu techniques
precision will be lower but speed higher. currently X86 only
*/
#if !defined(_IRR_OSX_PLATFORM_) && !defined(_IRR_SOLARIS_PLATFORM_)
//#define IRRLICHT_FAST_MATH
#endif
// Some cleanup and standard stuff
#ifdef _IRR_WINDOWS_API_
// To build Irrlicht as a static library, you must define _IRR_STATIC_LIB_ in both the
// Irrlicht build, *and* in the user application, before #including <irrlicht.h>
#ifndef _IRR_STATIC_LIB_
#ifdef IRRLICHT_EXPORTS
#define IRRLICHT_API __declspec(dllexport)
#else
#define IRRLICHT_API __declspec(dllimport)
#endif // IRRLICHT_EXPORT
#else
#define IRRLICHT_API
#endif // _IRR_STATIC_LIB_
// Declare the calling convention.
#if defined(_STDCALL_SUPPORTED)
#define IRRCALLCONV __stdcall
#else
#define IRRCALLCONV __cdecl
#endif // STDCALL_SUPPORTED
#else // _IRR_WINDOWS_API_
// Force symbol export in shared libraries built with gcc.
#if (__GNUC__ >= 4) && !defined(_IRR_STATIC_LIB_) && defined(IRRLICHT_EXPORTS)
#define IRRLICHT_API __attribute__ ((visibility("default")))
#else
#define IRRLICHT_API
#endif
#define IRRCALLCONV
#endif // _IRR_WINDOWS_API_
// We need to disable DIRECT3D9 support for Visual Studio 6.0 because
// those $%&$!! disabled support for it since Dec. 2004 and users are complaining
// about linker errors. Comment this out only if you are knowing what you are
// doing. (Which means you have an old DX9 SDK and VisualStudio6).
#ifdef _MSC_VER
#if (_MSC_VER < 1300 && !defined(__GNUC__))
#undef _IRR_COMPILE_WITH_DIRECT3D_9_
#pragma message("Compiling Irrlicht with Visual Studio 6.0, support for DX9 is disabled.")
#endif
#endif
// XBox does not have OpenGL or DirectX9
#if defined(_IRR_XBOX_PLATFORM_)
#undef _IRR_COMPILE_WITH_OPENGL_
#undef _IRR_COMPILE_WITH_DIRECT3D_9_
#endif
//! WinCE does not have OpenGL or DirectX9. use minimal loaders
#if defined(_WIN32_WCE)
#undef _IRR_COMPILE_WITH_OPENGL_
#undef _IRR_COMPILE_WITH_DIRECT3D_8_
#undef _IRR_COMPILE_WITH_DIRECT3D_9_
#undef BURNINGVIDEO_RENDERER_BEAUTIFUL
#undef BURNINGVIDEO_RENDERER_FAST
#undef BURNINGVIDEO_RENDERER_ULTRA_FAST
#define BURNINGVIDEO_RENDERER_CE
#undef _IRR_COMPILE_WITH_WINDOWS_DEVICE_
#define _IRR_COMPILE_WITH_WINDOWS_CE_DEVICE_
//#define _IRR_WCHAR_FILESYSTEM
#undef _IRR_COMPILE_WITH_IRR_MESH_LOADER_
//#undef _IRR_COMPILE_WITH_MD2_LOADER_
#undef _IRR_COMPILE_WITH_MD3_LOADER_
#undef _IRR_COMPILE_WITH_3DS_LOADER_
#undef _IRR_COMPILE_WITH_COLLADA_LOADER_
#undef _IRR_COMPILE_WITH_CSM_LOADER_
#undef _IRR_COMPILE_WITH_BSP_LOADER_
#undef _IRR_COMPILE_WITH_DMF_LOADER_
#undef _IRR_COMPILE_WITH_LMTS_LOADER_
#undef _IRR_COMPILE_WITH_MY3D_LOADER_
#undef _IRR_COMPILE_WITH_OBJ_LOADER_
#undef _IRR_COMPILE_WITH_OCT_LOADER_
#undef _IRR_COMPILE_WITH_OGRE_LOADER_
#undef _IRR_COMPILE_WITH_LWO_LOADER_
#undef _IRR_COMPILE_WITH_STL_LOADER_
#undef _IRR_COMPILE_WITH_IRR_WRITER_
#undef _IRR_COMPILE_WITH_COLLADA_WRITER_
#undef _IRR_COMPILE_WITH_STL_WRITER_
#undef _IRR_COMPILE_WITH_OBJ_WRITER_
//#undef _IRR_COMPILE_WITH_BMP_LOADER_
//#undef _IRR_COMPILE_WITH_JPG_LOADER_
#undef _IRR_COMPILE_WITH_PCX_LOADER_
//#undef _IRR_COMPILE_WITH_PNG_LOADER_
#undef _IRR_COMPILE_WITH_PPM_LOADER_
#undef _IRR_COMPILE_WITH_PSD_LOADER_
//#undef _IRR_COMPILE_WITH_TGA_LOADER_
#undef _IRR_COMPILE_WITH_WAL_LOADER_
#undef _IRR_COMPILE_WITH_BMP_WRITER_
#undef _IRR_COMPILE_WITH_JPG_WRITER_
#undef _IRR_COMPILE_WITH_PCX_WRITER_
#undef _IRR_COMPILE_WITH_PNG_WRITER_
#undef _IRR_COMPILE_WITH_PPM_WRITER_
#undef _IRR_COMPILE_WITH_PSD_WRITER_
#undef _IRR_COMPILE_WITH_TGA_WRITER_
#endif
#ifndef _IRR_WINDOWS_API_
#undef _IRR_WCHAR_FILESYSTEM
#endif
#if defined(__sparc__) || defined(__sun__)
#define __BIG_ENDIAN__
#endif
#if defined(_IRR_SOLARIS_PLATFORM_)
#undef _IRR_COMPILE_WITH_JOYSTICK_EVENTS_
#endif
#endif // __IRR_COMPILE_CONFIG_H_INCLUDED__
|
paupawsan/Irrlicht
|
8bb280f5e24b8e83ac641a360fe054dd7611c138
|
Fix typo in docs
|
diff --git a/include/ITexture.h b/include/ITexture.h
index 6366400..1b8d2f7 100644
--- a/include/ITexture.h
+++ b/include/ITexture.h
@@ -1,188 +1,188 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __I_TEXTURE_H_INCLUDED__
#define __I_TEXTURE_H_INCLUDED__
#include "IReferenceCounted.h"
#include "IImage.h"
#include "dimension2d.h"
#include "EDriverTypes.h"
#include "path.h"
#include "matrix4.h"
namespace irr
{
namespace video
{
//! Enumeration flags telling the video driver in which format textures should be created.
enum E_TEXTURE_CREATION_FLAG
{
/** Forces the driver to create 16 bit textures always, independent of
- which format the file on disk has. When choosing this you may loose
+ which format the file on disk has. When choosing this you may lose
some color detail, but gain much speed and memory. 16 bit textures can
be transferred twice as fast as 32 bit textures and only use half of
the space in memory.
When using this flag, it does not make sense to use the flags
ETCF_ALWAYS_32_BIT, ETCF_OPTIMIZED_FOR_QUALITY, or
ETCF_OPTIMIZED_FOR_SPEED at the same time. */
ETCF_ALWAYS_16_BIT = 0x00000001,
/** Forces the driver to create 32 bit textures always, independent of
which format the file on disk has. Please note that some drivers (like
the software device) will ignore this, because they are only able to
create and use 16 bit textures.
When using this flag, it does not make sense to use the flags
ETCF_ALWAYS_16_BIT, ETCF_OPTIMIZED_FOR_QUALITY, or
ETCF_OPTIMIZED_FOR_SPEED at the same time. */
ETCF_ALWAYS_32_BIT = 0x00000002,
/** Lets the driver decide in which format the textures are created and
tries to make the textures look as good as possible. Usually it simply
chooses the format in which the texture was stored on disk.
When using this flag, it does not make sense to use the flags
ETCF_ALWAYS_16_BIT, ETCF_ALWAYS_32_BIT, or ETCF_OPTIMIZED_FOR_SPEED at
the same time. */
ETCF_OPTIMIZED_FOR_QUALITY = 0x00000004,
/** Lets the driver decide in which format the textures are created and
tries to create them maximizing render speed.
When using this flag, it does not make sense to use the flags
ETCF_ALWAYS_16_BIT, ETCF_ALWAYS_32_BIT, or ETCF_OPTIMIZED_FOR_QUALITY,
at the same time. */
ETCF_OPTIMIZED_FOR_SPEED = 0x00000008,
/** Automatically creates mip map levels for the textures. */
ETCF_CREATE_MIP_MAPS = 0x00000010,
/** Discard any alpha layer and use non-alpha color format. */
ETCF_NO_ALPHA_CHANNEL = 0x00000020,
//! Allow the Driver to use Non-Power-2-Textures
/** BurningVideo can handle Non-Power-2 Textures in 2D (GUI), but not in 3D. */
ETCF_ALLOW_NON_POWER_2 = 0x00000040,
/** This flag is never used, it only forces the compiler to compile
these enumeration values to 32 bit. */
ETCF_FORCE_32_BIT_DO_NOT_USE = 0x7fffffff
};
//! Interface of a Video Driver dependent Texture.
/** An ITexture is created by an IVideoDriver by using IVideoDriver::addTexture
or IVideoDriver::getTexture. After that, the texture may only be used by this
VideoDriver. As you can imagine, textures of the DirectX and the OpenGL device
will, e.g., not be compatible. An exception is the Software device and the
NULL device, their textures are compatible. If you try to use a texture
created by one device with an other device, the device will refuse to do that
and write a warning or an error message to the output buffer.
*/
class ITexture : public virtual IReferenceCounted
{
public:
//! constructor
ITexture(const io::path& name) : NamedPath(name)
{
}
//! Lock function.
/** Locks the Texture and returns a pointer to access the
pixels. After lock() has been called and all operations on the pixels
are done, you must call unlock().
Locks are not accumulating, hence one unlock will do for an arbitrary
number of previous locks.
\param readOnly Specifies that no changes to the locked texture are
made. Unspecified behavior will arise if still write access happens.
\param mipmapLevel Number of the mipmapLevel to lock. 0 is main texture.
Non-existing levels will silently fail and return 0.
\return Returns a pointer to the pixel data. The format of the pixel can
be determined by using getColorFormat(). 0 is returned, if
the texture cannot be locked. */
virtual void* lock(bool readOnly = false, u32 mipmapLevel=0) = 0;
//! Unlock function. Must be called after a lock() to the texture.
/** One should avoid to call unlock more than once before another lock. */
virtual void unlock() = 0;
//! Get original size of the texture.
/** The texture is usually scaled, if it was created with an unoptimal
size. For example if the size was not a power of two. This method
returns the size of the texture it had before it was scaled. Can be
useful when drawing 2d images on the screen, which should have the
exact size of the original texture. Use ITexture::getSize() if you want
to know the real size it has now stored in the system.
\return The original size of the texture. */
virtual const core::dimension2d<u32>& getOriginalSize() const = 0;
//! Get dimension (=size) of the texture.
/** \return The size of the texture. */
virtual const core::dimension2d<u32>& getSize() const = 0;
//! Get driver type of texture.
/** This is the driver, which created the texture. This method is used
internally by the video devices, to check, if they may use a texture
because textures may be incompatible between different devices.
\return Driver type of texture. */
virtual E_DRIVER_TYPE getDriverType() const = 0;
//! Get the color format of texture.
/** \return The color format of texture. */
virtual ECOLOR_FORMAT getColorFormat() const = 0;
//! Get pitch of texture (in bytes).
/** The pitch is the amount of bytes used for a row of pixels in a
texture.
\return Pitch of texture in bytes. */
virtual u32 getPitch() const = 0;
//! Check whether the texture has MipMaps
/** \return True if texture has MipMaps, else false. */
virtual bool hasMipMaps() const { return false; }
//! Returns if the texture has an alpha channel
virtual bool hasAlpha() const {
return getColorFormat () == video::ECF_A8R8G8B8 || getColorFormat () == video::ECF_A1R5G5B5;
}
//! Regenerates the mip map levels of the texture.
/** Required after modifying the texture, usually after calling unlock(). */
virtual void regenerateMipMapLevels(void* mipmapData=0) = 0;
//! Check whether the texture is a render target
/** \return True if this is a render target, otherwise false. */
virtual bool isRenderTarget() const { return false; }
//! Get name of texture (in most cases this is the filename)
const io::SNamedPath& getName() const { return NamedPath; }
protected:
//! Helper function, helps to get the desired texture creation format from the flags.
/** \return Either ETCF_ALWAYS_32_BIT, ETCF_ALWAYS_16_BIT,
ETCF_OPTIMIZED_FOR_QUALITY, or ETCF_OPTIMIZED_FOR_SPEED. */
inline E_TEXTURE_CREATION_FLAG getTextureFormatFromFlags(u32 flags)
{
if (flags & ETCF_OPTIMIZED_FOR_SPEED)
return ETCF_OPTIMIZED_FOR_SPEED;
if (flags & ETCF_ALWAYS_16_BIT)
return ETCF_ALWAYS_16_BIT;
if (flags & ETCF_ALWAYS_32_BIT)
return ETCF_ALWAYS_32_BIT;
if (flags & ETCF_OPTIMIZED_FOR_QUALITY)
return ETCF_OPTIMIZED_FOR_QUALITY;
return ETCF_OPTIMIZED_FOR_SPEED;
}
io::SNamedPath NamedPath;
};
} // end namespace video
} // end namespace irr
#endif
|
paupawsan/Irrlicht
|
201f876df0be2a368972e217b947c3cb7f85aae5
|
Fix octree naming
|
diff --git a/source/Irrlicht/SConstruct b/source/Irrlicht/SConstruct
index 4ed3277..1117fef 100644
--- a/source/Irrlicht/SConstruct
+++ b/source/Irrlicht/SConstruct
@@ -1,102 +1,102 @@
import os
import sys
USE_GCC = 1;
NDEBUG = 1;
PROFILE = 0;
APPLICATION_NAME = 'Irrlicht';
LIBRARIES = ['gdi32', 'opengl32', 'd3dx9d', 'winmm'];
if USE_GCC==1 and PROFILE==1:
LIBRARIES += ['gmon'];
CXXINCS = ['../../include/', 'zlib/', 'jpeglib/', 'libpng/'];
if USE_GCC==0:
env = Environment(ENV = {
'PATH': os.environ['PATH']
}, CPPPATH=CXXINCS);
else:
env = Environment(ENV = {
'PATH': os.environ['PATH']
}, tools = ['mingw'], CPPPATH=CXXINCS);
IRRMESHLOADER = ['CBSPMeshFileLoader.cpp', 'CMD2MeshFileLoader.cpp', 'CMD3MeshFileLoader.cpp', 'CMS3DMeshFileLoader.cpp', 'CB3DMeshFileLoader.cpp', 'C3DSMeshFileLoader.cpp', 'COgreMeshFileLoader.cpp', 'COBJMeshFileLoader.cpp', 'CColladaFileLoader.cpp', 'CCSMLoader.cpp', 'CDMFLoader.cpp', 'CLMTSMeshFileLoader.cpp', 'CMY3DMeshFileLoader.cpp', 'COCTLoader.cpp', 'CXMeshFileLoader.cpp', 'CIrrMeshFileLoader.cpp', 'CSTLMeshFileLoader.cpp', 'CLWOMeshFileLoader.cpp'];
IRRMESHWRITER = ['CColladaMeshWriter.cpp', 'CIrrMeshWriter.cpp', 'COBJMeshWriter.cpp', 'CSTLMeshWriter.cpp'];
IRRMESHOBJ = IRRMESHLOADER + IRRMESHWRITER + ['CSkinnedMesh.cpp', 'CBoneSceneNode.cpp', 'CMeshSceneNode.cpp', 'CAnimatedMeshSceneNode.cpp', 'CAnimatedMeshMD2.cpp', 'CAnimatedMeshMD3.cpp', 'CQ3LevelMesh.cpp', 'CQuake3ShaderSceneNode.cpp'];
-IRROBJ = ['CBillboardSceneNode.cpp', 'CCameraSceneNode.cpp', 'CDummyTransformationSceneNode.cpp', 'CEmptySceneNode.cpp', 'CGeometryCreator.cpp', 'CLightSceneNode.cpp', 'CMeshManipulator.cpp', 'CMetaTriangleSelector.cpp', 'COctTreeSceneNode.cpp', 'COctTreeTriangleSelector.cpp', 'CSceneCollisionManager.cpp', 'CSceneManager.cpp', 'CShadowVolumeSceneNode.cpp', 'CSkyBoxSceneNode.cpp', 'CSkyDomeSceneNode.cpp', 'CTerrainSceneNode.cpp', 'CTerrainTriangleSelector.cpp', 'CVolumeLightSceneNode.cpp', 'CCubeSceneNode.cpp', 'CSphereSceneNode.cpp', 'CTextSceneNode.cpp', 'CTriangleBBSelector.cpp', 'CTriangleSelector.cpp', 'CWaterSurfaceSceneNode.cpp', 'CMeshCache.cpp', 'CDefaultSceneNodeAnimatorFactory.cpp', 'CDefaultSceneNodeFactory.cpp'];
+IRROBJ = ['CBillboardSceneNode.cpp', 'CCameraSceneNode.cpp', 'CDummyTransformationSceneNode.cpp', 'CEmptySceneNode.cpp', 'CGeometryCreator.cpp', 'CLightSceneNode.cpp', 'CMeshManipulator.cpp', 'CMetaTriangleSelector.cpp', 'COctreeSceneNode.cpp', 'COctreeTriangleSelector.cpp', 'CSceneCollisionManager.cpp', 'CSceneManager.cpp', 'CShadowVolumeSceneNode.cpp', 'CSkyBoxSceneNode.cpp', 'CSkyDomeSceneNode.cpp', 'CTerrainSceneNode.cpp', 'CTerrainTriangleSelector.cpp', 'CVolumeLightSceneNode.cpp', 'CCubeSceneNode.cpp', 'CSphereSceneNode.cpp', 'CTextSceneNode.cpp', 'CTriangleBBSelector.cpp', 'CTriangleSelector.cpp', 'CWaterSurfaceSceneNode.cpp', 'CMeshCache.cpp', 'CDefaultSceneNodeAnimatorFactory.cpp', 'CDefaultSceneNodeFactory.cpp'];
IRRPARTICLEOBJ = ['CParticleAnimatedMeshSceneNodeEmitter.cpp', 'CParticleBoxEmitter.cpp', 'CParticleCylinderEmitter.cpp', 'CParticleMeshEmitter.cpp', 'CParticlePointEmitter.cpp', 'CParticleRingEmitter.cpp', 'CParticleSphereEmitter.cpp', 'CParticleAttractionAffector.cpp', 'CParticleFadeOutAffector.cpp', 'CParticleGravityAffector.cpp', 'CParticleRotationAffector.cpp', 'CParticleSystemSceneNode.cpp', 'CParticleScaleAffector.cpp'];
IRRANIMOBJ = ['CSceneNodeAnimatorCameraFPS.cpp', 'CSceneNodeAnimatorCameraMaya.cpp', 'CSceneNodeAnimatorCollisionResponse.cpp', 'CSceneNodeAnimatorDelete.cpp', 'CSceneNodeAnimatorFlyCircle.cpp', 'CSceneNodeAnimatorFlyStraight.cpp', 'CSceneNodeAnimatorFollowSpline.cpp', 'CSceneNodeAnimatorRotation.cpp', 'CSceneNodeAnimatorTexture.cpp'];
IRRDRVROBJ = ['CNullDriver.cpp', 'COpenGLDriver.cpp', 'COpenGLNormalMapRenderer.cpp', 'COpenGLParallaxMapRenderer.cpp', 'COpenGLShaderMaterialRenderer.cpp', 'COpenGLTexture.cpp', 'COpenGLSLMaterialRenderer.cpp', 'COpenGLExtensionHandler.cpp', 'CD3D8Driver.cpp', 'CD3D8NormalMapRenderer.cpp', 'CD3D8ParallaxMapRenderer.cpp', 'CD3D8ShaderMaterialRenderer.cpp', 'CD3D8Texture.cpp', 'CD3D9Driver.cpp', 'CD3D9HLSLMaterialRenderer.cpp', 'CD3D9NormalMapRenderer.cpp', 'CD3D9ParallaxMapRenderer.cpp', 'CD3D9ShaderMaterialRenderer.cpp', 'CD3D9Texture.cpp'];
IRRIMAGEOBJ = ['CColorConverter.cpp', 'CImage.cpp', 'CImageLoaderBMP.cpp', 'CImageLoaderJPG.cpp', 'CImageLoaderPCX.cpp', 'CImageLoaderPNG.cpp', 'CImageLoaderPSD.cpp', 'CImageLoaderTGA.cpp', 'CImageLoaderPPM.cpp', 'CImageLoaderWAL.cpp', 'CImageWriterBMP.cpp', 'CImageWriterJPG.cpp', 'CImageWriterPCX.cpp', 'CImageWriterPNG.cpp', 'CImageWriterPPM.cpp', 'CImageWriterPSD.cpp', 'CImageWriterTGA.cpp'];
IRRVIDEOOBJ = ['CVideoModeList.cpp', 'CFPSCounter.cpp'] + IRRDRVROBJ + IRRIMAGEOBJ;
IRRSWRENDEROBJ = ['CSoftwareDriver.cpp', 'CSoftwareTexture.cpp', 'CTRFlat.cpp', 'CTRFlatWire.cpp', 'CTRGouraud.cpp', 'CTRGouraudWire.cpp', 'CTRTextureFlat.cpp', 'CTRTextureFlatWire.cpp', 'CTRTextureGouraud.cpp', 'CTRTextureGouraudAdd.cpp', 'CTRTextureGouraudNoZ.cpp', 'CTRTextureGouraudWire.cpp', 'CZBuffer.cpp', 'CTRTextureGouraudVertexAlpha2.cpp', 'CTRTextureGouraudNoZ2.cpp', 'CTRTextureLightMap2_M2.cpp', 'CTRTextureLightMap2_M4.cpp', 'CTRTextureLightMap2_M1.cpp', 'CSoftwareDriver2.cpp', 'CSoftwareTexture2.cpp', 'CTRTextureGouraud2.cpp', 'CTRGouraud2.cpp', 'CTRGouraudAlpha2.cpp', 'CTRGouraudAlphaNoZ2.cpp', 'CTRTextureDetailMap2.cpp', 'CTRTextureGouraudAdd2.cpp', 'CTRTextureGouraudAddNoZ2.cpp', 'CTRTextureWire2.cpp', 'CTRTextureLightMap2_Add.cpp', 'CTRTextureLightMapGouraud2_M4.cpp', 'IBurningShader.cpp', 'CTRTextureBlend.cpp', 'CTRTextureGouraudAlpha.cpp', 'CTRTextureGouraudAlphaNoZ.cpp', 'CDepthBuffer.cpp', 'CBurningShader_Raster_Reference.cpp'];
IRRIOOBJ = ['CFileList.cpp', 'CFileSystem.cpp', 'CLimitReadFile.cpp', 'CMemoryReadFile.cpp', 'CReadFile.cpp', 'CWriteFile.cpp', 'CXMLReader.cpp', 'CXMLWriter.cpp', 'CZipReader.cpp', 'CPakReader.cpp', 'CNPKReader.cpp', 'irrXML.cpp', 'CAttributes.cpp', 'lzma/LzmaDec.c'];
IRROTHEROBJ = ['CIrrDeviceSDL.cpp', 'CIrrDeviceLinux.cpp', 'CIrrDeviceStub.cpp', 'CIrrDeviceWin32.cpp', 'CLogger.cpp', 'COSOperator.cpp', 'Irrlicht.cpp', 'os.cpp'];
IRRGUIOBJ = ['CGUIButton.cpp', 'CGUICheckBox.cpp', 'CGUIComboBox.cpp', 'CGUIContextMenu.cpp', 'CGUIEditBox.cpp', 'CGUIEnvironment.cpp', 'CGUIFileOpenDialog.cpp', 'CGUIFont.cpp', 'CGUIImage.cpp', 'CGUIInOutFader.cpp', 'CGUIListBox.cpp', 'CGUIMenu.cpp', 'CGUIMeshViewer.cpp', 'CGUIMessageBox.cpp', 'CGUIModalScreen.cpp', 'CGUIScrollBar.cpp', 'CGUISpinBox.cpp', 'CGUISkin.cpp', 'CGUIStaticText.cpp', 'CGUITabControl.cpp', 'CGUITable.cpp', 'CGUIToolBar.cpp', 'CGUIWindow.cpp', 'CGUIColorSelectDialog.cpp', 'CDefaultGUIElementFactory.cpp', 'CGUISpriteBank.cpp'];
ZLIB_PREFIX = 'zlib/';
ZLIBNAMES = ['adler32.c', 'compress.c', 'crc32.c', 'deflate.c', 'inffast.c', 'inflate.c', 'inftrees.c', 'trees.c', 'uncompr.c', 'zutil.c'];
ZLIBOBJ = [];
for fileName in ZLIBNAMES:
ZLIBOBJ += [ZLIB_PREFIX + fileName];
JPEGLIB_PREFIX = 'jpeglib/';
JPEGLIBNAMES = ['jaricom.c', 'jcapimin.c', 'jcapistd.c', 'jcarith.c', 'jccoefct.c', 'jccolor.c', 'jcdctmgr.c', 'jchuff.c', 'jcinit.c', 'jcmainct.c', 'jcmarker.c', 'jcmaster.c', 'jcomapi.c', 'jcparam.c', 'jcprepct.c', 'jcsample.c', 'jctrans.c', 'jdapimin.c', 'jdapistd.c', 'jdarith.c', 'jdatadst.c', 'jdatasrc.c', 'jdcoefct.c', 'jdcolor.c', 'jddctmgr.c', 'jdhuff.c', 'jdinput.c', 'jdmainct.c', 'jdmarker.c', 'jdmaster.c', 'jdmerge.c', 'jdpostct.c', 'jdsample.c', 'jdtrans.c', 'jerror.c', 'jfdctflt.c', 'jfdctfst.c', 'jfdctint.c', 'jidctflt.c', 'jidctfst.c', 'jidctint.c', 'jmemmgr.c', 'jmemnobs.c', 'jquant1.c', 'jquant2.c', 'jutils.c'];
JPEGLIBOBJ = [];
for fileName in JPEGLIBNAMES:
JPEGLIBOBJ += [JPEGLIB_PREFIX + fileName];
LIBPNG_PREFIX = 'libpng/';
LIBPNGNAMES = ['png.c', 'pngerror.c', 'pngget.c', 'pngmem.c', 'pngpread.c', 'pngread.c', 'pngrio.c', 'pngrtran.c', 'pngrutil.c', 'pngset.c', 'pngtrans.c', 'pngwio.c', 'pngwrite.c', 'pngwtran.c', 'pngwutil.c'];
LIBPNGOBJ = [];
for fileName in LIBPNGNAMES:
LIBPNGOBJ += [LIBPNG_PREFIX + fileName];
AESGLADMAN_PREFIX = 'aesGladman/';
AESGLADMANNAMES = ['aescrypt.cpp', 'aeskey.cpp', 'aestab.cpp', 'fileenc.cpp', 'hmac.cpp', 'prng.cpp', 'pwd2key.cpp', 'sha1.cpp', 'sha2.cpp'];
AESGLADMANOBJ = [];
for fileName in AESGLADMANNAMES:
AESGLADMANOBJ += [AESGLADMAN_PREFIX + fileName];
BZIP2_PREFIX = 'bzip2/';
BZIP2NAMES = ['blocksort.c', 'bzcompress.c', 'bzlib.c', 'crctable.c', 'decompress.c', 'huffman.c', 'randtable.c'];
BZIP2OBJ = [];
for fileName in BZIP2NAMES:
BZIP2OBJ += [BZIP2_PREFIX + fileName];
# Next variable is for additional scene nodes etc. of customized Irrlicht versions
EXTRAOBJ = [];
LINKOBJ = IRRMESHOBJ + IRROBJ + IRRPARTICLEOBJ + IRRANIMOBJ + IRRVIDEOOBJ + IRRSWRENDEROBJ + IRRIOOBJ + IRROTHEROBJ + IRRGUIOBJ + ZLIBOBJ + JPEGLIBOBJ + LIBPNGOBJ + AESGLADMANOBJ + EXTRAOBJ;
env.Append(LIBS = LIBRARIES, LIBPATH = CXXINCS);
CXXFLAGS = ['-Wall'];
if NDEBUG:
CXXFLAGS += ['-fexpensive-optimizations', '-O3'];
else:
CXXFLAGS += ['-g', '-D_DEBUG'];
if PROFILE:
CXXFLAGS += ['-pg'];
CXXFLAGS += ['-DPNG_NO_MMX_CODE', '-DPNG_NO_MNG_FEATURES', '-DIRRLICHT_EXPORTS=1', '-D_IRR_STATIC_LIB_'];
if USE_GCC:
CXXFLAGS += ['-D__GNUWIN32__=1'];
env.Append(CCFLAGS = CXXFLAGS);
IrrlichtLibrary = env.SharedLibrary("Irrlicht.dll", LINKOBJ);
|
paupawsan/Irrlicht
|
9d0f1167c296905042fed7ba697aac5502212e10
|
Fix octree naming
|
diff --git a/source/Irrlicht/Irrlicht.dev b/source/Irrlicht/Irrlicht.dev
index a705c40..704da54 100644
--- a/source/Irrlicht/Irrlicht.dev
+++ b/source/Irrlicht/Irrlicht.dev
@@ -1681,1605 +1681,1605 @@ BuildCmd=
[Unit166]
FileName=CD3D9HLSLMaterialRenderer.cpp
Folder=Irrlicht/video/DirectX9
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit167]
FileName=CD3D9HLSLMaterialRenderer.h
Folder=Irrlicht/video/DirectX9
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit168]
FileName=CD3D9MaterialRenderer.h
Folder=Irrlicht/video/DirectX9
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit169]
FileName=CD3D9NormalMapRenderer.cpp
Folder=Irrlicht/video/DirectX9
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit170]
FileName=CD3D9NormalMapRenderer.h
Folder=Irrlicht/video/DirectX9
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit171]
FileName=CD3D9ParallaxMapRenderer.cpp
Folder=Irrlicht/video/DirectX9
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit172]
FileName=CD3D9ParallaxMapRenderer.h
Folder=Irrlicht/video/DirectX9
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit173]
FileName=CD3D9ShaderMaterialRenderer.cpp
Folder=Irrlicht/video/DirectX9
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit174]
FileName=CD3D9ShaderMaterialRenderer.h
Folder=Irrlicht/video/DirectX9
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit175]
FileName=CD3D9Texture.cpp
Folder=Irrlicht/video/DirectX9
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit176]
FileName=CD3D9Texture.h
Folder=Irrlicht/video/DirectX9
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit177]
FileName=CVideoModeList.cpp
Folder=Irrlicht/video
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit178]
FileName=CVideoModeList.h
Folder=Irrlicht/video
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit179]
FileName=C3DSMeshFileLoader.cpp
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit180]
FileName=C3DSMeshFileLoader.h
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit181]
FileName=CAnimatedMeshMD2.cpp
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit182]
FileName=CAnimatedMeshMD2.h
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit183]
FileName=CAnimatedMeshSceneNode.cpp
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit184]
FileName=CAnimatedMeshSceneNode.h
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit185]
FileName=CBillboardSceneNode.cpp
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit186]
FileName=CBillboardSceneNode.h
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit187]
FileName=CCameraSceneNode.cpp
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit188]
FileName=CCameraSceneNode.h
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit189]
FileName=CColladaFileLoader.cpp
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit190]
FileName=CColladaFileLoader.h
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit191]
FileName=CCSMLoader.cpp
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit192]
FileName=CCSMLoader.h
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit193]
FileName=CDMFLoader.cpp
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit194]
FileName=CDMFLoader.h
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit195]
FileName=CDummyTransformationSceneNode.cpp
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit196]
FileName=CDummyTransformationSceneNode.h
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit197]
FileName=CEmptySceneNode.cpp
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit198]
FileName=CEmptySceneNode.h
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit199]
FileName=CGeometryCreator.cpp
Folder=Irrlicht/scene/mesh
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit200]
FileName=CGeometryCreator.h
Folder=Irrlicht/scene/mesh
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit201]
FileName=CLightSceneNode.cpp
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit202]
FileName=CLightSceneNode.h
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit203]
FileName=CLMTSMeshFileLoader.cpp
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit204]
FileName=CLMTSMeshFileLoader.h
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit205]
FileName=CMeshManipulator.cpp
Folder=Irrlicht/scene/mesh
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit206]
FileName=CMeshManipulator.h
Folder=Irrlicht/scene/mesh
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit207]
FileName=CMeshSceneNode.cpp
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit208]
FileName=CMeshSceneNode.h
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit209]
FileName=CMetaTriangleSelector.cpp
Folder=Irrlicht/scene/collision
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit210]
FileName=CMetaTriangleSelector.h
Folder=Irrlicht/scene/collision
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit211]
FileName=CMY3DHelper.h
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit212]
FileName=CMY3DMeshFileLoader.cpp
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit213]
FileName=CMY3DMeshFileLoader.h
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit214]
FileName=..\..\include\EGUIAlignment.h
Folder=include/gui
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit215]
FileName=COCTLoader.cpp
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit216]
FileName=COCTLoader.h
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit217]
-FileName=COctTreeSceneNode.cpp
+FileName=COctreeSceneNode.cpp
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit218]
-FileName=COctTreeSceneNode.h
+FileName=COctreeSceneNode.h
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit219]
-FileName=COctTreeTriangleSelector.cpp
+FileName=COctreeTriangleSelector.cpp
Folder=Irrlicht/scene/collision
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit220]
-FileName=COctTreeTriangleSelector.h
+FileName=COctreeTriangleSelector.h
Folder=Irrlicht/scene/collision
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit221]
FileName=CParticleBoxEmitter.cpp
Folder=Irrlicht/scene/nodes/particles
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit222]
FileName=CParticleBoxEmitter.h
Folder=Irrlicht/scene/nodes/particles
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit223]
FileName=CParticleFadeOutAffector.cpp
Folder=Irrlicht/scene/nodes/particles
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit224]
FileName=CParticleFadeOutAffector.h
Folder=Irrlicht/scene/nodes/particles
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit225]
FileName=CParticleGravityAffector.cpp
Folder=Irrlicht/scene/nodes/particles
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit226]
FileName=CParticleGravityAffector.h
Folder=Irrlicht/scene/nodes/particles
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit227]
FileName=CParticlePointEmitter.cpp
Folder=Irrlicht/scene/nodes/particles
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit228]
FileName=CParticlePointEmitter.h
Folder=Irrlicht/scene/nodes/particles
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit229]
FileName=CParticleSystemSceneNode.cpp
Folder=Irrlicht/scene/nodes/particles
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit230]
FileName=CParticleSystemSceneNode.h
Folder=Irrlicht/scene/nodes/particles
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit231]
FileName=CQ3LevelMesh.cpp
Folder=Irrlicht/scene/mesh
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit232]
FileName=CQ3LevelMesh.h
Folder=Irrlicht/scene/mesh
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit233]
FileName=CSceneCollisionManager.cpp
Folder=Irrlicht/scene/collision
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit234]
FileName=CSceneCollisionManager.h
Folder=Irrlicht/scene/collision
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit235]
FileName=CSceneManager.cpp
Folder=Irrlicht/scene
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit236]
FileName=CSceneManager.h
Folder=Irrlicht/scene
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit237]
FileName=CSceneNodeAnimatorCollisionResponse.cpp
Folder=Irrlicht/scene/animators
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit238]
FileName=CSceneNodeAnimatorCollisionResponse.h
Folder=Irrlicht/scene/animators
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit239]
FileName=CSceneNodeAnimatorDelete.cpp
Folder=Irrlicht/scene/animators
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit240]
FileName=CSceneNodeAnimatorDelete.h
Folder=Irrlicht/scene/animators
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit241]
FileName=CSceneNodeAnimatorFlyCircle.cpp
Folder=Irrlicht/scene/animators
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit242]
FileName=CSceneNodeAnimatorFlyCircle.h
Folder=Irrlicht/scene/animators
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit243]
FileName=CSceneNodeAnimatorFlyStraight.cpp
Folder=Irrlicht/scene/animators
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit244]
FileName=CSceneNodeAnimatorFlyStraight.h
Folder=Irrlicht/scene/animators
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit245]
FileName=CSceneNodeAnimatorFollowSpline.cpp
Folder=Irrlicht/scene/animators
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit246]
FileName=CSceneNodeAnimatorFollowSpline.h
Folder=Irrlicht/scene/animators
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit247]
FileName=CSceneNodeAnimatorRotation.cpp
Folder=Irrlicht/scene/animators
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit248]
FileName=CSceneNodeAnimatorRotation.h
Folder=Irrlicht/scene/animators
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit249]
FileName=CSceneNodeAnimatorTexture.cpp
Folder=Irrlicht/scene/animators
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit250]
FileName=CSceneNodeAnimatorTexture.h
Folder=Irrlicht/scene/animators
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit251]
FileName=CShadowVolumeSceneNode.cpp
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit252]
FileName=CShadowVolumeSceneNode.h
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit253]
FileName=CSkyBoxSceneNode.cpp
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit254]
FileName=CSkyBoxSceneNode.h
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit255]
FileName=COBJMeshFileLoader.cpp
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit256]
FileName=COBJMeshFileLoader.h
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit257]
FileName=CTerrainSceneNode.cpp
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit258]
FileName=CTerrainSceneNode.h
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit259]
FileName=CTerrainTriangleSelector.cpp
Folder=Irrlicht/scene/collision
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit260]
FileName=CTerrainTriangleSelector.h
Folder=Irrlicht/scene/collision
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit261]
FileName=CTextSceneNode.cpp
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit262]
FileName=CTextSceneNode.h
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit263]
FileName=CTriangleBBSelector.cpp
Folder=Irrlicht/scene/collision
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit264]
FileName=CTriangleBBSelector.h
Folder=Irrlicht/scene/collision
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit265]
FileName=CTriangleSelector.cpp
Folder=Irrlicht/scene/collision
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit266]
FileName=CTriangleSelector.h
Folder=Irrlicht/scene/collision
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit267]
FileName=CWaterSurfaceSceneNode.cpp
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit268]
FileName=CWaterSurfaceSceneNode.h
Folder=Irrlicht/scene/nodes
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit269]
FileName=..\..\include\SExposedVideoData.h
Folder=include/video
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit270]
FileName=..\..\include\SKeyMap.h
Folder=include
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit271]
FileName=..\..\include\SMeshBufferTangents.h
Folder=include/video
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit272]
FileName=..\..\include\SParticle.h
Folder=include/scene
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit273]
FileName=CXMeshFileLoader.cpp
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit274]
FileName=CXMeshFileLoader.h
Folder=Irrlicht/scene/mesh/loaders
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit275]
-FileName=OctTree.h
+FileName=Octree.h
Folder=Irrlicht/scene/mesh
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit276]
FileName=CFileList.cpp
Folder=Irrlicht/io
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit277]
FileName=CFileList.h
Folder=Irrlicht/io
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit278]
FileName=CFileSystem.cpp
CompileCpp=1
Folder=Irrlicht/io
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit279]
FileName=CFileSystem.h
CompileCpp=1
Folder=Irrlicht/io
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit280]
FileName=CLimitReadFile.cpp
CompileCpp=1
Folder=Irrlicht/io/file
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit281]
FileName=CLimitReadFile.h
CompileCpp=1
Folder=Irrlicht/io/file
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit282]
FileName=CMemoryFile.cpp
Folder=Irrlicht/io/file
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit283]
FileName=CMemoryFile.h
Folder=Irrlicht/io/file
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit284]
FileName=CReadFile.cpp
Folder=Irrlicht/io/file
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit285]
FileName=CReadFile.h
Folder=Irrlicht/io/file
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit286]
FileName=CWriteFile.cpp
Folder=Irrlicht/io/file
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit287]
FileName=CWriteFile.h
Folder=Irrlicht/io/file
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit288]
FileName=CXMLReader.cpp
Folder=Irrlicht/io/xml
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit289]
FileName=CXMLReader.h
Folder=Irrlicht/io/xml
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit290]
FileName=CXMLWriter.cpp
Folder=Irrlicht/io/xml
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit291]
FileName=CXMLWriter.h
Folder=Irrlicht/io/xml
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit292]
FileName=CZipReader.cpp
Folder=Irrlicht/io/archive
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit293]
FileName=CZipReader.h
Folder=Irrlicht/io/archive
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit294]
FileName=irrXML.cpp
Folder=Irrlicht/io/xml
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit295]
FileName=zlib\adler32.c
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit296]
FileName=zlib\compress.c
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit297]
FileName=zlib\crc32.c
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit298]
FileName=zlib\crc32.h
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit299]
FileName=zlib\deflate.c
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit300]
FileName=zlib\deflate.h
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit301]
FileName=zlib\inffast.c
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit302]
FileName=zlib\inffast.h
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit303]
FileName=zlib\inflate.c
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit304]
FileName=zlib\inftrees.c
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit305]
FileName=zlib\inftrees.h
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit306]
FileName=zlib\trees.c
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit307]
FileName=zlib\trees.h
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit308]
FileName=zlib\uncompr.c
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit309]
FileName=zlib\zconf.h
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit310]
FileName=zlib\zlib.h
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit311]
FileName=zlib\zutil.c
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit312]
FileName=zlib\zutil.h
Folder=Irrlicht/extern/zlib
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit313]
FileName=jpeglib\cderror.h
Folder=Irrlicht/extern/jpeglib
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit314]
FileName=CSceneNodeAnimatorCameraFPS.h
CompileCpp=1
Folder=Irrlicht/scene/animators
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit315]
FileName=CSceneNodeAnimatorCameraMaya.cpp
CompileCpp=1
Folder=Irrlicht/scene/animators
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit316]
FileName=jpeglib\jcapimin.c
Folder=Irrlicht/extern/jpeglib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit317]
FileName=jpeglib\jcapistd.c
Folder=Irrlicht/extern/jpeglib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit318]
FileName=jpeglib\jccoefct.c
Folder=Irrlicht/extern/jpeglib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit319]
FileName=jpeglib\jccolor.c
Folder=Irrlicht/extern/jpeglib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit320]
FileName=jpeglib\jcdctmgr.c
Folder=Irrlicht/extern/jpeglib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit321]
FileName=jpeglib\jchuff.c
Folder=Irrlicht/extern/jpeglib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit322]
FileName=jpeglib\jchuff.h
Folder=Irrlicht/extern/jpeglib
Compile=1
CompileCpp=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit323]
FileName=jpeglib\jcinit.c
Folder=Irrlicht/extern/jpeglib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit324]
FileName=jpeglib\jcmainct.c
Folder=Irrlicht/extern/jpeglib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit325]
FileName=jpeglib\jcmarker.c
Folder=Irrlicht/extern/jpeglib
Compile=1
CompileCpp=0
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit326]
FileName=jpeglib\jcmaster.c
Folder=Irrlicht/extern/jpeglib
Compile=1
|
paupawsan/Irrlicht
|
ccdd79fc9afbb9255fb1788ff415d28b7819f889
|
Prevent Borland compile warnings in SColorHSL::FromRGB and in SVertexColorThresholdManipulator (found by mdeininger)
|
diff --git a/changes.txt b/changes.txt
index 8df93e7..fa5c75a 100644
--- a/changes.txt
+++ b/changes.txt
@@ -1,515 +1,521 @@
-----------------------------
Changes in 1.7.1 (17.02.2010)
+ - Prevent borland compile warnings in SColorHSL::FromRGB and in SVertexColorThresholdManipulator (found by mdeininger)
+
+ - Improve Windows version detection rules (Patch from brferreira)
+
+ - Make it compile on Borland compilers (thx to mdeininger)
+
- Make sure that CAnimatedMeshSceneNode::clone calls the virtual updateAbsolutePosition for the new object
- Fix that clones got dropped too often when SceneNodes without parent got cloned (found by Ulf)
- Make sure TAB is still recognized on X11 when shift+tab is pressed. This does also fix going to the previous tabstop on X11.
- Send EGET_ELEMENT_LEFT also when there won't be a new hovered element
- Update docs for EGET_ELEMENT_LEFT and EGET_ELEMENT_HOVERED
- Fix tooltips: Remove them when the element is hidden or removed (thx to seven for finding)
- Fix tooltips: Make (more) sure they don't get confused by gui-subelements
- Fix tooltips: Get faster relaunch times working
- Fix tooltips: Make sure hovered element is never the tooltip itself
- Fix string::remove which got in an endless loop when remove was called with an empty string (found and fixed by Ulf)
- Correctly release the GLSL shaders
- Make sure we only release an X11 atom when it was actually created
- Fix aabbox collision test, which not only broke the collision test routines, but also frustum culling, octree tests, etc.
- Fix compilation problem under OSX due to wrong glProgramParameteri usage
- mem leak in OBJ loader fixed
- Removed some default parameters to reduce ambigious situations
---------------------------
Changes in 1.7 (03.02.2010)
- Implement minimize and deminimize under OSX.
- Define sorting order for vector2d and vector3d in operators <, <=, > and >= to fix bugs 2783509 and 2783510. Operators order now by X,Y,Z and use float tolerances.
- Ogre mesh 32bit indices fixed.
- Fix tooltips for gui-elements with sub-element like IGUISpinBox (id: 2927079, found by ArakisTheKitsune)
- ITimer no longer stops when started twice
- wchar_t filesystem updates under Windows.
- Joystick POV fixed under Windows, ids fixed under OSX.
- Some updates to skinned mesh for better bones support and scaling animations.
- OSX supports external window id in creation parameters now.
- Fix bbox collision tests.
- Updates for win32 key handling
- new convenience method for flat plane creation.
- Sky dome and other meshes use VBOs by default now.
- Speed up b3d loading for files with many frames, material color flags and vertex color support enhanced.
- Add hasType to IGUIElement as a dynamic_cast substitute.
- Add another parameter to IGUISkin::draw3DWindowBackground to allow getting the client area without actually drawing
- Add function getClientRect to IGUIWindow for getting the draw-able area
- Fix bug that menus on IGUIWindows with titlebar got drawn too high (id: 2714400)
- Renamed OctTree to Octree
- Allow getting a ConstIterator from a non-const core:list
- Add swap functions to irrMath and to the core classes.
- Deprecate map::isEmpty() and replace it with map::empty() to make it similar to other base classes.
- Allow to set the logging level already in SIrrlichtCreationParameters.
- Add clearSystemMessages to devices (implemented only for Linux and Win32 so far).
- Support changing the render window from beginScene also with OpenGL driver.
- Add getMaterial2D which allows to alter the 2d render state settings, such as filtering, anti-aliasing, thickness, etc.
- Fix incorrect cursorpos for resizable windows on Windows Vista (found and patched by buffer)
- Change the beginScene window parameter from void* to SExposedVideoData&. This will allow to manage contexts for OpenGL at some point.
- Add bzip2 and LZMA decompression modes for zip loader.
- Add OBJ_TEXTURE_PATH and B3D_TEXTURE_PATH to SceneParameters to allow setting texture-paths for obj and b3d.
- Irrlicht keeps now filenames additionally to the internally used names, thereby fixing some problems with uppercase-filenames on Linux.
- Bugfix: Mousewheel no longer sends EMIE_MOUSE_WHEEL messages twice on Linux.
- Use latest jpeglib
- refactoring: E_ATTRIBUTE_TYPE and IAttribute have now own headers
- CStringWArrayAttribute speedup
- SceneNodeAnimatorFollowSpline can now loop and pingpong
- Meshviewer.example got some fast-scale buttons.
- Support AES-encrypted zip files. Should work with 128, 196, and 256 bit AES. This addition also adds a new PRNG, SHA, and other algorithms to the engine, though no interface is yet added for them. The implementation of the encryption algorithms is provided by Dr Brian Gladman.
- flattenFilename and getAbsolutePath fixed and properly added at several places.
- Added geometry shaders for OpenGL. A first version of the code was submitted by Matthew Kielan (devsh).
- Bugfix: irrArray should no longer crash when using other allocators.
- Add MaterialViewer example.
- Texture activation now back in setMaterial, which simplifies writing external material renderers (OpenGL only).
- Checkbox uses now disabled text color when disabled.
- Changed colors for window-title caption to keep them readable when not active.
- Draw sub-menus to left side if they would be outside main-window otherwise.
- Give ListBox better defaults for the ScrollBar stepsizes.
- Double and triple click events now for each mouse-button. Old events for that got removed.
- Fix adding archives twice, which caused multiple archives of the same name and type covering each other. This one required a texture name change from using backslashes to slashes under Windows.
- Give access to texture mipmaps. You can provide custom mipmap textures upon generation, regeneration, and locking.
Make sure the provided data is large enough and covers all miplevels. Also the returned pointer (from lock) will only cover the smaller data of the mipmap level dimension chosen (level 0 is the original texture).
- Separate TextureWrap mode into U and V fields
- Add mirror texture wrap modes
- windows show now active/inactive state
- remove unneeded drop/grab calls found by manik_sheeri
- fix rounding problem in IGUIElements which have EGUIA_SCALE alignments.
- MessageBox supports now automatic resizing and images.
Deprecated EGDS_MESSAGE_BOX_WIDTH and EGDS_MESSAGE_BOX_HEIGHT
- Let maya-cam animator react on a setTarget call to the camera which happened outside it's own control
- New contextmenue features:
automatic checking for checked flag.
close handling now customizable
serialization can handle incomplete xml's
setEventParent now in public interface
New function findItemWithCommandId
New function insertItem
- new vector3d::getSphericalCoordinateAngles method.
- new triangle3d::isTotalOutsideBox method.
- Newly introduced VertexManipulator interface. This allows for very easy creation of vertex manipulation algorithms. Several manipulators, e.g. vertex color changer and transformation algorithms are already available.
- createMeshWith1TCoords avoids vertex duplication
- getRotation now handles matrices with scaling as well
- Ogre format animations now supported.
- irrArray: Fixed issues with push_front and reallocation
Changed behavior for set_pointer and clear, when free_when_destroyed is false
- NPK (Nebula device archive) reader added, it's an uncompressed PAK-like format
- SSkinMeshBuffer::MoveTo* methods renamed to convertTo*
- Multiple Render Target (MRT) support added, including some enhanced blend features where supported
- Directory changing fixed for virtual file systems (Archives etc)
- Fix texture matrix init in scene manager and driver
- More draw2dimage support in software drivers
- Sphere node now properly chooses a good tesselation based on the parameters
- Active camera not registered twice anymore
- Parallax/normal map shader rotation bug under OpenGL fixed
- bump map handling for obj files fixed
- Fog serialization added
- New context menu features added
- Bounding Box updates for skinned meshes fixed
- The current FPS for an animated scene node can be queried now, added some variables to serialization
- Scrollbars fixed
- Fixed 2d vertex primitive method to correctly handle transparency
- Fullscreen handling has been enhanced for Windows, now proper resolution is restored on Alt-Tab etc.
- Cameras can now be added to the scene node without automatically activating them
Clone method added
- New video driver method getMaxTextureSize
- PAK archive reader fixed
- TRANSPARENT_ALPHA_CHANNEL_REF uses modulate to enable lighting
- LIGHTMAP_ADD now always uses add operator
- Some Unicode file system fixes
- destructor of irrString not virtual anymore, please don't derive from irrString
Some new methods added, for searching and splitting
Assignment operator optimized
- new lightness method for SColor
- draw3DTriangle now renders filled polygons, old behavior can be achieved by setting EMT_WIREFRAME
-----------------------------
Changes in 1.6.1 (13.01.2010)
- Fix pingpong for CSceneNodeAnimatorFlyStraight (found by gbox)
- Fix bug with IGUIEditBox where the cursor position is reset on text change.
- Make sure the window top-left corner on Windows is not negative on start so that Windows sytem-menu is always visible.
- Fix problem that the window did sometimes not get the keyboard focus in X11 in fullscreen. Add more debug output in case focus grabbing goes wrong.
- Fix screensize in videodriver when we didn't get the requested window size. This also prevents that gui-clicks are no longer synchronized with gui-drawing and elements can't be hit anymore.
- Bugfix: Prevent a crash when getTypeName was called for the guienvironment. EGUIET_ELEMENT got changed for this.
- Bugfix: Horizontal centered font with linebreaks draw now all lines. For example multiline TextSceneNodes work again.
- Bugfix: spinbox can no longer get in an endless loop due to floating point rounding error (found by slavik262)
- !!API change!! Disabled AntiAliasing of Lines in material default
Please enable this manually per material when sure that it won't lead to SW rendering.
- IGUIComboBox: clicking on the statictext displaying the active selection does now close and open listbox correctly. (Bug found by Reiko)
- Scrollbuttons in IGUITabControl adapt now to tab-height.
- Fix texturing of cylinder mesh
- Fix modal dialog position (found by LoneBoco: http://sourceforge.net/tracker/?func=detail&aid=2900266&group_id=74339&atid=540676)
- Fix DMF loading
- Fixing left+right special keys (ctrl, shift, alt) on Win32 (thanks to pc0de for good patch-ideas).
- Make stringarrays for enums in IGUISkin a little safer
- Add support for keys KEY_PRINT, KEY_HOME (on numpad) and KEY_NUMLOCK on Linux.
- Fix material handling in createMeshWith1TCoords
- Fix another (OldValue == NewValue) before drop()/grap(), this time in CTextureAttribute::setTexture.
- Fix LIGHTMAP_LIGHTING for D3D drivers.
- AntiAliasing disabled for debug render elements.
- Bugfix: CGUIToolBar::addButton does no longer mess up when no image is set and does now actually work with the text.
- Fix ninja animation range which got messed up a little when b3d animations got fixed (thx gbox for finding)
---------------------------
Changes in 1.6 (23.09.2009)
- Added IFileSystem::createEmptyFileList, exposed IFileList::sort, addItem and added getID
- Fix MAKE_IRR_ID so it can be used from outside the irr namespace (Micha's patch)
- Renamed some methods in ISkinnedMesh to match the official Irrlicht naming scheme according to createXXX()
- Change debug data to draw using lines instead of arrows, which is much faster. Patch by pc0de
- Fix a bug with FPS camera animator causing stutters. Patch by FuzzYspo0N
- Fix scrolling controls in CGUITabControl
- Fix a bug when getting optimal texture size in D3D drivers, by Jetro Lauha (tonic)
- Added EGDS_TITLEBARTEXT_DISTANCE_X and EGDS_TITLEBARTEXT_DISTANCE_Y to GUI, submitted by FuzzYspo0N
- Fix for UFT8 filenames displayed in file dialog, patch by MadHyde.
- Added const method for array::binary_search, potentially slow as it doesn't sort the list!
- Add support for scaling button images.
- Irrlicht can now come with multiple device types compiled in, the device to use is selected by SIrrlichtCreationParameters.DeviceType. This defaults to EIDT_BEST which automatically select the best device available starting with native, then X11, SDL and finally the console.
- Added support for EXP2 fog distribution. This required a change in the setFog parameters where now an enum value instead of the bool linear is given.
- IFileSystem changes:
- Renamed the following functions-
IFileArchive::getArchiveType to getType
IFileSystem::registerFileArchive to addFileArchive
IFileSystem::unregisterFileArchive to removeFileArchive
IFileArchive::openFile to createAndOpenFile
- New enum, E_FILE_ARCHIVE_TYPE. getType on IArchiveLoader and IFileArchive now both return this.
- IFileSystem::addFileArchive takes a parameter to specify the archive type rather always using the file extension. IFileSystem::addZipFileArchive, addFolderFileArchive and addPakFileArchive now use this but these functions are now marked as deprecated. Users should now use addFileArchive instead.
- Added TAR archive loader.
- The ZIP archive loader can now load gzip files, combined with the TAR loader this means Irrlicht now has native support for .tar.gz
Currently this must be done in two calls, for example:
fileSystem->addFileArchive("path/to/myArchive.tar.gz");
fileSystem->addFileArchive("myArchive.tar");
- Fix highlighting in IGUIEditBox where kerning pairs are used in the font. For example in future italic, OS or other custom fonts.
- IOSOperator::getTextFromClipboard returns now const c8* instead of c8*
- Support for copy&paste on linux (X11) added (fixing bug 2804014 found by Pan)
- bugfix for 2795321 found by egrath: Don't rely anymore on broken XkbSetDetectableAutoRepeat.
- bugfix: CMountPointReader::openFile no longer returns true for empty files. Corresponding test added.
- Direct3D now also uses screen coordinates in 2d mode, just like OpenGL. This means that screen coords are going from 0..ScreenWidth and 0..ScreenHeight instead of -1..1.
- ALT+F4 keypress now closes Windows SDL device
- Allow Direct3D drivers in SDL, patch by Halifax
- Added compiler error when attempting to compile with VC6.
- Use setWindowTextA in Windows device for WIN64 platform, posted by veegun
- ELL_ERROR log events are now created when shaders fail to compile or link, reported by Halan
- irrList now uses irrAllocator, fixed by Nox
- Added IGUIWindow::setDraggable and IGUIWindow::isDraggable, by Nox
- Added SGI RGB file reader by Gary Conway, for loading Silicon Graphics .rgb, .rgba, .sgi, .int and .inta textures
- Renamed setResizeAble to setResizable
- Added new device method minimizeWindow which minimizes the window (just as if the minimize button has been clicked).
- SkyDome is now serialized correctly
- Added PLY mesh reader and writer
- Ensure ListBox on combo box doesn't hang off the bottom of the GUI root, by Matthias Specht
- Made IGUIElements recalculate clipping rectangle after setNotClipped, reported by Aelis440
- Bug fix for the combo box where it showed white text instead of skin colour before being focused, fix posted by drewbacca
- EGDS_MESSAGE_BOX_HEIGHT is now honoured, bug reported by Spkka
- Fixed a bug in the edit box where events are sometimes sent to a null parent, reported by Sudi.
- Coordinate system fix for OpenGL in SDL device
- Added generic console device. You can now use Irrlicht to create and manipuate graphics on a shell where no graphics hardware
or windowing system is available. To enable it uncomment #define _IRR_USE_CONSOLE_DEVICE_ in IrrCompileConfig.h
- The console device can now present images from the software drivers and display them as ASCII art in the console
- By default it replaces the default font in the skin, to prevent fonts from being huge.
- Fixed problems with changing cursor visibility while mouse is pressed on windows
- Allow control of background drawing in listbox
- Allow control of drawing background and titlebar in windows
- Improved window serialization
- Add mouse events EMIE_MOUSE_DOUBLE_CLICK and EMIE_MOUSE_TRIPLE_CLICK (thx to Ulf for patch proposal)
- Set "ButtonStates" for mouse events also on Linux (was only for Windows formerly)
- Add Shift+Control states to mouse event
- bugfix (2003238): serialize modal screens
- allow stacking modal screens
- allowing hiding modals
- replace many IsVisible checks with virtual isVisible() checks in IGUIElement
- bugfix: reset selected row when clearing CGUITable
- adding events EGET_EDITBOX_CHANGED and EGET_EDITBOX_MARKING_CHANGED
- prevent editbox from recalculating its textbreaking each frame
- let spinbox react on each textchange without waiting for enter to prevent getting value changes without corresponding EGET_SPINBOX_CHANGED events.
- new test for zipreader
- prevent dropping objects accidentally in many set functions
- Reversed change in vector3d::normalize.
Works now again as documented and a corresponding test has been added.
Does fix bug 2770709 (https://sourceforge.net/tracker/?func=detail&aid=2770709&group_id=74339&atid=540676)
- Animations can now be paused by setting the fps to 0.
- Avoid fp-precision problem in getPickedNodeBB (see also http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=33838&highlight=).
This change might also fix the problem with picking nodes found by aanderse (http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=32890&highlight=)
- implemented isALoadableFileFormat ( File *file ) for the Archive Loader
- PixelBlend16 and PixelBlend16_simd are working for the new rules.
- bugfix. CLightSceneNode didn't correctly update it's attributes
- vector template and equals tests
also set the equal test for s32 to behave like the f32 routine.
The function equals always implements a weak test.
that means a tolerance MUST always be used if you use the equal function. default is 1.
- VideoDriver drawPixel
The HW renderes are using the alpha components for blending.
The Software Renderes and image loaders are using CImage::setPixel copy.
so setPixel is engaged to either blends or copy the pixel
default: false
- Burningvideo
added RenderMaterial EMT_SPHERE_MAP
pushed burningsvideo to 0.43
added RenderMaterial EMT_REFLECTION_2_LAYER
pushed burningsvideo to 0.44
set EMT_TRANSPARENT_ALPHA_CHANNEL_REF
to use AlphaRef 0.5 like Direct3D
One Note: in OpenGL there is know difference between sphere_map and reflection layer
both using GL_TEXTURE_GEN_MODE GL_SPHERE_MAP, whereas in d3d one time using camera_normal
on sphere and reflection on refletcion_layer.
The visual difference is that on sphere map the "image is not moving" when you rotate the
viewer. For Burning i took the opengl visual. always moving
- rename quake3 SEntity to IEntity to be confom with IShader
- fixed createMeshWith2TCoords, normals were missing during copy.
- added
//! Creates a copy of the mesh, which will only consist of S3DVertex vertices.
IMesh* CMeshManipulator::createMeshWith1TCoords(IMesh* mesh) const
- added io::IFileSystem* CSceneManager::getFileSystem()
- added virtual const c8* ISceneManager::getAnimatorTypeName(ESCENE_NODE_ANIMATOR_TYPE type);
- added CSceneNodeAnimatorFlyCircle::radiusEllipsoid.
if radiusEllipsoid == 0 the default circle animation is done
else radiusEllipsoid forms the b-axe of the ellipsoid.
-> gummiball bouncing
- added ISceneManager::createFlyStraightAnimator variable bool ping-pong
used in loop mode to device if start from beginning ( default ) or make ping-pong
-> straight bouncing
- changed IFileSystem::registerFileArchive
remove the index of the hierarchy and added a new interface method
//! move the hirarchy of the filesystem. moves sourceIndex relative up or down
virtual bool moveFileArchive( u32 sourceIndex, s32 relative ) = 0;
- bugfix and changes in SViewFrustum::SViewFrustum
wrong size of Matrices copy.
renamed E_TRANSFORMATION_STATE_2 to E_TRANSFORMATION_STATE_FRUSTUM
therefore also changed SViewFrustum::setTransformState to not tap
in the pitfall again of wrong memory...
- moved
//! EMT_ONETEXTURE_BLEND: has BlendFactor Alphablending
inline bool textureBlendFunc_hasAlpha ( E_BLEND_FACTOR factor ) const
from the material renderes ( 3x declared ) to SMaterial.h
- updated managed light example to use standard driver selection
- BurningsVideo
- LightModel reworked.
Point Light & Direction Light works for Diffuse Color as expected
Specular and Fog still have problems ( needs new pixel shader )
pushed burningsvideo to 0.42 for this major step
- removed obsolete matrix transformations
renamed E_TRANSFORMATION_STATE_2 to E_TRANSFORMATION_STATE_BURNING
- cleaned line3d.h vector3d.h template behavior.
many mixed f32/f64 implementations are here. i'm not sure if this should be
the default behavior to use f64 for example for 1.0/x value, because they
benefit from more precisions, but in my point of view the user is responsible
of choosing a vector3d<f32> or vector3d<f64>.
- added core::squareroot to irrmath.h
-> for having candidates for faster math in the same file
- added AllowZWriteOnTransparent from SceneManager to burningsvideo
diff --git a/include/SColor.h b/include/SColor.h
index 400a88a..763ee89 100644
--- a/include/SColor.h
+++ b/include/SColor.h
@@ -1,581 +1,582 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __COLOR_H_INCLUDED__
#define __COLOR_H_INCLUDED__
#include "irrTypes.h"
#include "irrMath.h"
namespace irr
{
namespace video
{
//! Creates a 16 bit A1R5G5B5 color
inline u16 RGBA16(u32 r, u32 g, u32 b, u32 a=0xFF)
{
return (u16)((a & 0x80) << 8 |
(r & 0xF8) << 7 |
(g & 0xF8) << 2 |
(b & 0xF8) >> 3);
}
//! Creates a 16 bit A1R5G5B5 color
inline u16 RGB16(u32 r, u32 g, u32 b)
{
return RGBA16(r,g,b);
}
//! Creates a 16bit A1R5G5B5 color, based on 16bit input values
inline u16 RGB16from16(u16 r, u16 g, u16 b)
{
return (0x8000 |
(r & 0x1F) << 10 |
(g & 0x1F) << 5 |
(b & 0x1F));
}
//! Converts a 32bit (X8R8G8B8) color to a 16bit A1R5G5B5 color
inline u16 X8R8G8B8toA1R5G5B5(u32 color)
{
return (u16)(0x8000 |
( color & 0x00F80000) >> 9 |
( color & 0x0000F800) >> 6 |
( color & 0x000000F8) >> 3);
}
//! Converts a 32bit (A8R8G8B8) color to a 16bit A1R5G5B5 color
inline u16 A8R8G8B8toA1R5G5B5(u32 color)
{
return (u16)(( color & 0x80000000) >> 16|
( color & 0x00F80000) >> 9 |
( color & 0x0000F800) >> 6 |
( color & 0x000000F8) >> 3);
}
//! Converts a 32bit (A8R8G8B8) color to a 16bit R5G6B5 color
inline u16 A8R8G8B8toR5G6B5(u32 color)
{
return (u16)(( color & 0x00F80000) >> 8 |
( color & 0x0000FC00) >> 5 |
( color & 0x000000F8) >> 3);
}
//! Convert A8R8G8B8 Color from A1R5G5B5 color
/** build a nicer 32bit Color by extending dest lower bits with source high bits. */
inline u32 A1R5G5B5toA8R8G8B8(u16 color)
{
return ( (( -( (s32) color & 0x00008000 ) >> (s32) 31 ) & 0xFF000000 ) |
(( color & 0x00007C00 ) << 9) | (( color & 0x00007000 ) << 4) |
(( color & 0x000003E0 ) << 6) | (( color & 0x00000380 ) << 1) |
(( color & 0x0000001F ) << 3) | (( color & 0x0000001C ) >> 2)
);
}
//! Returns A8R8G8B8 Color from R5G6B5 color
inline u32 R5G6B5toA8R8G8B8(u16 color)
{
return 0xFF000000 |
((color & 0xF800) << 8)|
((color & 0x07E0) << 5)|
((color & 0x001F) << 3);
}
//! Returns A1R5G5B5 Color from R5G6B5 color
inline u16 R5G6B5toA1R5G5B5(u16 color)
{
return 0x8000 | (((color & 0xFFC0) >> 1) | (color & 0x1F));
}
//! Returns R5G6B5 Color from A1R5G5B5 color
inline u16 A1R5G5B5toR5G6B5(u16 color)
{
return (((color & 0x7FE0) << 1) | (color & 0x1F));
}
//! Returns the alpha component from A1R5G5B5 color
- /** In Irrlicht, alpha refers to opacity.
+ /** In Irrlicht, alpha refers to opacity.
\return The alpha value of the color. 0 is transparent, 1 is opaque. */
inline u32 getAlpha(u16 color)
{
return ((color >> 15)&0x1);
}
//! Returns the red component from A1R5G5B5 color.
/** Shift left by 3 to get 8 bit value. */
inline u32 getRed(u16 color)
{
return ((color >> 10)&0x1F);
}
//! Returns the green component from A1R5G5B5 color
/** Shift left by 3 to get 8 bit value. */
inline u32 getGreen(u16 color)
{
return ((color >> 5)&0x1F);
}
//! Returns the blue component from A1R5G5B5 color
/** Shift left by 3 to get 8 bit value. */
inline u32 getBlue(u16 color)
{
return (color & 0x1F);
}
//! Returns the average from a 16 bit A1R5G5B5 color
inline s32 getAverage(s16 color)
{
return ((getRed(color)<<3) + (getGreen(color)<<3) + (getBlue(color)<<3)) / 3;
}
//! Class representing a 32 bit ARGB color.
/** The color values for alpha, red, green, and blue are
stored in a single u32. So all four values may be between 0 and 255.
Alpha in Irrlicht is opacity, so 0 is fully transparent, 255 is fully opaque (solid).
This class is used by most parts of the Irrlicht Engine
to specify a color. Another way is using the class SColorf, which
stores the color values in 4 floats.
This class must consist of only one u32 and must not use virtual functions.
*/
class SColor
{
public:
//! Constructor of the Color. Does nothing.
/** The color value is not initialized to save time. */
SColor() {}
//! Constructs the color from 4 values representing the alpha, red, green and blue component.
/** Must be values between 0 and 255. */
SColor (u32 a, u32 r, u32 g, u32 b)
: color(((a & 0xff)<<24) | ((r & 0xff)<<16) | ((g & 0xff)<<8) | (b & 0xff)) {}
//! Constructs the color from a 32 bit value. Could be another color.
SColor(u32 clr)
: color(clr) {}
//! Returns the alpha component of the color.
- /** The alpha component defines how opaque a color is.
+ /** The alpha component defines how opaque a color is.
\return The alpha value of the color. 0 is fully transparent, 255 is fully opaque. */
u32 getAlpha() const { return color>>24; }
//! Returns the red component of the color.
/** \return Value between 0 and 255, specifying how red the color is.
0 means no red, 255 means full red. */
u32 getRed() const { return (color>>16) & 0xff; }
//! Returns the green component of the color.
/** \return Value between 0 and 255, specifying how green the color is.
0 means no green, 255 means full green. */
u32 getGreen() const { return (color>>8) & 0xff; }
//! Returns the blue component of the color.
/** \return Value between 0 and 255, specifying how blue the color is.
0 means no blue, 255 means full blue. */
u32 getBlue() const { return color & 0xff; }
//! Get lightness of the color in the range [0,255]
f32 getLightness() const
{
return 0.5f*(core::max_(core::max_(getRed(),getGreen()),getBlue())+core::min_(core::min_(getRed(),getGreen()),getBlue()));
}
//! Get luminance of the color in the range [0,255].
f32 getLuminance() const
{
return 0.3f*getRed() + 0.59f*getGreen() + 0.11f*getBlue();
}
//! Get average intensity of the color in the range [0,255].
u32 getAverage() const
{
return ( getRed() + getGreen() + getBlue() ) / 3;
}
//! Sets the alpha component of the Color.
/** The alpha component defines how transparent a color should be.
\param a The alpha value of the color. 0 is fully transparent, 255 is fully opaque. */
void setAlpha(u32 a) { color = ((a & 0xff)<<24) | (color & 0x00ffffff); }
//! Sets the red component of the Color.
/** \param r: Has to be a value between 0 and 255.
0 means no red, 255 means full red. */
void setRed(u32 r) { color = ((r & 0xff)<<16) | (color & 0xff00ffff); }
//! Sets the green component of the Color.
/** \param g: Has to be a value between 0 and 255.
0 means no green, 255 means full green. */
void setGreen(u32 g) { color = ((g & 0xff)<<8) | (color & 0xffff00ff); }
//! Sets the blue component of the Color.
/** \param b: Has to be a value between 0 and 255.
0 means no blue, 255 means full blue. */
void setBlue(u32 b) { color = (b & 0xff) | (color & 0xffffff00); }
//! Calculates a 16 bit A1R5G5B5 value of this color.
/** \return 16 bit A1R5G5B5 value of this color. */
u16 toA1R5G5B5() const { return A8R8G8B8toA1R5G5B5(color); }
//! Converts color to OpenGL color format
/** From ARGB to RGBA in 4 byte components for endian aware
passing to OpenGL
\param dest: address where the 4x8 bit OpenGL color is stored. */
void toOpenGLColor(u8* dest) const
{
*dest = (u8)getRed();
*++dest = (u8)getGreen();
*++dest = (u8)getBlue();
*++dest = (u8)getAlpha();
}
//! Sets all four components of the color at once.
/** Constructs the color from 4 values representing the alpha,
red, green and blue components of the color. Must be values
between 0 and 255.
\param a: Alpha component of the color. The alpha component
defines how transparent a color should be. Has to be a value
between 0 and 255. 255 means not transparent (opaque), 0 means
fully transparent.
\param r: Sets the red component of the Color. Has to be a
value between 0 and 255. 0 means no red, 255 means full red.
\param g: Sets the green component of the Color. Has to be a
value between 0 and 255. 0 means no green, 255 means full
green.
\param b: Sets the blue component of the Color. Has to be a
value between 0 and 255. 0 means no blue, 255 means full blue. */
void set(u32 a, u32 r, u32 g, u32 b)
{
color = (((a & 0xff)<<24) | ((r & 0xff)<<16) | ((g & 0xff)<<8) | (b & 0xff));
}
void set(u32 col) { color = col; }
//! Compares the color to another color.
/** \return True if the colors are the same, and false if not. */
bool operator==(const SColor& other) const { return other.color == color; }
//! Compares the color to another color.
/** \return True if the colors are different, and false if they are the same. */
bool operator!=(const SColor& other) const { return other.color != color; }
//! comparison operator
/** \return True if this color is smaller than the other one */
bool operator<(const SColor& other) const { return (color < other.color); }
//! Adds two colors, result is clamped to 0..255 values
/** \param other Color to add to this color
\return Addition of the two colors, clamped to 0..255 values */
SColor operator+(const SColor& other) const
{
return SColor(core::min_(getAlpha() + other.getAlpha(), 255u),
core::min_(getRed() + other.getRed(), 255u),
core::min_(getGreen() + other.getGreen(), 255u),
core::min_(getBlue() + other.getBlue(), 255u));
}
//! Interpolates the color with a f32 value to another color
/** \param other: Other color
\param d: value between 0.0f and 1.0f
\return Interpolated color. */
SColor getInterpolated(const SColor &other, f32 d) const
{
d = core::clamp(d, 0.f, 1.f);
const f32 inv = 1.0f - d;
return SColor((u32)(other.getAlpha()*inv + getAlpha()*d),
(u32)(other.getRed()*inv + getRed()*d),
(u32)(other.getGreen()*inv + getGreen()*d),
(u32)(other.getBlue()*inv + getBlue()*d));
}
//! Returns interpolated color. ( quadratic )
/** \param c1: first color to interpolate with
\param c2: second color to interpolate with
\param d: value between 0.0f and 1.0f. */
SColor getInterpolated_quadratic(const SColor& c1, const SColor& c2, f32 d) const
{
// this*(1-d)*(1-d) + 2 * c1 * (1-d) + c2 * d * d;
d = core::clamp(d, 0.f, 1.f);
const f32 inv = 1.f - d;
const f32 mul0 = inv * inv;
const f32 mul1 = 2.f * d * inv;
const f32 mul2 = d * d;
return SColor(
core::clamp( core::floor32(
getAlpha() * mul0 + c1.getAlpha() * mul1 + c2.getAlpha() * mul2 ), 0, 255 ),
core::clamp( core::floor32(
getRed() * mul0 + c1.getRed() * mul1 + c2.getRed() * mul2 ), 0, 255 ),
core::clamp ( core::floor32(
getGreen() * mul0 + c1.getGreen() * mul1 + c2.getGreen() * mul2 ), 0, 255 ),
core::clamp ( core::floor32(
getBlue() * mul0 + c1.getBlue() * mul1 + c2.getBlue() * mul2 ), 0, 255 ));
}
//! color in A8R8G8B8 Format
u32 color;
};
//! Class representing a color with four floats.
/** The color values for red, green, blue
and alpha are each stored in a 32 bit floating point variable.
So all four values may be between 0.0f and 1.0f.
Another, faster way to define colors is using the class SColor, which
stores the color values in a single 32 bit integer.
*/
class SColorf
{
public:
//! Default constructor for SColorf.
/** Sets red, green and blue to 0.0f and alpha to 1.0f. */
SColorf() : r(0.0f), g(0.0f), b(0.0f), a(1.0f) {}
//! Constructs a color from up to four color values: red, green, blue, and alpha.
/** \param r: Red color component. Should be a value between
0.0f meaning no red and 1.0f, meaning full red.
\param g: Green color component. Should be a value between 0.0f
meaning no green and 1.0f, meaning full green.
\param b: Blue color component. Should be a value between 0.0f
meaning no blue and 1.0f, meaning full blue.
\param a: Alpha color component of the color. The alpha
component defines how transparent a color should be. Has to be
a value between 0.0f and 1.0f, 1.0f means not transparent
(opaque), 0.0f means fully transparent. */
SColorf(f32 r, f32 g, f32 b, f32 a = 1.0f) : r(r), g(g), b(b), a(a) {}
//! Constructs a color from 32 bit Color.
/** \param c: 32 bit color from which this SColorf class is
constructed from. */
SColorf(SColor c)
{
const f32 inv = 1.0f / 255.0f;
r = c.getRed() * inv;
g = c.getGreen() * inv;
b = c.getBlue() * inv;
a = c.getAlpha() * inv;
}
//! Converts this color to a SColor without floats.
SColor toSColor() const
{
return SColor((u32)(a*255.0f), (u32)(r*255.0f), (u32)(g*255.0f), (u32)(b*255.0f));
}
//! Sets three color components to new values at once.
/** \param rr: Red color component. Should be a value between 0.0f meaning
no red (=black) and 1.0f, meaning full red.
\param gg: Green color component. Should be a value between 0.0f meaning
no green (=black) and 1.0f, meaning full green.
\param bb: Blue color component. Should be a value between 0.0f meaning
no blue (=black) and 1.0f, meaning full blue. */
void set(f32 rr, f32 gg, f32 bb) {r = rr; g =gg; b = bb; }
//! Sets all four color components to new values at once.
/** \param aa: Alpha component. Should be a value between 0.0f meaning
fully transparent and 1.0f, meaning opaque.
\param rr: Red color component. Should be a value between 0.0f meaning
no red and 1.0f, meaning full red.
\param gg: Green color component. Should be a value between 0.0f meaning
no green and 1.0f, meaning full green.
\param bb: Blue color component. Should be a value between 0.0f meaning
no blue and 1.0f, meaning full blue. */
void set(f32 aa, f32 rr, f32 gg, f32 bb) {a = aa; r = rr; g =gg; b = bb; }
//! Interpolates the color with a f32 value to another color
/** \param other: Other color
\param d: value between 0.0f and 1.0f
\return Interpolated color. */
SColorf getInterpolated(const SColorf &other, f32 d) const
{
d = core::clamp(d, 0.f, 1.f);
const f32 inv = 1.0f - d;
return SColorf(other.r*inv + r*d,
other.g*inv + g*d, other.b*inv + b*d, other.a*inv + a*d);
}
//! Returns interpolated color. ( quadratic )
/** \param c1: first color to interpolate with
\param c2: second color to interpolate with
\param d: value between 0.0f and 1.0f. */
inline SColorf getInterpolated_quadratic(const SColorf& c1, const SColorf& c2,
f32 d) const
{
d = core::clamp(d, 0.f, 1.f);
// this*(1-d)*(1-d) + 2 * c1 * (1-d) + c2 * d * d;
const f32 inv = 1.f - d;
const f32 mul0 = inv * inv;
const f32 mul1 = 2.f * d * inv;
const f32 mul2 = d * d;
return SColorf (r * mul0 + c1.r * mul1 + c2.r * mul2,
g * mul0 + c1.g * mul1 + c2.g * mul2,
g * mul0 + c1.b * mul1 + c2.b * mul2,
a * mul0 + c1.a * mul1 + c2.a * mul2);
}
//! Sets a color component by index. R=0, G=1, B=2, A=3
void setColorComponentValue(s32 index, f32 value)
{
switch(index)
{
case 0: r = value; break;
case 1: g = value; break;
case 2: b = value; break;
case 3: a = value; break;
}
}
//! Returns the alpha component of the color in the range 0.0 (transparent) to 1.0 (opaque)
f32 getAlpha() const { return a; }
//! Returns the red component of the color in the range 0.0 to 1.0
f32 getRed() const { return r; }
//! Returns the green component of the color in the range 0.0 to 1.0
f32 getGreen() const { return g; }
//! Returns the blue component of the color in the range 0.0 to 1.0
f32 getBlue() const { return b; }
//! red color component
f32 r;
//! green color component
f32 g;
//! blue component
f32 b;
//! alpha color component
f32 a;
};
//! Class representing a color in HSV format
/** The color values for hue, saturation, value
are stored in a 32 bit floating point variable.
*/
class SColorHSL
{
public:
SColorHSL ( f32 h = 0.f, f32 s = 0.f, f32 l = 0.f )
: Hue ( h ), Saturation ( s ), Luminance ( l ) {}
void fromRGB(const SColor &color);
void toRGB(SColor &color) const;
f32 Hue;
f32 Saturation;
f32 Luminance;
private:
inline u32 toRGB1(f32 rm1, f32 rm2, f32 rh) const;
};
inline void SColorHSL::fromRGB(const SColor &color)
{
- const f32 maxVal = (f32)core::max_(color.getRed(), color.getGreen(), color.getBlue());
+ const u32 maxValInt = core::max_(color.getRed(), color.getGreen(), color.getBlue());
+ const f32 maxVal = (f32)maxValInt;
const f32 minVal = (f32)core::min_(color.getRed(), color.getGreen(), color.getBlue());
Luminance = (maxVal/minVal)*0.5f;
if (core::equals(maxVal, minVal))
{
Hue=0.f;
Saturation=0.f;
return;
}
const f32 delta = maxVal-minVal;
if ( Luminance <= 0.5f )
{
Saturation = (delta)/(maxVal+minVal);
}
else
{
Saturation = (delta)/(2-maxVal-minVal);
}
- if (maxVal==color.getRed())
+ if (maxValInt == color.getRed())
Hue = (color.getGreen()-color.getBlue())/delta;
- else if (maxVal==color.getGreen())
+ else if (maxValInt == color.getGreen())
Hue = 2+(color.getBlue()-color.getRed())/delta;
- else if (maxVal==color.getBlue())
+ else // blue is max
Hue = 4+(color.getRed()-color.getGreen())/delta;
Hue *= (60.0f * core::DEGTORAD);
while ( Hue < 0.f )
Hue += 2.f * core::PI;
}
inline void SColorHSL::toRGB(SColor &color) const
{
if (core::iszero(Saturation)) // grey
{
u8 c = (u8) ( Luminance * 255.0 );
color.setRed(c);
color.setGreen(c);
color.setBlue(c);
return;
}
f32 rm2;
if ( Luminance <= 0.5f )
{
rm2 = Luminance + Luminance * Saturation;
}
else
{
rm2 = Luminance + Saturation - Luminance * Saturation;
}
const f32 rm1 = 2.0f * Luminance - rm2;
color.setRed ( toRGB1(rm1, rm2, Hue + (120.0f * core::DEGTORAD )) );
color.setGreen ( toRGB1(rm1, rm2, Hue) );
color.setBlue ( toRGB1(rm1, rm2, Hue - (120.0f * core::DEGTORAD) ) );
}
inline u32 SColorHSL::toRGB1(f32 rm1, f32 rm2, f32 rh) const
{
while ( rh > 2.f * core::PI )
rh -= 2.f * core::PI;
while ( rh < 0.f )
rh += 2.f * core::PI;
if (rh < 60.0f * core::DEGTORAD )
rm1 = rm1 + (rm2 - rm1) * rh / (60.0f * core::DEGTORAD);
else if (rh < 180.0f * core::DEGTORAD )
rm1 = rm2;
else if (rh < 240.0f * core::DEGTORAD )
rm1 = rm1 + (rm2 - rm1) * ( ( 240.0f * core::DEGTORAD ) - rh) /
(60.0f * core::DEGTORAD);
return (u32) (rm1 * 255.f);
}
} // end namespace video
} // end namespace irr
#endif
diff --git a/include/SVertexManipulator.h b/include/SVertexManipulator.h
index 75f77b4..097eb9c 100644
--- a/include/SVertexManipulator.h
+++ b/include/SVertexManipulator.h
@@ -1,292 +1,292 @@
// Copyright (C) 2009 Christian Stehno
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __S_VERTEX_MANIPULATOR_H_INCLUDED__
#define __S_VERTEX_MANIPULATOR_H_INCLUDED__
#include "S3DVertex.h"
#include "SColor.h"
namespace irr
{
namespace scene
{
class IMesh;
class IMeshBuffer;
struct SMesh;
//! Interface for vertex manipulators.
/** You should derive your manipulator from this class if it shall be called for every vertex, getting as parameter just the vertex.
*/
struct IVertexManipulator
{
};
//! Vertex manipulator to set color to a fixed color for all vertices
class SVertexColorSetManipulator : public IVertexManipulator
{
public:
SVertexColorSetManipulator(video::SColor color) : Color(color) {}
void operator()(video::S3DVertex& vertex) const
{
vertex.Color=Color;
}
private:
video::SColor Color;
};
//! Vertex manipulator to set the alpha value of the vertex color to a fixed value
class SVertexColorSetAlphaManipulator : public IVertexManipulator
{
public:
SVertexColorSetAlphaManipulator(u32 alpha) : Alpha(alpha) {}
void operator()(video::S3DVertex& vertex) const
{
vertex.Color.setAlpha(Alpha);
}
private:
u32 Alpha;
};
//! Vertex manipulator which invertes the RGB values
class SVertexColorInvertManipulator : public IVertexManipulator
{
public:
void operator()(video::S3DVertex& vertex) const
{
vertex.Color.setRed(255-vertex.Color.getRed());
vertex.Color.setGreen(255-vertex.Color.getGreen());
vertex.Color.setBlue(255-vertex.Color.getBlue());
}
};
//! Vertex manipulator to set vertex color to one of two values depending on a given threshold
/** If average of the color value is >Threshold the High color is chosen, else Low. */
class SVertexColorThresholdManipulator : public IVertexManipulator
{
public:
SVertexColorThresholdManipulator(u8 threshold, video::SColor low,
video::SColor high) : Threshold(threshold), Low(low), High(high) {}
void operator()(video::S3DVertex& vertex) const
{
- vertex.Color = (vertex.Color.getAverage()>Threshold)?High:Low;
+ vertex.Color = ((u8)vertex.Color.getAverage()>Threshold)?High:Low;
}
private:
u8 Threshold;
video::SColor Low;
video::SColor High;
};
//! Vertex manipulator which adjusts the brightness by the given amount
/** A positive value increases brightness, a negative value darkens the colors. */
class SVertexColorBrightnessManipulator : public IVertexManipulator
{
public:
SVertexColorBrightnessManipulator(s32 amount) : Amount(amount) {}
void operator()(video::S3DVertex& vertex) const
{
vertex.Color.setRed(core::clamp(vertex.Color.getRed()+Amount, 0u, 255u));
vertex.Color.setGreen(core::clamp(vertex.Color.getGreen()+Amount, 0u, 255u));
vertex.Color.setBlue(core::clamp(vertex.Color.getBlue()+Amount, 0u, 255u));
}
private:
s32 Amount;
};
//! Vertex manipulator which adjusts the contrast by the given factor
/** Factors over 1 increase contrast, below 1 reduce it. */
class SVertexColorContrastManipulator : public IVertexManipulator
{
public:
SVertexColorContrastManipulator(f32 factor) : Factor(factor) {}
void operator()(video::S3DVertex& vertex) const
{
vertex.Color.setRed(core::clamp(core::round32((vertex.Color.getRed()-128)*Factor)+128, 0, 255));
vertex.Color.setGreen(core::clamp(core::round32((vertex.Color.getGreen()-128)*Factor)+128, 0, 255));
vertex.Color.setBlue(core::clamp(core::round32((vertex.Color.getBlue()-128)*Factor)+128, 0, 255));
}
private:
f32 Factor;
};
//! Vertex manipulator which adjusts the contrast by the given factor and brightness by a signed amount.
/** Factors over 1 increase contrast, below 1 reduce it.
A positive amount increases brightness, a negative one darkens the colors. */
class SVertexColorContrastBrightnessManipulator : public IVertexManipulator
{
public:
SVertexColorContrastBrightnessManipulator(f32 factor, s32 amount) : Factor(factor), Amount(amount+128) {}
void operator()(video::S3DVertex& vertex) const
{
vertex.Color.setRed(core::clamp(core::round32((vertex.Color.getRed()-128)*Factor)+Amount, 0, 255));
vertex.Color.setGreen(core::clamp(core::round32((vertex.Color.getGreen()-128)*Factor)+Amount, 0, 255));
vertex.Color.setBlue(core::clamp(core::round32((vertex.Color.getBlue()-128)*Factor)+Amount, 0, 255));
}
private:
f32 Factor;
s32 Amount;
};
//! Vertex manipulator which adjusts the brightness by a gamma operation
/** A value over one increases brightness, one below darkens the colors. */
class SVertexColorGammaManipulator : public IVertexManipulator
{
public:
SVertexColorGammaManipulator(f32 gamma) : Gamma(1.f)
{
if (gamma != 0.f)
Gamma = 1.f/gamma;
}
void operator()(video::S3DVertex& vertex) const
{
vertex.Color.setRed(core::clamp(core::round32(powf((f32)(vertex.Color.getRed()),Gamma)), 0, 255));
vertex.Color.setGreen(core::clamp(core::round32(powf((f32)(vertex.Color.getGreen()),Gamma)), 0, 255));
vertex.Color.setBlue(core::clamp(core::round32(powf((f32)(vertex.Color.getBlue()),Gamma)), 0, 255));
}
private:
f32 Gamma;
};
//! Vertex manipulator which scales the color values
/** Can e.g be used for white balance, factor would be 255.f/brightest color. */
class SVertexColorScaleManipulator : public IVertexManipulator
{
public:
SVertexColorScaleManipulator(f32 factor) : Factor(factor) {}
void operator()(video::S3DVertex& vertex) const
{
vertex.Color.setRed(core::clamp(core::round32(vertex.Color.getRed()*Factor), 0, 255));
vertex.Color.setGreen(core::clamp(core::round32(vertex.Color.getGreen()*Factor), 0, 255));
vertex.Color.setBlue(core::clamp(core::round32(vertex.Color.getBlue()*Factor), 0, 255));
}
private:
f32 Factor;
};
//! Vertex manipulator which desaturates the color values
/** Uses the lightness value of the color. */
class SVertexColorDesaturateToLightnessManipulator : public IVertexManipulator
{
public:
void operator()(video::S3DVertex& vertex) const
{
vertex.Color=core::round32(vertex.Color.getLightness());
}
};
//! Vertex manipulator which desaturates the color values
/** Uses the average value of the color. */
class SVertexColorDesaturateToAverageManipulator : public IVertexManipulator
{
public:
void operator()(video::S3DVertex& vertex) const
{
vertex.Color=vertex.Color.getAverage();
}
};
//! Vertex manipulator which desaturates the color values
/** Uses the luminance value of the color. */
class SVertexColorDesaturateToLuminanceManipulator : public IVertexManipulator
{
public:
void operator()(video::S3DVertex& vertex) const
{
vertex.Color=core::round32(vertex.Color.getLuminance());
}
};
//! Vertex manipulator which interpolates the color values
/** Uses linear interpolation. */
class SVertexColorInterpolateLinearManipulator : public IVertexManipulator
{
public:
SVertexColorInterpolateLinearManipulator(video::SColor color, f32 factor) :
Color(color), Factor(factor) {}
void operator()(video::S3DVertex& vertex) const
{
vertex.Color=vertex.Color.getInterpolated(Color, Factor);
}
private:
video::SColor Color;
f32 Factor;
};
//! Vertex manipulator which interpolates the color values
/** Uses linear interpolation. */
class SVertexColorInterpolateQuadraticManipulator : public IVertexManipulator
{
public:
SVertexColorInterpolateQuadraticManipulator(video::SColor color1, video::SColor color2, f32 factor) :
Color1(color1), Color2(color2), Factor(factor) {}
void operator()(video::S3DVertex& vertex) const
{
vertex.Color=vertex.Color.getInterpolated_quadratic(Color1, Color2, Factor);
}
private:
video::SColor Color1;
video::SColor Color2;
f32 Factor;
};
//! Vertex manipulator which scales the position of the vertex
class SVertexPositionScaleManipulator : public IVertexManipulator
{
public:
SVertexPositionScaleManipulator(const core::vector3df& factor) : Factor(factor) {}
template <typename VType>
void operator()(VType& vertex) const
{
vertex.Pos *= Factor;
}
private:
core::vector3df Factor;
};
//! Vertex manipulator which scales the position of the vertex along the normals
/** This can look more pleasing than the usual Scale operator, but
depends on the mesh geometry.
*/
class SVertexPositionScaleAlongNormalsManipulator : public IVertexManipulator
{
public:
SVertexPositionScaleAlongNormalsManipulator(const core::vector3df& factor) : Factor(factor) {}
template <typename VType>
void operator()(VType& vertex) const
{
vertex.Pos += vertex.Normal*Factor;
}
private:
core::vector3df Factor;
};
//! Vertex manipulator which transforms the position of the vertex
class SVertexPositionTransformManipulator : public IVertexManipulator
{
public:
SVertexPositionTransformManipulator(const core::matrix4& m) : Transformation(m) {}
template <typename VType>
void operator()(VType& vertex) const
{
Transformation.transformVect(vertex.Pos);
}
private:
core::matrix4 Transformation;
};
//! Vertex manipulator which scales the TCoords of the vertex
class SVertexTCoordsScaleManipulator : public IVertexManipulator
{
public:
SVertexTCoordsScaleManipulator(const core::vector2df& factor, u32 uvSet=1) : Factor(factor), UVSet(uvSet) {}
void operator()(video::S3DVertex2TCoords& vertex) const
{
if (1==UVSet)
vertex.TCoords *= Factor;
else if (2==UVSet)
vertex.TCoords2 *= Factor;
}
template <typename VType>
void operator()(VType& vertex) const
{
if (1==UVSet)
vertex.TCoords *= Factor;
}
private:
core::vector2df Factor;
u32 UVSet;
};
} // end namespace scene
} // end namespace irr
#endif
diff --git a/source/Irrlicht/Irrlicht-gcc.cbp b/source/Irrlicht/Irrlicht-gcc.cbp
index 9c334b4..d9777e2 100644
--- a/source/Irrlicht/Irrlicht-gcc.cbp
+++ b/source/Irrlicht/Irrlicht-gcc.cbp
@@ -23,1024 +23,1025 @@
<Add option="-Wno-unused-parameter" />
<Add option="-DWIN32" />
<Add option="-D_DEBUG" />
<Add option="-D_WINDOWS" />
<Add option="-D_USRDLL" />
<Add option="-DIRRLICHT_EXPORTS" />
<Add option="-D_CRT_SECURE_NO_DEPRECATE" />
<Add option="-D__GNUWIN32__" />
<Add directory="../../include" />
<Add directory="zlib" />
</Compiler>
<Linker>
<Add library="kernel32" />
<Add library="user32" />
<Add library="gdi32" />
<Add library="winspool" />
<Add library="comdlg32" />
<Add library="advapi32" />
<Add library="shell32" />
<Add library="ole32" />
<Add library="oleaut32" />
<Add library="uuid" />
<Add library="opengl32" />
<Add library="winmm" />
</Linker>
<ExtraCommands>
<Add after="cmd /c del ..\..\bin\Win32-gcc\Irrlicht.dll" />
<Add after="cmd /c move ..\..\lib\Win32-gcc\Irrlicht.dll ..\..\bin\Win32-gcc\Irrlicht.dll" />
</ExtraCommands>
</Target>
<Target title="Win32 - Release - accurate math - dll">
<Option platforms="Windows;" />
<Option output="../../lib/Win32-gcc/Irrlicht" prefix_auto="1" extension_auto="1" />
<Option object_output="../obj/win32-gcc-release-dll" />
<Option type="3" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Option createStaticLib="1" />
<Compiler>
<Add option="-O2" />
<Add option="-W" />
<Add option="-Wall" />
<Add option="-Wno-unused-parameter" />
<Add option="-DWIN32" />
<Add option="-DNDEBUG" />
<Add option="-D_WINDOWS" />
<Add option="-D_USRDLL" />
<Add option="-DIRRLICHT_EXPORTS" />
<Add option="-D_CRT_SECURE_NO_DEPRECATE" />
<Add option="-D__GNUWIN32__" />
<Add directory="../../include" />
<Add directory="zlib" />
</Compiler>
<Linker>
<Add library="kernel32" />
<Add library="user32" />
<Add library="gdi32" />
<Add library="winspool" />
<Add library="comdlg32" />
<Add library="advapi32" />
<Add library="shell32" />
<Add library="ole32" />
<Add library="oleaut32" />
<Add library="uuid" />
<Add library="opengl32" />
<Add library="winmm" />
</Linker>
<ExtraCommands>
<Add after="cmd /c del ..\..\bin\Win32-gcc\Irrlicht.dll" />
<Add after="cmd /c move ..\..\lib\Win32-gcc\Irrlicht.dll ..\..\bin\Win32-gcc\Irrlicht.dll" />
</ExtraCommands>
</Target>
<Target title="Win32 - Release - fast math - dll">
<Option platforms="Windows;" />
<Option output="../../lib/Win32-gcc/Irrlicht" prefix_auto="1" extension_auto="1" />
<Option object_output="../obj/win32-gcc-release-fast-dll" />
<Option type="3" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Option createStaticLib="1" />
<Compiler>
<Add option="-O3" />
<Add option="-W" />
<Add option="-Wall" />
<Add option="-ffast-math" />
<Add option="-Wno-unused-parameter" />
<Add option="-DWIN32" />
<Add option="-DNDEBUG" />
<Add option="-D_WINDOWS" />
<Add option="-D_USRDLL" />
<Add option="-DIRRLICHT_EXPORTS" />
<Add option="-D_CRT_SECURE_NO_DEPRECATE" />
<Add option="-D__GNUWIN32__" />
<Add directory="../../include" />
<Add directory="zlib" />
</Compiler>
<Linker>
<Add library="kernel32" />
<Add library="user32" />
<Add library="gdi32" />
<Add library="winspool" />
<Add library="comdlg32" />
<Add library="advapi32" />
<Add library="shell32" />
<Add library="ole32" />
<Add library="oleaut32" />
<Add library="uuid" />
<Add library="opengl32" />
<Add library="winmm" />
</Linker>
<ExtraCommands>
<Add after="cmd /c del ..\..\bin\Win32-gcc\Irrlicht.dll" />
<Add after="cmd /c move ..\..\lib\Win32-gcc\Irrlicht.dll ..\..\bin\Win32-gcc\Irrlicht.dll" />
</ExtraCommands>
</Target>
<Target title="Win32 - Debug - static">
<Option platforms="Windows;" />
<Option output="../../lib/Win32-gcc/libIrrlicht" prefix_auto="1" extension_auto="1" />
<Option working_dir="" />
<Option object_output="../obj/win32-gcc-debug-static" />
<Option type="2" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Compiler>
<Add option="-W" />
<Add option="-Wall" />
<Add option="-g" />
<Add option="-O0" />
<Add option="-Wextra" />
<Add option="-Wno-unused-parameter" />
<Add option="-DWIN32" />
<Add option="-D_DEBUG" />
<Add option="-D_WINDOWS" />
<Add option="-D_IRR_STATIC_LIB_" />
<Add option="-D_CRT_SECURE_NO_DEPRECATE" />
<Add option="-D__GNUWIN32__" />
<Add directory="../../include" />
<Add directory="zlib" />
</Compiler>
<Linker>
<Add library="kernel32" />
<Add library="user32" />
<Add library="gdi32" />
<Add library="winspool" />
<Add library="comdlg32" />
<Add library="advapi32" />
<Add library="shell32" />
<Add library="ole32" />
<Add library="oleaut32" />
<Add library="uuid" />
<Add library="opengl32" />
<Add library="winmm" />
</Linker>
</Target>
<Target title="Win32 - Release - accurate math - static">
<Option platforms="Windows;" />
<Option output="../../lib/Win32-gcc/libIrrlicht" prefix_auto="1" extension_auto="1" />
<Option working_dir="" />
<Option object_output="../obj/win32-gcc-release-dll" />
<Option type="2" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Compiler>
<Add option="-Os" />
<Add option="-O3" />
<Add option="-O2" />
<Add option="-W" />
<Add option="-Wall" />
<Add option="-Wno-unused-parameter" />
<Add option="-DWIN32" />
<Add option="-DNDEBUG" />
<Add option="-D_WINDOWS" />
<Add option="-DIRRLICHT_EXPORTS" />
<Add option="-D_CRT_SECURE_NO_DEPRECATE" />
<Add option="-D__GNUWIN32__" />
<Add directory="../../include" />
<Add directory="zlib" />
</Compiler>
<Linker>
<Add option="-s" />
<Add library="kernel32" />
<Add library="user32" />
<Add library="gdi32" />
<Add library="winspool" />
<Add library="comdlg32" />
<Add library="advapi32" />
<Add library="shell32" />
<Add library="ole32" />
<Add library="oleaut32" />
<Add library="uuid" />
<Add library="opengl32" />
<Add library="winmm" />
</Linker>
</Target>
<Target title="Win32 - Release - fast math - static">
<Option platforms="Windows;" />
<Option output="../../lib/Win32-gcc/libIrrlicht" prefix_auto="1" extension_auto="1" />
<Option working_dir="" />
<Option object_output="../obj/win32-gcc-release-fast-static" />
<Option type="2" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Compiler>
<Add option="-fexpensive-optimizations" />
<Add option="-Os" />
<Add option="-O3" />
<Add option="-W" />
<Add option="-Wall" />
<Add option="-ffast-math" />
<Add option="-Wno-unused-parameter" />
<Add option="-DWIN32" />
<Add option="-DNDEBUG" />
<Add option="-D_WINDOWS" />
<Add option="-D_IRR_STATIC_LIB_" />
<Add option="-D_CRT_SECURE_NO_DEPRECATE" />
<Add option="-D__GNUWIN32__" />
<Add directory="../../include" />
<Add directory="zlib" />
</Compiler>
<Linker>
<Add option="-s" />
<Add library="kernel32" />
<Add library="user32" />
<Add library="gdi32" />
<Add library="winspool" />
<Add library="comdlg32" />
<Add library="advapi32" />
<Add library="shell32" />
<Add library="ole32" />
<Add library="oleaut32" />
<Add library="uuid" />
<Add library="opengl32" />
<Add library="winmm" />
</Linker>
</Target>
<Target title="Linux - Debug - shared">
<Option platforms="Unix;" />
<Option output="../../lib/Linux/libIrrlicht" prefix_auto="0" extension_auto="1" />
<Option object_output="../obj/linux-gcc-debug-shared" />
<Option type="3" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Option createStaticLib="1" />
<Compiler>
<Add option="-W" />
<Add option="-Wall" />
<Add option="-g" />
<Add option="-O0" />
<Add option="-Wextra" />
<Add option="-Wno-unused-parameter" />
<Add option="-fPIC" />
<Add option="-D_DEBUG" />
<Add directory="../../include" />
<Add directory="zlib" />
<Add directory="libpng" />
<Add directory="jpeglib" />
</Compiler>
<Linker>
<Add library="GL" />
<Add library="Xxf86vm" />
<Add directory="/usr/X11R6/lib" />
<Add directory="/usr/local/lib" />
</Linker>
</Target>
<Target title="Linux - Release - accurate math - shared">
<Option platforms="Unix;" />
<Option output="../../lib/Linux/libIrrlicht" prefix_auto="0" extension_auto="1" />
<Option object_output="../obj/linux-gcc-release-shared" />
<Option type="3" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Option createStaticLib="1" />
<Compiler>
<Add option="-O3" />
<Add option="-W" />
<Add option="-Wextra" />
<Add option="-Wno-unused-parameter" />
<Add option="-fPIC" />
<Add directory="../../include" />
<Add directory="zlib" />
<Add directory="libpng" />
<Add directory="jpeglib" />
</Compiler>
<Linker>
<Add library="GL" />
<Add library="Xxf86vm" />
<Add directory="/usr/X11R6/lib" />
<Add directory="/usr/local/lib" />
</Linker>
</Target>
<Target title="Linux - Release - fast math - shared">
<Option platforms="Unix;" />
<Option output="../../lib/Linux/libIrrlicht" prefix_auto="0" extension_auto="1" />
<Option object_output="../obj/linux-gcc-release-fast-shared" />
<Option type="3" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Option createStaticLib="1" />
<Compiler>
<Add option="-O3" />
<Add option="-W" />
<Add option="-Wextra" />
<Add option="-Wno-unused-parameter" />
<Add option="-ffast-math" />
<Add directory="../../include" />
<Add directory="zlib" />
<Add directory="libpng" />
<Add directory="jpeglib" />
</Compiler>
<Linker>
<Add library="GL" />
<Add library="Xxf86vm" />
<Add directory="/usr/X11R6/lib" />
<Add directory="/usr/local/lib" />
</Linker>
</Target>
<Target title="Linux - Debug - static">
<Option platforms="Unix;" />
<Option output="../../lib/Linux/libIrrlicht" prefix_auto="0" extension_auto="1" />
<Option working_dir="" />
<Option object_output="../obj/linux-gcc-debug-shared" />
<Option type="2" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Compiler>
<Add option="-W" />
<Add option="-Wall" />
<Add option="-g" />
<Add option="-O0" />
<Add option="-Wextra" />
<Add option="-Wno-unused-parameter" />
<Add option="-fPIC" />
<Add option="-D_IRR_STATIC_LIB_" />
<Add option="-D_DEBUG" />
<Add directory="../../include" />
<Add directory="zlib" />
<Add directory="libpng" />
</Compiler>
<Linker>
<Add library="GL" />
<Add library="Xxf86vm" />
<Add directory="/usr/X11R6/lib" />
<Add directory="/usr/local/lib" />
</Linker>
</Target>
<Target title="Linux - Release - accurate math - static">
<Option platforms="Unix;" />
<Option output="../../lib/Linux/libIrrlicht" prefix_auto="0" extension_auto="1" />
<Option working_dir="" />
<Option object_output="../obj/linux-gcc-release-shared" />
<Option type="2" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Compiler>
<Add option="-O3" />
<Add option="-W" />
<Add option="-Wextra" />
<Add option="-Wno-unused-parameter" />
<Add option="-fPIC" />
<Add option="-D_IRR_STATIC_LIB_" />
<Add directory="../../include" />
<Add directory="zlib" />
<Add directory="libpng" />
</Compiler>
<Linker>
<Add library="GL" />
<Add library="Xxf86vm" />
<Add directory="/usr/X11R6/lib" />
<Add directory="/usr/local/lib" />
</Linker>
</Target>
<Target title="Linux - Release - fast math - static">
<Option platforms="Unix;" />
<Option output="../../lib/Linux/libIrrlicht" prefix_auto="0" extension_auto="1" />
<Option working_dir="" />
<Option object_output="../obj/linux-gcc-release-fast-shared" />
<Option type="2" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Compiler>
<Add option="-O3" />
<Add option="-W" />
<Add option="-Wextra" />
<Add option="-Wno-unused-parameter" />
<Add option="-ffast-math" />
<Add option="-fPIC" />
<Add option="-D_IRR_STATIC_LIB_" />
<Add directory="../../include" />
<Add directory="zlib" />
<Add directory="libpng" />
</Compiler>
<Linker>
<Add library="GL" />
<Add library="Xxf86vm" />
<Add directory="/usr/X11R6/lib" />
<Add directory="/usr/local/lib" />
</Linker>
</Target>
</Build>
<VirtualTargets>
<Add alias="All" targets="Win32 - Debug - dll;Win32 - Release - accurate math - dll;Win32 - Release - fast math - dll;" />
</VirtualTargets>
<Unit filename="../../changes.txt" />
<Unit filename="../../include/EAttributes.h" />
<Unit filename="../../include/ECullingTypes.h" />
<Unit filename="../../include/EDebugSceneTypes.h" />
<Unit filename="../../include/EDriverTypes.h" />
<Unit filename="../../include/EGUIElementTypes.h" />
<Unit filename="../../include/EMeshWriterEnums.h" />
<Unit filename="../../include/EMessageBoxFlags.h" />
<Unit filename="../../include/ESceneNodeAnimatorTypes.h" />
<Unit filename="../../include/ESceneNodeTypes.h" />
<Unit filename="../../include/IAnimatedMesh.h" />
<Unit filename="../../include/IAnimatedMeshMD2.h" />
<Unit filename="../../include/IAnimatedMeshSceneNode.h" />
<Unit filename="../../include/IAttributeExchangingObject.h" />
<Unit filename="../../include/IAttributes.h" />
<Unit filename="../../include/IBillboardSceneNode.h" />
<Unit filename="../../include/IBoneSceneNode.h" />
<Unit filename="../../include/ICameraSceneNode.h" />
<Unit filename="../../include/ICursorControl.h" />
<Unit filename="../../include/IDummyTransformationSceneNode.h" />
<Unit filename="../../include/IEventReceiver.h" />
<Unit filename="../../include/IFileArchive.h" />
<Unit filename="../../include/IFileList.h" />
<Unit filename="../../include/IFileSystem.h" />
<Unit filename="../../include/IGPUProgrammingServices.h" />
<Unit filename="../../include/IGUIButton.h" />
<Unit filename="../../include/IGUICheckBox.h" />
<Unit filename="../../include/IGUIComboBox.h" />
<Unit filename="../../include/IGUIContextMenu.h" />
<Unit filename="../../include/IGUIEditBox.h" />
<Unit filename="../../include/IGUIElement.h" />
<Unit filename="../../include/IGUIElementFactory.h" />
<Unit filename="../../include/IGUIEnvironment.h" />
<Unit filename="../../include/IGUIFileOpenDialog.h" />
<Unit filename="../../include/IGUIFont.h" />
<Unit filename="../../include/IGUIImage.h" />
<Unit filename="../../include/IGUIInOutFader.h" />
<Unit filename="../../include/IGUIListBox.h" />
<Unit filename="../../include/IGUIMeshViewer.h" />
<Unit filename="../../include/IGUIScrollBar.h" />
<Unit filename="../../include/IGUISkin.h" />
<Unit filename="../../include/IGUISpinBox.h" />
<Unit filename="../../include/IGUISpriteBank.h" />
<Unit filename="../../include/IGUIStaticText.h" />
<Unit filename="../../include/IGUITabControl.h" />
<Unit filename="../../include/IGUITable.h" />
<Unit filename="../../include/IGUIToolbar.h" />
<Unit filename="../../include/IGUIWindow.h" />
<Unit filename="../../include/IGeometryCreator.h" />
<Unit filename="../../include/IImage.h" />
<Unit filename="../../include/IImageLoader.h" />
<Unit filename="../../include/ILightSceneNode.h" />
<Unit filename="../../include/ILogger.h" />
<Unit filename="../../include/IMaterialRenderer.h" />
<Unit filename="../../include/IMaterialRendererServices.h" />
<Unit filename="../../include/IMesh.h" />
<Unit filename="../../include/IMeshBuffer.h" />
<Unit filename="../../include/IMeshCache.h" />
<Unit filename="../../include/IMeshLoader.h" />
<Unit filename="../../include/IMeshManipulator.h" />
<Unit filename="../../include/IMeshSceneNode.h" />
<Unit filename="../../include/IMeshWriter.h" />
<Unit filename="../../include/IMetaTriangleSelector.h" />
<Unit filename="../../include/IOSOperator.h" />
<Unit filename="../../include/IParticleAffector.h" />
<Unit filename="../../include/IParticleEmitter.h" />
<Unit filename="../../include/IParticleSystemSceneNode.h" />
<Unit filename="../../include/IQ3LevelMesh.h" />
<Unit filename="../../include/IReadFile.h" />
<Unit filename="../../include/IReferenceCounted.h" />
<Unit filename="../../include/ISceneCollisionManager.h" />
<Unit filename="../../include/ISceneManager.h" />
<Unit filename="../../include/ISceneNode.h" />
<Unit filename="../../include/ISceneNodeAnimator.h" />
<Unit filename="../../include/ISceneNodeAnimatorCameraFPS.h" />
<Unit filename="../../include/ISceneNodeAnimatorCameraMaya.h" />
<Unit filename="../../include/ISceneNodeAnimatorCollisionResponse.h" />
<Unit filename="../../include/ISceneNodeAnimatorFactory.h" />
<Unit filename="../../include/ISceneNodeFactory.h" />
<Unit filename="../../include/IShaderConstantSetCallBack.h" />
<Unit filename="../../include/IShadowVolumeSceneNode.h" />
<Unit filename="../../include/ISkinnedMesh.h" />
<Unit filename="../../include/ITerrainSceneNode.h" />
<Unit filename="../../include/ITextSceneNode.h" />
<Unit filename="../../include/ITexture.h" />
<Unit filename="../../include/ITimer.h" />
<Unit filename="../../include/ITriangleSelector.h" />
<Unit filename="../../include/IVideoDriver.h" />
<Unit filename="../../include/IVideoModeList.h" />
<Unit filename="../../include/IVolumeLightSceneNode.h" />
<Unit filename="../../include/IWriteFile.h" />
<Unit filename="../../include/IXMLReader.h" />
<Unit filename="../../include/IXMLWriter.h" />
<Unit filename="../../include/IrrCompileConfig.h" />
<Unit filename="../../include/IrrlichtDevice.h" />
<Unit filename="../../include/Keycodes.h" />
<Unit filename="../../include/S3DVertex.h" />
<Unit filename="../../include/SAnimatedMesh.h" />
<Unit filename="../../include/SColor.h" />
<Unit filename="../../include/SExposedVideoData.h" />
<Unit filename="../../include/SIrrCreationParameters.h" />
<Unit filename="../../include/SKeyMap.h" />
<Unit filename="../../include/SLight.h" />
<Unit filename="../../include/SMaterial.h" />
<Unit filename="../../include/SMesh.h" />
<Unit filename="../../include/SMeshBuffer.h" />
<Unit filename="../../include/SMeshBufferLightMap.h" />
<Unit filename="../../include/SMeshBufferTangents.h" />
<Unit filename="../../include/SParticle.h" />
<Unit filename="../../include/SSkinMeshBuffer.h" />
+ <Unit filename="../../include/SVertexManipulator.h" />
<Unit filename="../../include/SViewFrustum.h" />
<Unit filename="../../include/SceneParameters.h" />
<Unit filename="../../include/aabbox3d.h" />
<Unit filename="../../include/dimension2d.h" />
<Unit filename="../../include/heapsort.h" />
<Unit filename="../../include/irrAllocator.h" />
<Unit filename="../../include/irrArray.h" />
<Unit filename="../../include/irrList.h" />
<Unit filename="../../include/irrMap.h" />
<Unit filename="../../include/irrMath.h" />
<Unit filename="../../include/irrString.h" />
<Unit filename="../../include/irrTypes.h" />
<Unit filename="../../include/irrXML.h" />
<Unit filename="../../include/irrlicht.h" />
<Unit filename="../../include/line2d.h" />
<Unit filename="../../include/line3d.h" />
<Unit filename="../../include/matrix4.h" />
<Unit filename="../../include/path.h" />
<Unit filename="../../include/plane3d.h" />
<Unit filename="../../include/position2d.h" />
<Unit filename="../../include/quaternion.h" />
<Unit filename="../../include/rect.h" />
<Unit filename="../../include/triangle3d.h" />
<Unit filename="../../include/vector2d.h" />
<Unit filename="../../include/vector3d.h" />
<Unit filename="../../readme.txt" />
<Unit filename="BuiltInFont.h" />
<Unit filename="C3DSMeshFileLoader.cpp" />
<Unit filename="C3DSMeshFileLoader.h" />
<Unit filename="CAnimatedMeshMD2.cpp" />
<Unit filename="CAnimatedMeshMD2.h" />
<Unit filename="CAnimatedMeshMD3.cpp" />
<Unit filename="CAnimatedMeshMD3.h" />
<Unit filename="CAnimatedMeshSceneNode.cpp" />
<Unit filename="CAnimatedMeshSceneNode.h" />
<Unit filename="CAttributeImpl.h" />
<Unit filename="CAttributes.cpp" />
<Unit filename="CAttributes.h" />
<Unit filename="CB3DMeshFileLoader.cpp" />
<Unit filename="CB3DMeshFileLoader.h" />
<Unit filename="CBSPMeshFileLoader.cpp" />
<Unit filename="CBSPMeshFileLoader.h" />
<Unit filename="CBillboardSceneNode.cpp" />
<Unit filename="CBillboardSceneNode.h" />
<Unit filename="CBoneSceneNode.cpp" />
<Unit filename="CBoneSceneNode.h" />
<Unit filename="CBurningShader_Raster_Reference.cpp" />
<Unit filename="CCSMLoader.cpp" />
<Unit filename="CCSMLoader.h" />
<Unit filename="CCameraSceneNode.cpp" />
<Unit filename="CCameraSceneNode.h" />
<Unit filename="CColladaFileLoader.cpp" />
<Unit filename="CColladaFileLoader.h" />
<Unit filename="CColladaMeshWriter.cpp" />
<Unit filename="CColladaMeshWriter.h" />
<Unit filename="CColorConverter.cpp" />
<Unit filename="CColorConverter.h" />
<Unit filename="CCubeSceneNode.cpp" />
<Unit filename="CCubeSceneNode.h" />
<Unit filename="CD3D8Driver.cpp" />
<Unit filename="CD3D8Driver.h" />
<Unit filename="CD3D8MaterialRenderer.h" />
<Unit filename="CD3D8NormalMapRenderer.cpp" />
<Unit filename="CD3D8NormalMapRenderer.h" />
<Unit filename="CD3D8ParallaxMapRenderer.cpp" />
<Unit filename="CD3D8ParallaxMapRenderer.h" />
<Unit filename="CD3D8ShaderMaterialRenderer.cpp" />
<Unit filename="CD3D8ShaderMaterialRenderer.h" />
<Unit filename="CD3D8Texture.cpp" />
<Unit filename="CD3D8Texture.h" />
<Unit filename="CD3D9Driver.cpp" />
<Unit filename="CD3D9Driver.h" />
<Unit filename="CD3D9HLSLMaterialRenderer.cpp" />
<Unit filename="CD3D9HLSLMaterialRenderer.h" />
<Unit filename="CD3D9MaterialRenderer.h" />
<Unit filename="CD3D9NormalMapRenderer.cpp" />
<Unit filename="CD3D9NormalMapRenderer.h" />
<Unit filename="CD3D9ParallaxMapRenderer.cpp" />
<Unit filename="CD3D9ParallaxMapRenderer.h" />
<Unit filename="CD3D9ShaderMaterialRenderer.cpp" />
<Unit filename="CD3D9ShaderMaterialRenderer.h" />
<Unit filename="CD3D9Texture.cpp" />
<Unit filename="CD3D9Texture.h" />
<Unit filename="CDMFLoader.cpp" />
<Unit filename="CDMFLoader.h" />
<Unit filename="CDefaultGUIElementFactory.cpp" />
<Unit filename="CDefaultGUIElementFactory.h" />
<Unit filename="CDefaultSceneNodeAnimatorFactory.cpp" />
<Unit filename="CDefaultSceneNodeAnimatorFactory.h" />
<Unit filename="CDefaultSceneNodeFactory.cpp" />
<Unit filename="CDefaultSceneNodeFactory.h" />
<Unit filename="CDepthBuffer.cpp" />
<Unit filename="CDepthBuffer.h" />
<Unit filename="CDummyTransformationSceneNode.cpp" />
<Unit filename="CDummyTransformationSceneNode.h" />
<Unit filename="CEmptySceneNode.cpp" />
<Unit filename="CEmptySceneNode.h" />
<Unit filename="CFPSCounter.cpp" />
<Unit filename="CFPSCounter.h" />
<Unit filename="CFileList.cpp" />
<Unit filename="CFileList.h" />
<Unit filename="CFileSystem.cpp" />
<Unit filename="CFileSystem.h" />
<Unit filename="CGUIButton.cpp" />
<Unit filename="CGUIButton.h" />
<Unit filename="CGUICheckBox.cpp" />
<Unit filename="CGUICheckbox.h" />
<Unit filename="CGUIColorSelectDialog.cpp" />
<Unit filename="CGUIColorSelectDialog.h" />
<Unit filename="CGUIComboBox.cpp" />
<Unit filename="CGUIComboBox.h" />
<Unit filename="CGUIContextMenu.cpp" />
<Unit filename="CGUIContextMenu.h" />
<Unit filename="CGUIEditBox.cpp" />
<Unit filename="CGUIEditBox.h" />
<Unit filename="CGUIEnvironment.cpp" />
<Unit filename="CGUIEnvironment.h" />
<Unit filename="CGUIFileOpenDialog.cpp" />
<Unit filename="CGUIFileOpenDialog.h" />
<Unit filename="CGUIFont.cpp" />
<Unit filename="CGUIFont.h" />
<Unit filename="CGUIImage.cpp" />
<Unit filename="CGUIImage.h" />
<Unit filename="CGUIImageList.cpp" />
<Unit filename="CGUIImageList.h" />
<Unit filename="CGUIInOutFader.cpp" />
<Unit filename="CGUIInOutFader.h" />
<Unit filename="CGUIListBox.cpp" />
<Unit filename="CGUIListBox.h" />
<Unit filename="CGUIMenu.cpp" />
<Unit filename="CGUIMenu.h" />
<Unit filename="CGUIMeshViewer.cpp" />
<Unit filename="CGUIMeshViewer.h" />
<Unit filename="CGUIMessageBox.cpp" />
<Unit filename="CGUIMessageBox.h" />
<Unit filename="CGUIModalScreen.cpp" />
<Unit filename="CGUIModalScreen.h" />
<Unit filename="CGUIScrollBar.cpp" />
<Unit filename="CGUIScrollBar.h" />
<Unit filename="CGUISkin.cpp" />
<Unit filename="CGUISkin.h" />
<Unit filename="CGUISpinBox.cpp" />
<Unit filename="CGUISpinBox.h" />
<Unit filename="CGUISpriteBank.cpp" />
<Unit filename="CGUISpriteBank.h" />
<Unit filename="CGUIStaticText.cpp" />
<Unit filename="CGUIStaticText.h" />
<Unit filename="CGUITabControl.cpp" />
<Unit filename="CGUITabControl.h" />
<Unit filename="CGUITable.cpp" />
<Unit filename="CGUITable.h" />
<Unit filename="CGUIToolBar.cpp" />
<Unit filename="CGUIToolBar.h" />
<Unit filename="CGUITreeView.cpp" />
<Unit filename="CGUITreeView.h" />
<Unit filename="CGUIWindow.cpp" />
<Unit filename="CGUIWindow.h" />
<Unit filename="CGeometryCreator.cpp" />
<Unit filename="CGeometryCreator.h" />
<Unit filename="CImage.cpp" />
<Unit filename="CImage.h" />
<Unit filename="CImageLoaderBMP.cpp" />
<Unit filename="CImageLoaderBMP.h" />
<Unit filename="CImageLoaderJPG.cpp" />
<Unit filename="CImageLoaderJPG.h" />
<Unit filename="CImageLoaderPCX.cpp" />
<Unit filename="CImageLoaderPCX.h" />
<Unit filename="CImageLoaderPNG.cpp" />
<Unit filename="CImageLoaderPNG.h" />
<Unit filename="CImageLoaderPPM.cpp" />
<Unit filename="CImageLoaderPPM.h" />
<Unit filename="CImageLoaderPSD.cpp" />
<Unit filename="CImageLoaderPSD.h" />
<Unit filename="CImageLoaderRGB.cpp" />
<Unit filename="CImageLoaderRGB.h" />
<Unit filename="CImageLoaderTGA.cpp" />
<Unit filename="CImageLoaderTGA.h" />
<Unit filename="CImageLoaderWAL.cpp" />
<Unit filename="CImageLoaderWAL.h" />
<Unit filename="CImageWriterBMP.cpp" />
<Unit filename="CImageWriterBMP.h" />
<Unit filename="CImageWriterJPG.cpp" />
<Unit filename="CImageWriterJPG.h" />
<Unit filename="CImageWriterPCX.cpp" />
<Unit filename="CImageWriterPCX.h" />
<Unit filename="CImageWriterPNG.cpp" />
<Unit filename="CImageWriterPNG.h" />
<Unit filename="CImageWriterPPM.cpp" />
<Unit filename="CImageWriterPPM.h" />
<Unit filename="CImageWriterPSD.cpp" />
<Unit filename="CImageWriterPSD.h" />
<Unit filename="CImageWriterTGA.cpp" />
<Unit filename="CImageWriterTGA.h" />
<Unit filename="CIrrDeviceConsole.cpp" />
<Unit filename="CIrrDeviceConsole.h" />
<Unit filename="CIrrDeviceLinux.cpp" />
<Unit filename="CIrrDeviceLinux.h" />
<Unit filename="CIrrDeviceSDL.cpp" />
<Unit filename="CIrrDeviceSDL.h" />
<Unit filename="CIrrDeviceStub.cpp" />
<Unit filename="CIrrDeviceStub.h" />
<Unit filename="CIrrDeviceWin32.cpp" />
<Unit filename="CIrrDeviceWin32.h" />
<Unit filename="CIrrDeviceWinCE.cpp" />
<Unit filename="CIrrDeviceWinCE.h" />
<Unit filename="CIrrMeshFileLoader.cpp" />
<Unit filename="CIrrMeshFileLoader.h" />
<Unit filename="CIrrMeshWriter.cpp" />
<Unit filename="CIrrMeshWriter.h" />
<Unit filename="CLMTSMeshFileLoader.cpp" />
<Unit filename="CLMTSMeshFileLoader.h" />
<Unit filename="CLWOMeshFileLoader.cpp" />
<Unit filename="CLWOMeshFileLoader.h" />
<Unit filename="CLightSceneNode.cpp" />
<Unit filename="CLightSceneNode.h" />
<Unit filename="CLimitReadFile.cpp" />
<Unit filename="CLimitReadFile.h" />
<Unit filename="CLogger.cpp" />
<Unit filename="CLogger.h" />
<Unit filename="CMD2MeshFileLoader.cpp" />
<Unit filename="CMD2MeshFileLoader.h" />
<Unit filename="CMD3MeshFileLoader.cpp" />
<Unit filename="CMD3MeshFileLoader.h" />
<Unit filename="CMS3DMeshFileLoader.cpp" />
<Unit filename="CMS3DMeshFileLoader.h" />
<Unit filename="CMY3DHelper.h" />
<Unit filename="CMY3DMeshFileLoader.cpp" />
<Unit filename="CMY3DMeshFileLoader.h" />
<Unit filename="CMemoryFile.cpp" />
<Unit filename="CMemoryFile.h" />
<Unit filename="CMeshCache.cpp" />
<Unit filename="CMeshCache.h" />
<Unit filename="CMeshManipulator.cpp" />
<Unit filename="CMeshManipulator.h" />
<Unit filename="CMeshSceneNode.cpp" />
<Unit filename="CMeshSceneNode.h" />
<Unit filename="CMetaTriangleSelector.cpp" />
<Unit filename="CMetaTriangleSelector.h" />
<Unit filename="CMountPointReader.cpp" />
<Unit filename="CMountPointReader.h" />
<Unit filename="CNPKReader.cpp" />
<Unit filename="CNPKReader.h" />
<Unit filename="CNullDriver.cpp" />
<Unit filename="CNullDriver.h" />
<Unit filename="COBJMeshFileLoader.cpp" />
<Unit filename="COBJMeshFileLoader.h" />
<Unit filename="COBJMeshWriter.cpp" />
<Unit filename="COBJMeshWriter.h" />
<Unit filename="COCTLoader.cpp" />
<Unit filename="COCTLoader.h" />
<Unit filename="COSOperator.cpp" />
<Unit filename="COSOperator.h" />
<Unit filename="COctreeSceneNode.cpp" />
<Unit filename="COctreeSceneNode.h" />
<Unit filename="COctreeTriangleSelector.cpp" />
<Unit filename="COctreeTriangleSelector.h" />
<Unit filename="COgreMeshFileLoader.cpp" />
<Unit filename="COgreMeshFileLoader.h" />
<Unit filename="COpenGLDriver.cpp" />
<Unit filename="COpenGLDriver.h" />
<Unit filename="COpenGLExtensionHandler.cpp" />
<Unit filename="COpenGLExtensionHandler.h" />
<Unit filename="COpenGLMaterialRenderer.h" />
<Unit filename="COpenGLNormalMapRenderer.cpp" />
<Unit filename="COpenGLNormalMapRenderer.h" />
<Unit filename="COpenGLParallaxMapRenderer.cpp" />
<Unit filename="COpenGLParallaxMapRenderer.h" />
<Unit filename="COpenGLSLMaterialRenderer.cpp" />
<Unit filename="COpenGLSLMaterialRenderer.h" />
<Unit filename="COpenGLShaderMaterialRenderer.cpp" />
<Unit filename="COpenGLShaderMaterialRenderer.h" />
<Unit filename="COpenGLTexture.cpp" />
<Unit filename="COpenGLTexture.h" />
<Unit filename="CPLYMeshFileLoader.cpp" />
<Unit filename="CPLYMeshFileLoader.h" />
<Unit filename="CPLYMeshWriter.cpp" />
<Unit filename="CPLYMeshWriter.h" />
<Unit filename="CPakReader.cpp" />
<Unit filename="CPakReader.h" />
<Unit filename="CParticleAnimatedMeshSceneNodeEmitter.cpp" />
<Unit filename="CParticleAttractionAffector.cpp" />
<Unit filename="CParticleBoxEmitter.cpp" />
<Unit filename="CParticleBoxEmitter.h" />
<Unit filename="CParticleCylinderEmitter.cpp" />
<Unit filename="CParticleFadeOutAffector.cpp" />
<Unit filename="CParticleFadeOutAffector.h" />
<Unit filename="CParticleGravityAffector.cpp" />
<Unit filename="CParticleGravityAffector.h" />
<Unit filename="CParticleMeshEmitter.cpp" />
<Unit filename="CParticlePointEmitter.cpp" />
<Unit filename="CParticlePointEmitter.h" />
<Unit filename="CParticleRingEmitter.cpp" />
<Unit filename="CParticleRotationAffector.cpp" />
<Unit filename="CParticleScaleAffector.cpp" />
<Unit filename="CParticleScaleAffector.h" />
<Unit filename="CParticleSphereEmitter.cpp" />
<Unit filename="CParticleSystemSceneNode.cpp" />
<Unit filename="CParticleSystemSceneNode.h" />
<Unit filename="CQ3LevelMesh.cpp" />
<Unit filename="CQ3LevelMesh.h" />
<Unit filename="CQuake3ShaderSceneNode.cpp" />
<Unit filename="CQuake3ShaderSceneNode.h" />
<Unit filename="CReadFile.cpp" />
<Unit filename="CReadFile.h" />
<Unit filename="CSTLMeshFileLoader.cpp" />
<Unit filename="CSTLMeshFileLoader.h" />
<Unit filename="CSTLMeshWriter.cpp" />
<Unit filename="CSTLMeshWriter.h" />
<Unit filename="CSceneCollisionManager.cpp" />
<Unit filename="CSceneCollisionManager.h" />
<Unit filename="CSceneManager.cpp" />
<Unit filename="CSceneManager.h" />
<Unit filename="CSceneNodeAnimatorCameraFPS.cpp" />
<Unit filename="CSceneNodeAnimatorCameraFPS.h" />
<Unit filename="CSceneNodeAnimatorCameraMaya.cpp" />
<Unit filename="CSceneNodeAnimatorCameraMaya.h" />
<Unit filename="CSceneNodeAnimatorCollisionResponse.cpp" />
<Unit filename="CSceneNodeAnimatorCollisionResponse.h" />
<Unit filename="CSceneNodeAnimatorDelete.cpp" />
<Unit filename="CSceneNodeAnimatorDelete.h" />
<Unit filename="CSceneNodeAnimatorFlyCircle.cpp" />
<Unit filename="CSceneNodeAnimatorFlyCircle.h" />
<Unit filename="CSceneNodeAnimatorFlyStraight.cpp" />
<Unit filename="CSceneNodeAnimatorFlyStraight.h" />
<Unit filename="CSceneNodeAnimatorFollowSpline.cpp" />
<Unit filename="CSceneNodeAnimatorFollowSpline.h" />
<Unit filename="CSceneNodeAnimatorRotation.cpp" />
<Unit filename="CSceneNodeAnimatorRotation.h" />
<Unit filename="CSceneNodeAnimatorTexture.cpp" />
<Unit filename="CSceneNodeAnimatorTexture.h" />
<Unit filename="CShadowVolumeSceneNode.cpp" />
<Unit filename="CShadowVolumeSceneNode.h" />
<Unit filename="CSkinnedMesh.cpp" />
<Unit filename="CSkinnedMesh.h" />
<Unit filename="CSkyBoxSceneNode.cpp" />
<Unit filename="CSkyBoxSceneNode.h" />
<Unit filename="CSkyDomeSceneNode.cpp" />
<Unit filename="CSkyDomeSceneNode.h" />
<Unit filename="CSoftware2MaterialRenderer.h" />
<Unit filename="CSoftwareDriver.cpp" />
<Unit filename="CSoftwareDriver.h" />
<Unit filename="CSoftwareDriver2.cpp" />
<Unit filename="CSoftwareDriver2.h" />
<Unit filename="CSoftwareTexture.cpp" />
<Unit filename="CSoftwareTexture.h" />
<Unit filename="CSoftwareTexture2.cpp" />
<Unit filename="CSoftwareTexture2.h" />
<Unit filename="CSphereSceneNode.cpp" />
<Unit filename="CSphereSceneNode.h" />
<Unit filename="CTRFlat.cpp" />
<Unit filename="CTRFlatWire.cpp" />
<Unit filename="CTRGouraud.cpp" />
<Unit filename="CTRGouraud2.cpp" />
<Unit filename="CTRGouraudAlpha2.cpp" />
<Unit filename="CTRGouraudAlphaNoZ2.cpp" />
<Unit filename="CTRGouraudWire.cpp" />
<Unit filename="CTRTextureBlend.cpp" />
<Unit filename="CTRTextureDetailMap2.cpp" />
<Unit filename="CTRTextureFlat.cpp" />
<Unit filename="CTRTextureFlatWire.cpp" />
<Unit filename="CTRTextureGouraud.cpp" />
<Unit filename="CTRTextureGouraud.h" />
<Unit filename="CTRTextureGouraud2.cpp" />
<Unit filename="CTRTextureGouraudAdd.cpp" />
<Unit filename="CTRTextureGouraudAdd2.cpp" />
<Unit filename="CTRTextureGouraudAddNoZ2.cpp" />
<Unit filename="CTRTextureGouraudAlpha.cpp" />
<Unit filename="CTRTextureGouraudAlphaNoZ.cpp" />
<Unit filename="CTRTextureGouraudNoZ.cpp" />
<Unit filename="CTRTextureGouraudNoZ2.cpp" />
<Unit filename="CTRTextureGouraudVertexAlpha2.cpp" />
<Unit filename="CTRTextureGouraudWire.cpp" />
<Unit filename="CTRTextureLightMap2_Add.cpp" />
<Unit filename="CTRTextureLightMap2_M1.cpp" />
<Unit filename="CTRTextureLightMap2_M2.cpp" />
<Unit filename="CTRTextureLightMap2_M4.cpp" />
<Unit filename="CTRTextureLightMapGouraud2_M4.cpp" />
<Unit filename="CTRTextureWire2.cpp" />
<Unit filename="CTarReader.cpp" />
<Unit filename="CTarReader.h" />
<Unit filename="CTerrainSceneNode.cpp" />
<Unit filename="CTerrainSceneNode.h" />
<Unit filename="CTerrainTriangleSelector.cpp" />
<Unit filename="CTerrainTriangleSelector.h" />
<Unit filename="CTextSceneNode.cpp" />
<Unit filename="CTextSceneNode.h" />
<Unit filename="CTimer.h" />
<Unit filename="CTriangleBBSelector.cpp" />
<Unit filename="CTriangleBBSelector.h" />
<Unit filename="CTriangleSelector.cpp" />
<Unit filename="CTriangleSelector.h" />
<Unit filename="CVideoModeList.cpp" />
<Unit filename="CVideoModeList.h" />
<Unit filename="CVolumeLightSceneNode.cpp" />
<Unit filename="CVolumeLightSceneNode.h" />
<Unit filename="CWaterSurfaceSceneNode.cpp" />
<Unit filename="CWaterSurfaceSceneNode.h" />
<Unit filename="CWriteFile.cpp" />
<Unit filename="CWriteFile.h" />
<Unit filename="CXMLReader.cpp" />
<Unit filename="CXMLReader.h" />
<Unit filename="CXMLReaderImpl.h" />
<Unit filename="CXMLWriter.cpp" />
<Unit filename="CXMLWriter.h" />
<Unit filename="CXMeshFileLoader.cpp" />
<Unit filename="CXMeshFileLoader.h" />
<Unit filename="CZBuffer.cpp" />
<Unit filename="CZBuffer.h" />
<Unit filename="CZipReader.cpp" />
<Unit filename="CZipReader.h" />
<Unit filename="IAttribute.h" />
<Unit filename="IBurningShader.cpp" />
<Unit filename="IBurningShader.h" />
<Unit filename="IDepthBuffer.h" />
<Unit filename="IImagePresenter.h" />
<Unit filename="ITriangleRenderer.h" />
<Unit filename="IZBuffer.h" />
<Unit filename="Irrlicht.cpp" />
<Unit filename="MacOSX/CIrrDeviceMacOSX.h" />
<Unit filename="MacOSX/CIrrDeviceMacOSX.mm" />
<Unit filename="Octree.h" />
<Unit filename="S2DVertex.h" />
<Unit filename="S4DVertex.h" />
<Unit filename="SoftwareDriver2_compile_config.h" />
<Unit filename="SoftwareDriver2_helper.h" />
<Unit filename="aesGladman/aes.h" />
<Unit filename="aesGladman/aescrypt.cpp" />
<Unit filename="aesGladman/aeskey.cpp" />
<Unit filename="aesGladman/aesopt.h" />
<Unit filename="aesGladman/aestab.cpp" />
<Unit filename="aesGladman/fileenc.cpp" />
<Unit filename="aesGladman/fileenc.h" />
<Unit filename="aesGladman/hmac.cpp" />
<Unit filename="aesGladman/hmac.h" />
<Unit filename="aesGladman/prng.cpp" />
<Unit filename="aesGladman/prng.h" />
<Unit filename="aesGladman/pwd2key.cpp" />
<Unit filename="aesGladman/pwd2key.h" />
<Unit filename="aesGladman/sha1.cpp" />
<Unit filename="aesGladman/sha1.h" />
<Unit filename="aesGladman/sha2.cpp" />
<Unit filename="aesGladman/sha2.h" />
<Unit filename="bzip2/blocksort.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="bzip2/bzcompress.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="bzip2/bzlib.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="bzip2/bzlib.h" />
<Unit filename="bzip2/bzlib_private.h" />
<Unit filename="bzip2/crctable.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="bzip2/decompress.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="bzip2/huffman.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="bzip2/randtable.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="dmfsupport.h" />
<Unit filename="glext.h" />
<Unit filename="irrXML.cpp" />
<Unit filename="jpeglib/cderror.h" />
<Unit filename="jpeglib/jaricom.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="jpeglib/jcapimin.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="jpeglib/jcapistd.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="jpeglib/jcarith.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="jpeglib/jccoefct.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="jpeglib/jccolor.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="jpeglib/jcdctmgr.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="jpeglib/jchuff.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="jpeglib/jchuff.h" />
<Unit filename="jpeglib/jcinit.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="jpeglib/jcmainct.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="jpeglib/jcmarker.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="jpeglib/jcmaster.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="jpeglib/jcomapi.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="jpeglib/jconfig.h" />
<Unit filename="jpeglib/jcparam.c">
<Option compilerVar="CC" />
diff --git a/tests/tests-last-passed-at.txt b/tests/tests-last-passed-at.txt
index 242ffd4..71b990b 100644
--- a/tests/tests-last-passed-at.txt
+++ b/tests/tests-last-passed-at.txt
@@ -1,4 +1,4 @@
Tests finished. 51 tests of 51 passed.
Compiled as DEBUG
-Test suite pass at GMT Sat Mar 6 17:06:39 2010
+Test suite pass at GMT Mon Mar 8 13:04:19 2010
|
paupawsan/Irrlicht
|
45a70bcb6acef09675d0f6e12d63f962c2daeb76
|
Add the improved Windows version detection rules from brferreira (see http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=37579&highlight=) Fix compiling on Visual Studio which got broken by Borland fixes (seems to work now on all compilers).
|
diff --git a/source/Irrlicht/CD3D9Driver.h b/source/Irrlicht/CD3D9Driver.h
index 7b6b12c..ccc7e7f 100644
--- a/source/Irrlicht/CD3D9Driver.h
+++ b/source/Irrlicht/CD3D9Driver.h
@@ -1,446 +1,448 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_VIDEO_DIRECTX_9_H_INCLUDED__
#define __C_VIDEO_DIRECTX_9_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
#ifdef _IRR_WINDOWS_
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include "CNullDriver.h"
#include "IMaterialRendererServices.h"
+#if defined(__BORLANDC__) || defined (__BCPLUSPLUS__)
#include "irrMath.h" // needed by borland for sqrtf define
+#endif
#include <d3d9.h>
namespace irr
{
namespace video
{
struct SDepthSurface : public IReferenceCounted
{
SDepthSurface() : Surface(0)
{
#ifdef _DEBUG
setDebugName("SDepthSurface");
#endif
}
virtual ~SDepthSurface()
{
if (Surface)
Surface->Release();
}
IDirect3DSurface9* Surface;
core::dimension2du Size;
};
class CD3D9Driver : public CNullDriver, IMaterialRendererServices
{
public:
friend class CD3D9Texture;
//! constructor
CD3D9Driver(const core::dimension2d<u32>& screenSize, HWND window, bool fullscreen,
bool stencibuffer, io::IFileSystem* io, bool pureSoftware=false);
//! destructor
virtual ~CD3D9Driver();
//! applications must call this method before performing any rendering. returns false if failed.
virtual bool beginScene(bool backBuffer=true, bool zBuffer=true,
SColor color=SColor(255,0,0,0),
const SExposedVideoData& videoData=SExposedVideoData(),
core::rect<s32>* sourceRect=0);
//! applications must call this method after performing any rendering. returns false if failed.
virtual bool endScene();
//! queries the features of the driver, returns true if feature is available
virtual bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const;
//! sets transformation
virtual void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat);
//! sets a material
virtual void setMaterial(const SMaterial& material);
//! sets a render target
virtual bool setRenderTarget(video::ITexture* texture,
bool clearBackBuffer=true, bool clearZBuffer=true,
SColor color=video::SColor(0,0,0,0));
//! Sets multiple render targets
virtual bool setRenderTarget(const core::array<video::IRenderTarget>& texture,
bool clearBackBuffer=true, bool clearZBuffer=true,
SColor color=video::SColor(0,0,0,0));
//! sets a viewport
virtual void setViewPort(const core::rect<s32>& area);
//! gets the area of the current viewport
virtual const core::rect<s32>& getViewPort() const;
struct SHWBufferLink_d3d9 : public SHWBufferLink
{
SHWBufferLink_d3d9(const scene::IMeshBuffer *_MeshBuffer):
SHWBufferLink(_MeshBuffer),
vertexBuffer(0), indexBuffer(0),
vertexBufferSize(0), indexBufferSize(0) {}
IDirect3DVertexBuffer9* vertexBuffer;
IDirect3DIndexBuffer9* indexBuffer;
u32 vertexBufferSize;
u32 indexBufferSize;
};
bool updateVertexHardwareBuffer(SHWBufferLink_d3d9 *HWBuffer);
bool updateIndexHardwareBuffer(SHWBufferLink_d3d9 *HWBuffer);
//! updates hardware buffer if needed
virtual bool updateHardwareBuffer(SHWBufferLink *HWBuffer);
//! Create hardware buffer from mesh
virtual SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer* mb);
//! Delete hardware buffer (only some drivers can)
virtual void deleteHardwareBuffer(SHWBufferLink *HWBuffer);
//! Draw hardware buffer
virtual void drawHardwareBuffer(SHWBufferLink *HWBuffer);
//! draws a vertex primitive list
virtual void drawVertexPrimitiveList(const void* vertices, u32 vertexCount,
const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType,
E_INDEX_TYPE iType);
//! draws a vertex primitive list in 2d
virtual void draw2DVertexPrimitiveList(const void* vertices, u32 vertexCount,
const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType,
E_INDEX_TYPE iType);
//! draws an 2d image, using a color (if color is other then Color(255,255,255,255)) and the alpha channel of the texture if wanted.
virtual void draw2DImage(const video::ITexture* texture, const core::position2d<s32>& destPos,
const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect = 0,
SColor color=SColor(255,255,255,255), bool useAlphaChannelOfTexture=false);
//! Draws a part of the texture into the rectangle.
virtual void draw2DImage(const video::ITexture* texture, const core::rect<s32>& destRect,
const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect = 0,
const video::SColor* const colors=0, bool useAlphaChannelOfTexture=false);
//! Draws a set of 2d images, using a color and the alpha channel of the texture.
virtual void draw2DImageBatch(const video::ITexture* texture,
const core::array<core::position2d<s32> >& positions,
const core::array<core::rect<s32> >& sourceRects,
const core::rect<s32>* clipRect=0,
SColor color=SColor(255,255,255,255),
bool useAlphaChannelOfTexture=false);
//!Draws an 2d rectangle with a gradient.
virtual void draw2DRectangle(const core::rect<s32>& pos,
SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown,
const core::rect<s32>* clip);
//! Draws a 2d line.
virtual void draw2DLine(const core::position2d<s32>& start,
const core::position2d<s32>& end,
SColor color=SColor(255,255,255,255));
//! Draws a pixel.
virtual void drawPixel(u32 x, u32 y, const SColor & color);
//! Draws a 3d line.
virtual void draw3DLine(const core::vector3df& start,
const core::vector3df& end, SColor color = SColor(255,255,255,255));
//! initialises the Direct3D API
bool initDriver(const core::dimension2d<u32>& screenSize, HWND hwnd,
u32 bits, bool fullScreen, bool pureSoftware,
bool highPrecisionFPU, bool vsync, u8 antiAlias);
//! \return Returns the name of the video driver. Example: In case of the DIRECT3D8
//! driver, it would return "Direct3D8.1".
virtual const wchar_t* getName() const;
//! deletes all dynamic lights there are
virtual void deleteAllDynamicLights();
//! adds a dynamic light, returning an index to the light
//! \param light: the light data to use to create the light
//! \return An index to the light, or -1 if an error occurs
virtual s32 addDynamicLight(const SLight& light);
//! Turns a dynamic light on or off
//! \param lightIndex: the index returned by addDynamicLight
//! \param turnOn: true to turn the light on, false to turn it off
virtual void turnLightOn(s32 lightIndex, bool turnOn);
//! returns the maximal amount of dynamic lights the device can handle
virtual u32 getMaximalDynamicLightAmount() const;
//! Sets the dynamic ambient light color. The default color is
//! (0,0,0,0) which means it is dark.
//! \param color: New color of the ambient light.
virtual void setAmbientLight(const SColorf& color);
//! Draws a shadow volume into the stencil buffer.
virtual void drawStencilShadowVolume(const core::vector3df* triangles, s32 count, bool zfail);
//! Fills the stencil shadow with color.
virtual void drawStencilShadow(bool clearStencilBuffer=false,
video::SColor leftUpEdge = video::SColor(0,0,0,0),
video::SColor rightUpEdge = video::SColor(0,0,0,0),
video::SColor leftDownEdge = video::SColor(0,0,0,0),
video::SColor rightDownEdge = video::SColor(0,0,0,0));
//! Returns the maximum amount of primitives (mostly vertices) which
//! the device is able to render with one drawIndexedTriangleList
//! call.
virtual u32 getMaximalPrimitiveCount() const;
//! Enables or disables a texture creation flag.
virtual void setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag, bool enabled);
//! Sets the fog mode.
virtual void setFog(SColor color, E_FOG_TYPE fogType, f32 start,
f32 end, f32 density, bool pixelFog, bool rangeFog);
//! Only used by the internal engine. Used to notify the driver that
//! the window was resized.
virtual void OnResize(const core::dimension2d<u32>& size);
//! Can be called by an IMaterialRenderer to make its work easier.
virtual void setBasicRenderStates(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates);
//! Returns type of video driver
virtual E_DRIVER_TYPE getDriverType() const;
//! Returns the transformation set by setTransform
virtual const core::matrix4& getTransform(E_TRANSFORMATION_STATE state) const;
//! Sets a vertex shader constant.
virtual void setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1);
//! Sets a pixel shader constant.
virtual void setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1);
//! Sets a constant for the vertex shader based on a name.
virtual bool setVertexShaderConstant(const c8* name, const f32* floats, int count);
//! Sets a constant for the pixel shader based on a name.
virtual bool setPixelShaderConstant(const c8* name, const f32* floats, int count);
//! Returns a pointer to the IVideoDriver interface. (Implementation for
//! IMaterialRendererServices)
virtual IVideoDriver* getVideoDriver();
//! Creates a render target texture.
virtual ITexture* addRenderTargetTexture(const core::dimension2d<u32>& size,
const io::path& name, const ECOLOR_FORMAT format = ECF_UNKNOWN);
//! Clears the ZBuffer.
virtual void clearZBuffer();
//! Returns an image created from the last rendered frame.
virtual IImage* createScreenShot();
//! Set/unset a clipping plane.
virtual bool setClipPlane(u32 index, const core::plane3df& plane, bool enable=false);
//! Enable/disable a clipping plane.
virtual void enableClipPlane(u32 index, bool enable);
//! Returns the graphics card vendor name.
virtual core::stringc getVendorInfo() {return VendorName;}
//! Enable the 2d override material
virtual void enableMaterial2D(bool enable=true);
//! Check if the driver was recently reset.
virtual bool checkDriverReset() {return DriverWasReset;}
// removes the depth struct from the DepthSurface array
void removeDepthSurface(SDepthSurface* depth);
//! Get the current color format of the color buffer
/** \return Color format of the color buffer. */
virtual ECOLOR_FORMAT getColorFormat() const;
//! Returns the maximum texture size supported.
virtual core::dimension2du getMaxTextureSize() const;
//! Get the current color format of the color buffer
/** \return Color format of the color buffer as D3D color value. */
D3DFORMAT getD3DColorFormat() const;
//! Get D3D color format from Irrlicht color format.
D3DFORMAT getD3DFormatFromColorFormat(ECOLOR_FORMAT format) const;
//! Get Irrlicht color format from D3D color format.
ECOLOR_FORMAT getColorFormatFromD3DFormat(D3DFORMAT format) const;
private:
//! enumeration for rendering modes such as 2d and 3d for minizing the switching of renderStates.
enum E_RENDER_MODE
{
ERM_NONE = 0, // no render state has been set yet.
ERM_2D, // 2d drawing rendermode
ERM_3D, // 3d rendering mode
ERM_STENCIL_FILL, // stencil fill mode
ERM_SHADOW_VOLUME_ZFAIL, // stencil volume draw mode
ERM_SHADOW_VOLUME_ZPASS // stencil volume draw mode
};
//! sets right vertex shader
void setVertexShader(video::E_VERTEX_TYPE newType);
//! sets the needed renderstates
bool setRenderStates3DMode();
//! sets the needed renderstates
void setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel);
//! sets the needed renderstates
void setRenderStatesStencilFillMode(bool alpha);
//! sets the needed renderstates
void setRenderStatesStencilShadowMode(bool zfail);
//! sets the current Texture
bool setActiveTexture(u32 stage, const video::ITexture* texture);
//! resets the device
bool reset();
//! returns a device dependent texture from a software surface (IImage)
//! THIS METHOD HAS TO BE OVERRIDDEN BY DERIVED DRIVERS WITH OWN TEXTURES
virtual video::ITexture* createDeviceDependentTexture(IImage* surface, const io::path& name, void* mipmapData=0);
//! returns the current size of the screen or rendertarget
virtual const core::dimension2d<u32>& getCurrentRenderTargetSize() const;
//! Check if a proper depth buffer for the RTT is available, otherwise create it.
void checkDepthBuffer(ITexture* tex);
//! Adds a new material renderer to the VideoDriver, using pixel and/or
//! vertex shaders to render geometry.
s32 addShaderMaterial(const c8* vertexShaderProgram, const c8* pixelShaderProgram,
IShaderConstantSetCallBack* callback,
E_MATERIAL_TYPE baseMaterial, s32 userData);
//! Adds a new material renderer to the VideoDriver, based on a high level shading
//! language.
virtual s32 addHighLevelShaderMaterial(
const c8* vertexShaderProgram,
const c8* vertexShaderEntryPointName,
E_VERTEX_SHADER_TYPE vsCompileTarget,
const c8* pixelShaderProgram,
const c8* pixelShaderEntryPointName,
E_PIXEL_SHADER_TYPE psCompileTarget,
const c8* geometryShaderProgram,
const c8* geometryShaderEntryPointName = "main",
E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0,
scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES,
scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP,
u32 verticesOut = 0,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData=0);
void createMaterialRenderers();
void draw2D3DVertexPrimitiveList(const void* vertices,
u32 vertexCount, const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType,
E_INDEX_TYPE iType, bool is3D);
D3DTEXTUREADDRESS getTextureWrapMode(const u8 clamp);
inline D3DCOLORVALUE colorToD3D(const SColor& col)
{
const f32 f = 1.0f / 255.0f;
D3DCOLORVALUE v;
v.r = col.getRed() * f;
v.g = col.getGreen() * f;
v.b = col.getBlue() * f;
v.a = col.getAlpha() * f;
return v;
}
E_RENDER_MODE CurrentRenderMode;
D3DPRESENT_PARAMETERS present;
SMaterial Material, LastMaterial;
bool ResetRenderStates; // bool to make all renderstates be reseted if set.
bool Transformation3DChanged;
bool StencilBuffer;
u8 AntiAliasing;
const ITexture* CurrentTexture[MATERIAL_MAX_TEXTURES];
bool LastTextureMipMapsAvailable[MATERIAL_MAX_TEXTURES];
core::matrix4 Matrices[ETS_COUNT]; // matrizes of the 3d mode we need to restore when we switch back from the 2d mode.
HINSTANCE D3DLibrary;
IDirect3D9* pID3D;
IDirect3DDevice9* pID3DDevice;
IDirect3DSurface9* PrevRenderTarget;
core::dimension2d<u32> CurrentRendertargetSize;
core::dimension2d<u32> CurrentDepthBufferSize;
HWND WindowId;
core::rect<s32>* SceneSourceRect;
D3DCAPS9 Caps;
E_VERTEX_TYPE LastVertexType;
SColorf AmbientLight;
core::stringc VendorName;
u16 VendorID;
core::array<SDepthSurface*> DepthBuffers;
u32 MaxTextureUnits;
u32 MaxUserClipPlanes;
f32 MaxLightDistance;
s32 LastSetLight;
enum E_CACHE_2D_ATTRIBUTES
{
EC2D_ALPHA = 0x1,
EC2D_TEXTURE = 0x2,
EC2D_ALPHA_CHANNEL = 0x4
};
u32 Cached2DModeSignature;
ECOLOR_FORMAT ColorFormat;
D3DFORMAT D3DColorFormat;
bool DeviceLost;
bool Fullscreen;
bool DriverWasReset;
bool AlphaToCoverageSupport;
};
} // end namespace video
} // end namespace irr
#endif // _IRR_COMPILE_WITH_DIRECT3D_9_
#endif // __C_VIDEO_DIRECTX_9_H_INCLUDED__
diff --git a/source/Irrlicht/CD3D9MaterialRenderer.h b/source/Irrlicht/CD3D9MaterialRenderer.h
index f108ad7..284ac8f 100644
--- a/source/Irrlicht/CD3D9MaterialRenderer.h
+++ b/source/Irrlicht/CD3D9MaterialRenderer.h
@@ -1,524 +1,526 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_D3D9_MATERIAL_RENDERER_H_INCLUDED__
#define __C_D3D9_MATERIAL_RENDERER_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_WINDOWS_
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
+#if defined(__BORLANDC__) || defined (__BCPLUSPLUS__)
#include "irrMath.h" // needed by borland for sqrtf define
+#endif
#include <d3d9.h>
#include "IMaterialRenderer.h"
namespace irr
{
namespace video
{
D3DMATRIX UnitMatrixD3D9;
D3DMATRIX SphereMapMatrixD3D9;
//! Base class for all internal D3D9 material renderers
class CD3D9MaterialRenderer : public IMaterialRenderer
{
public:
//! Constructor
CD3D9MaterialRenderer(IDirect3DDevice9* d3ddev, video::IVideoDriver* driver)
: pID3DDevice(d3ddev), Driver(driver)
{
}
~CD3D9MaterialRenderer()
{
}
//! sets a variable in the shader.
//! \param vertexShader: True if this should be set in the vertex shader, false if
//! in the pixel shader.
//! \param name: Name of the variable
//! \param floats: Pointer to array of floats
//! \param count: Amount of floats in array.
virtual bool setVariable(bool vertexShader, const c8* name, const f32* floats, int count)
{
os::Printer::log("Invalid material to set variable in.");
return false;
}
protected:
IDirect3DDevice9* pID3DDevice;
video::IVideoDriver* Driver;
};
//! Solid material renderer
class CD3D9MaterialRenderer_SOLID : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_SOLID(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
pID3DDevice->SetTextureStageState (0, D3DTSS_COLOROP, D3DTOP_MODULATE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
}
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
};
//! Generic Texture Blend
class CD3D9MaterialRenderer_ONETEXTURE_BLEND : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_ONETEXTURE_BLEND(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType ||
material.MaterialTypeParam != lastMaterial.MaterialTypeParam ||
resetAllRenderstates)
{
E_BLEND_FACTOR srcFact,dstFact;
E_MODULATE_FUNC modulate;
u32 alphaSource;
unpack_texureBlendFunc ( srcFact, dstFact, modulate, alphaSource, material.MaterialTypeParam );
if (srcFact == EBF_SRC_COLOR && dstFact == EBF_ZERO)
{
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
}
else
{
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
pID3DDevice->SetRenderState(D3DRS_SRCBLEND, getD3DBlend ( srcFact ) );
pID3DDevice->SetRenderState(D3DRS_DESTBLEND, getD3DBlend ( dstFact ) );
}
pID3DDevice->SetTextureStageState (0, D3DTSS_COLOROP, getD3DModulate ( modulate ) );
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
if ( textureBlendFunc_hasAlpha ( srcFact ) || textureBlendFunc_hasAlpha ( dstFact ) )
{
if (alphaSource==EAS_VERTEX_COLOR)
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE );
}
else if (alphaSource==EAS_TEXTURE)
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
}
else
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
}
}
else
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
}
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
//! Returns if the material is transparent.
/** The scene management needs to know this for being able to sort the
materials by opaque and transparent.
The return value could be optimized, but we'd need to know the
MaterialTypeParam for it. */
virtual bool isTransparent() const
{
return true;
}
private:
u32 getD3DBlend ( E_BLEND_FACTOR factor ) const
{
u32 r = 0;
switch ( factor )
{
case EBF_ZERO: r = D3DBLEND_ZERO; break;
case EBF_ONE: r = D3DBLEND_ONE; break;
case EBF_DST_COLOR: r = D3DBLEND_DESTCOLOR; break;
case EBF_ONE_MINUS_DST_COLOR: r = D3DBLEND_INVDESTCOLOR; break;
case EBF_SRC_COLOR: r = D3DBLEND_SRCCOLOR; break;
case EBF_ONE_MINUS_SRC_COLOR: r = D3DBLEND_INVSRCCOLOR; break;
case EBF_SRC_ALPHA: r = D3DBLEND_SRCALPHA; break;
case EBF_ONE_MINUS_SRC_ALPHA: r = D3DBLEND_INVSRCALPHA; break;
case EBF_DST_ALPHA: r = D3DBLEND_DESTALPHA; break;
case EBF_ONE_MINUS_DST_ALPHA: r = D3DBLEND_INVDESTALPHA; break;
case EBF_SRC_ALPHA_SATURATE: r = D3DBLEND_SRCALPHASAT; break;
}
return r;
}
u32 getD3DModulate ( E_MODULATE_FUNC func ) const
{
u32 r = D3DTOP_MODULATE;
switch ( func )
{
case EMFN_MODULATE_1X: r = D3DTOP_MODULATE; break;
case EMFN_MODULATE_2X: r = D3DTOP_MODULATE2X; break;
case EMFN_MODULATE_4X: r = D3DTOP_MODULATE4X; break;
}
return r;
}
bool transparent;
};
//! Solid 2 layer material renderer
class CD3D9MaterialRenderer_SOLID_2_LAYER : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_SOLID_2_LAYER(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
pID3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
pID3DDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 0);
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_BLENDDIFFUSEALPHA);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
};
//! Transparent add color material renderer
class CD3D9MaterialRenderer_TRANSPARENT_ADD_COLOR : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_TRANSPARENT_ADD_COLOR(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
pID3DDevice->SetTextureStageState (0, D3DTSS_COLOROP, D3DTOP_MODULATE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
pID3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
pID3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCCOLOR);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
//! Returns if the material is transparent. The scene management needs to know this
//! for being able to sort the materials by opaque and transparent.
virtual bool isTransparent() const
{
return true;
}
};
//! Transparent vertex alpha material renderer
class CD3D9MaterialRenderer_TRANSPARENT_VERTEX_ALPHA : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_TRANSPARENT_VERTEX_ALPHA(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
pID3DDevice->SetTextureStageState (0, D3DTSS_COLOROP, D3DTOP_MODULATE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
pID3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
pID3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
//! Returns if the material is transparent. The scene managment needs to know this
//! for being able to sort the materials by opaque and transparent.
virtual bool isTransparent() const
{
return true;
}
};
//! Transparent alpha channel material renderer
class CD3D9MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates
|| material.MaterialTypeParam != lastMaterial.MaterialTypeParam )
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_CURRENT );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE );
pID3DDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
pID3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
pID3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
pID3DDevice->SetRenderState(D3DRS_ALPHAREF, core::floor32(material.MaterialTypeParam * 255.f));
pID3DDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
pID3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
virtual void OnUnsetMaterial()
{
pID3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
}
//! Returns if the material is transparent. The scene managment needs to know this
//! for being able to sort the materials by opaque and transparent.
virtual bool isTransparent() const
{
return true;
}
};
//! Transparent alpha channel material renderer
class CD3D9MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL_REF : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL_REF(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_CURRENT );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE );
pID3DDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
// 127 is required by EMT_TRANSPARENT_ALPHA_CHANNEL_REF
pID3DDevice->SetRenderState(D3DRS_ALPHAREF, 127);
pID3DDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
pID3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
virtual void OnUnsetMaterial()
{
pID3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
}
//! Returns if the material is transparent. The scene managment needs to know this
//! for being able to sort the materials by opaque and transparent.
virtual bool isTransparent() const
{
return false; // this material is not really transparent because it does no blending.
}
};
//! material renderer for all kinds of lightmaps
class CD3D9MaterialRenderer_LIGHTMAP : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_LIGHTMAP(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
if (material.MaterialType >= EMT_LIGHTMAP_LIGHTING)
{
// with lighting
pID3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
pID3DDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
}
else
{
pID3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
pID3DDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
}
pID3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 1);
if (material.MaterialType == EMT_LIGHTMAP_ADD)
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_ADD);
else
if (material.MaterialType == EMT_LIGHTMAP_M4 || material.MaterialType == EMT_LIGHTMAP_LIGHTING_M4)
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE4X);
else
if (material.MaterialType == EMT_LIGHTMAP_M2 || material.MaterialType == EMT_LIGHTMAP_LIGHTING_M2)
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE2X);
else
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE);
pID3DDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT);
pID3DDevice->SetTextureStageState (1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
};
//! material renderer for detail maps
class CD3D9MaterialRenderer_DETAIL_MAP : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_DETAIL_MAP(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
pID3DDevice->SetTextureStageState (0, D3DTSS_COLOROP, D3DTOP_MODULATE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState (1, D3DTSS_COLOROP, D3DTOP_ADDSIGNED);
pID3DDevice->SetTextureStageState (1, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState (1, D3DTSS_COLORARG2, D3DTA_CURRENT);
pID3DDevice->SetTextureStageState (1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 1);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
};
//! sphere map material renderer
class CD3D9MaterialRenderer_SPHERE_MAP : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_SPHERE_MAP(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
pID3DDevice->SetTextureStageState (0, D3DTSS_COLOROP, D3DTOP_MODULATE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
pID3DDevice->SetTransform( D3DTS_TEXTURE0, &SphereMapMatrixD3D9 );
pID3DDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2 );
pID3DDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACENORMAL );
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
virtual void OnUnsetMaterial()
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 0);
pID3DDevice->SetTransform( D3DTS_TEXTURE0, &UnitMatrixD3D9 );
}
};
diff --git a/source/Irrlicht/CD3D9NormalMapRenderer.h b/source/Irrlicht/CD3D9NormalMapRenderer.h
index 3e2f25f..432ec55 100644
--- a/source/Irrlicht/CD3D9NormalMapRenderer.h
+++ b/source/Irrlicht/CD3D9NormalMapRenderer.h
@@ -1,54 +1,56 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_D3D9_NORMAL_MAPMATERIAL_RENDERER_H_INCLUDED__
#define __C_D3D9_NORMAL_MAPMATERIAL_RENDERER_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_WINDOWS_
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
+#if defined(__BORLANDC__) || defined (__BCPLUSPLUS__)
#include "irrMath.h" // needed by borland for sqrtf define
+#endif
#include <d3d9.h>
#include "CD3D9ShaderMaterialRenderer.h"
#include "IShaderConstantSetCallBack.h"
namespace irr
{
namespace video
{
//! Renderer for normal maps
class CD3D9NormalMapRenderer :
public CD3D9ShaderMaterialRenderer, IShaderConstantSetCallBack
{
public:
CD3D9NormalMapRenderer(
IDirect3DDevice9* d3ddev, video::IVideoDriver* driver,
s32& outMaterialTypeNr, IMaterialRenderer* baseMaterial);
~CD3D9NormalMapRenderer();
//! Called by the engine when the vertex and/or pixel shader constants for an
//! material renderer should be set.
virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData);
virtual bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype);
//! Returns the render capability of the material.
virtual s32 getRenderCapability() const;
private:
};
} // end namespace video
} // end namespace irr
#endif
#endif
#endif
diff --git a/source/Irrlicht/CD3D9ParallaxMapRenderer.h b/source/Irrlicht/CD3D9ParallaxMapRenderer.h
index 15cb527..a62373d 100644
--- a/source/Irrlicht/CD3D9ParallaxMapRenderer.h
+++ b/source/Irrlicht/CD3D9ParallaxMapRenderer.h
@@ -1,61 +1,63 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_D3D9_PARALLAX_MAPMATERIAL_RENDERER_H_INCLUDED__
#define __C_D3D9_PARALLAX_MAPMATERIAL_RENDERER_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_WINDOWS_
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
+#if defined(__BORLANDC__) || defined (__BCPLUSPLUS__)
#include "irrMath.h" // needed by borland for sqrtf define
+#endif
#include <d3d9.h>
#include "CD3D9ShaderMaterialRenderer.h"
#include "IShaderConstantSetCallBack.h"
namespace irr
{
namespace video
{
//! Renderer for normal maps using parallax mapping
class CD3D9ParallaxMapRenderer :
public CD3D9ShaderMaterialRenderer, IShaderConstantSetCallBack
{
public:
CD3D9ParallaxMapRenderer(
IDirect3DDevice9* d3ddev, video::IVideoDriver* driver,
s32& outMaterialTypeNr, IMaterialRenderer* baseMaterial);
~CD3D9ParallaxMapRenderer();
//! Called by the engine when the vertex and/or pixel shader constants for an
//! material renderer should be set.
virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData);
virtual bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype);
//! Returns the render capability of the material.
virtual s32 getRenderCapability() const;
virtual void OnSetMaterial(const SMaterial& material) { }
virtual void OnSetMaterial(const video::SMaterial& material,
const video::SMaterial& lastMaterial,
bool resetAllRenderstates, video::IMaterialRendererServices* services);
private:
f32 CurrentScale;
};
} // end namespace video
} // end namespace irr
#endif
#endif
#endif
diff --git a/source/Irrlicht/CD3D9ShaderMaterialRenderer.h b/source/Irrlicht/CD3D9ShaderMaterialRenderer.h
index e69fc34..66354de 100644
--- a/source/Irrlicht/CD3D9ShaderMaterialRenderer.h
+++ b/source/Irrlicht/CD3D9ShaderMaterialRenderer.h
@@ -1,101 +1,103 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_D3D9_SHADER_MATERIAL_RENDERER_H_INCLUDED__
#define __C_D3D9_SHADER_MATERIAL_RENDERER_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_WINDOWS_
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
+#if defined(__BORLANDC__) || defined (__BCPLUSPLUS__)
#include "irrMath.h" // needed by borland for sqrtf define
+#endif
#include <d3d9.h>
#include <d3dx9shader.h>
#include "IMaterialRenderer.h"
namespace irr
{
namespace video
{
class IVideoDriver;
class IShaderConstantSetCallBack;
class IMaterialRenderer;
//! Class for using vertex and pixel shaders with D3D9
class CD3D9ShaderMaterialRenderer : public IMaterialRenderer
{
public:
//! Public constructor
CD3D9ShaderMaterialRenderer(IDirect3DDevice9* d3ddev, video::IVideoDriver* driver,
s32& outMaterialTypeNr, const c8* vertexShaderProgram, const c8* pixelShaderProgram,
IShaderConstantSetCallBack* callback, IMaterialRenderer* baseMaterial, s32 userData);
//! Destructor
~CD3D9ShaderMaterialRenderer();
virtual void OnSetMaterial(const video::SMaterial& material, const video::SMaterial& lastMaterial,
bool resetAllRenderstates, video::IMaterialRendererServices* services);
virtual void OnUnsetMaterial();
virtual bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype);
//! Returns if the material is transparent.
virtual bool isTransparent() const;
protected:
//! constructor only for use by derived classes who want to
//! create a fall back material for example.
CD3D9ShaderMaterialRenderer(IDirect3DDevice9* d3ddev,
video::IVideoDriver* driver,
IShaderConstantSetCallBack* callback,
IMaterialRenderer* baseMaterial,
s32 userData=0);
void init(s32& outMaterialTypeNr, const c8* vertexShaderProgram, const c8* pixelShaderProgram);
bool createPixelShader(const c8* pxsh);
bool createVertexShader(const char* vtxsh);
HRESULT stubD3DXAssembleShader(LPCSTR pSrcData, UINT SrcDataLen,
CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude,
DWORD Flags, LPD3DXBUFFER* ppShader,
LPD3DXBUFFER* ppErrorMsgs);
HRESULT stubD3DXAssembleShaderFromFile(LPCSTR pSrcFile,
CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, DWORD Flags,
LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs);
HRESULT stubD3DXCompileShader(LPCSTR pSrcData, UINT SrcDataLen, CONST D3DXMACRO* pDefines,
LPD3DXINCLUDE pInclude, LPCSTR pFunctionName,
LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader,
LPD3DXBUFFER* ppErrorMsgs, LPD3DXCONSTANTTABLE* ppConstantTable);
HRESULT stubD3DXCompileShaderFromFile(LPCSTR pSrcFile, CONST D3DXMACRO* pDefines,
LPD3DXINCLUDE pInclude, LPCSTR pFunctionName,
LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs,
LPD3DXCONSTANTTABLE* ppConstantTable);
IDirect3DDevice9* pID3DDevice;
video::IVideoDriver* Driver;
IShaderConstantSetCallBack* CallBack;
IMaterialRenderer* BaseMaterial;
IDirect3DVertexShader9* VertexShader;
IDirect3DVertexShader9* OldVertexShader;
IDirect3DPixelShader9* PixelShader;
s32 UserData;
};
} // end namespace video
} // end namespace irr
#endif
#endif
#endif
diff --git a/source/Irrlicht/CD3D9Texture.h b/source/Irrlicht/CD3D9Texture.h
index 73130f9..19927f1 100644
--- a/source/Irrlicht/CD3D9Texture.h
+++ b/source/Irrlicht/CD3D9Texture.h
@@ -1,128 +1,130 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_DIRECTX9_TEXTURE_H_INCLUDED__
#define __C_DIRECTX9_TEXTURE_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
#include "ITexture.h"
#include "IImage.h"
+#if defined(__BORLANDC__) || defined (__BCPLUSPLUS__)
#include "irrMath.h" // needed by borland for sqrtf define
+#endif
#include <d3d9.h>
namespace irr
{
namespace video
{
class CD3D9Driver;
// forward declaration for RTT depth buffer handling
struct SDepthSurface;
/*!
interface for a Video Driver dependent Texture.
*/
class CD3D9Texture : public ITexture
{
public:
//! constructor
CD3D9Texture(IImage* image, CD3D9Driver* driver,
u32 flags, const io::path& name, void* mipmapData=0);
//! rendertarget constructor
CD3D9Texture(CD3D9Driver* driver, const core::dimension2d<u32>& size, const io::path& name,
const ECOLOR_FORMAT format = ECF_UNKNOWN);
//! destructor
virtual ~CD3D9Texture();
//! lock function
virtual void* lock(bool readOnly = false, u32 mipmapLevel=0);
//! unlock function
virtual void unlock();
//! Returns original size of the texture.
virtual const core::dimension2d<u32>& getOriginalSize() const;
//! Returns (=size) of the texture.
virtual const core::dimension2d<u32>& getSize() const;
//! returns driver type of texture (=the driver, who created the texture)
virtual E_DRIVER_TYPE getDriverType() const;
//! returns color format of texture
virtual ECOLOR_FORMAT getColorFormat() const;
//! returns pitch of texture (in bytes)
virtual u32 getPitch() const;
//! returns the DIRECT3D9 Texture
IDirect3DBaseTexture9* getDX9Texture() const;
//! returns if texture has mipmap levels
bool hasMipMaps() const;
//! Regenerates the mip map levels of the texture. Useful after locking and
//! modifying the texture
virtual void regenerateMipMapLevels(void* mipmapData=0);
//! returns if it is a render target
virtual bool isRenderTarget() const;
//! Returns pointer to the render target surface
IDirect3DSurface9* getRenderTargetSurface();
private:
friend class CD3D9Driver;
void createRenderTarget(const ECOLOR_FORMAT format = ECF_UNKNOWN);
//! creates the hardware texture
bool createTexture(u32 flags, IImage * image);
//! copies the image to the texture
bool copyTexture(IImage * image);
//! Helper function for mipmap generation.
bool createMipMaps(u32 level=1);
//! Helper function for mipmap generation.
void copy16BitMipMap(char* src, char* tgt,
s32 width, s32 height, s32 pitchsrc, s32 pitchtgt) const;
//! Helper function for mipmap generation.
void copy32BitMipMap(char* src, char* tgt,
s32 width, s32 height, s32 pitchsrc, s32 pitchtgt) const;
//! set Pitch based on the d3d format
void setPitch(D3DFORMAT d3dformat);
IDirect3DDevice9* Device;
IDirect3DTexture9* Texture;
IDirect3DSurface9* RTTSurface;
CD3D9Driver* Driver;
SDepthSurface* DepthSurface;
core::dimension2d<u32> TextureSize;
core::dimension2d<u32> ImageSize;
s32 Pitch;
u32 MipLevelLocked;
ECOLOR_FORMAT ColorFormat;
bool HasMipMaps;
bool HardwareMipMaps;
bool IsRenderTarget;
};
} // end namespace video
} // end namespace irr
#endif // _IRR_COMPILE_WITH_DIRECT3D_9_
#endif // __C_DIRECTX9_TEXTURE_H_INCLUDED__
diff --git a/source/Irrlicht/CIrrDeviceWin32.cpp b/source/Irrlicht/CIrrDeviceWin32.cpp
index 096c459..5f1dfcf 100644
--- a/source/Irrlicht/CIrrDeviceWin32.cpp
+++ b/source/Irrlicht/CIrrDeviceWin32.cpp
@@ -1,1455 +1,1538 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_
#include "CIrrDeviceWin32.h"
#include "IEventReceiver.h"
#include "irrList.h"
#include "os.h"
#include "CTimer.h"
#include "irrString.h"
#include "COSOperator.h"
#include "dimension2d.h"
#include <winuser.h>
namespace irr
{
namespace video
{
#ifdef _IRR_COMPILE_WITH_DIRECT3D_8_
IVideoDriver* createDirectX8Driver(const core::dimension2d<u32>& screenSize, HWND window,
u32 bits, bool fullscreen, bool stencilbuffer, io::IFileSystem* io,
bool pureSoftware, bool highPrecisionFPU, bool vsync, u8 antiAlias);
#endif
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
IVideoDriver* createDirectX9Driver(const core::dimension2d<u32>& screenSize, HWND window,
u32 bits, bool fullscreen, bool stencilbuffer, io::IFileSystem* io,
bool pureSoftware, bool highPrecisionFPU, bool vsync, u8 antiAlias);
#endif
#ifdef _IRR_COMPILE_WITH_OPENGL_
IVideoDriver* createOpenGLDriver(const irr::SIrrlichtCreationParameters& params,
io::IFileSystem* io, CIrrDeviceWin32* device);
#endif
}
} // end namespace irr
-// Get the codepage from the locale language id
+// Get the codepage from the locale language id
// Based on the table from http://www.science.co.il/Language/Locale-Codes.asp?s=decimal
static unsigned int LocaleIdToCodepage(unsigned int lcid)
{
switch ( lcid )
{
case 1098: // Telugu
case 1095: // Gujarati
case 1094: // Punjabi
case 1103: // Sanskrit
case 1111: // Konkani
case 1114: // Syriac
case 1099: // Kannada
case 1102: // Marathi
case 1125: // Divehi
case 1067: // Armenian
case 1081: // Hindi
case 1079: // Georgian
case 1097: // Tamil
return 0;
case 1054: // Thai
return 874;
case 1041: // Japanese
return 932;
case 2052: // Chinese (PRC)
case 4100: // Chinese (Singapore)
return 936;
case 1042: // Korean
return 949;
case 5124: // Chinese (Macau S.A.R.)
case 3076: // Chinese (Hong Kong S.A.R.)
case 1028: // Chinese (Taiwan)
return 950;
case 1048: // Romanian
case 1060: // Slovenian
case 1038: // Hungarian
case 1051: // Slovak
case 1045: // Polish
case 1052: // Albanian
case 2074: // Serbian (Latin)
case 1050: // Croatian
case 1029: // Czech
return 1250;
case 1104: // Mongolian (Cyrillic)
case 1071: // FYRO Macedonian
case 2115: // Uzbek (Cyrillic)
case 1058: // Ukrainian
case 2092: // Azeri (Cyrillic)
case 1092: // Tatar
case 1087: // Kazakh
case 1059: // Belarusian
case 1088: // Kyrgyz (Cyrillic)
case 1026: // Bulgarian
case 3098: // Serbian (Cyrillic)
case 1049: // Russian
return 1251;
case 8201: // English (Jamaica)
case 3084: // French (Canada)
case 1036: // French (France)
case 5132: // French (Luxembourg)
case 5129: // English (New Zealand)
case 6153: // English (Ireland)
case 1043: // Dutch (Netherlands)
case 9225: // English (Caribbean)
case 4108: // French (Switzerland)
case 4105: // English (Canada)
case 1110: // Galician
case 10249: // English (Belize)
case 3079: // German (Austria)
case 6156: // French (Monaco)
case 12297: // English (Zimbabwe)
case 1069: // Basque
case 2067: // Dutch (Belgium)
case 2060: // French (Belgium)
case 1035: // Finnish
case 1080: // Faroese
case 1031: // German (Germany)
case 3081: // English (Australia)
case 1033: // English (United States)
case 2057: // English (United Kingdom)
case 1027: // Catalan
case 11273: // English (Trinidad)
case 7177: // English (South Africa)
case 1030: // Danish
case 13321: // English (Philippines)
case 15370: // Spanish (Paraguay)
case 9226: // Spanish (Colombia)
case 5130: // Spanish (Costa Rica)
case 7178: // Spanish (Dominican Republic)
case 12298: // Spanish (Ecuador)
case 17418: // Spanish (El Salvador)
case 4106: // Spanish (Guatemala)
case 18442: // Spanish (Honduras)
case 3082: // Spanish (International Sort)
case 13322: // Spanish (Chile)
case 19466: // Spanish (Nicaragua)
case 2058: // Spanish (Mexico)
case 10250: // Spanish (Peru)
case 20490: // Spanish (Puerto Rico)
case 1034: // Spanish (Traditional Sort)
case 14346: // Spanish (Uruguay)
case 8202: // Spanish (Venezuela)
case 1089: // Swahili
case 1053: // Swedish
case 2077: // Swedish (Finland)
case 5127: // German (Liechtenstein)
case 1078: // Afrikaans
case 6154: // Spanish (Panama)
case 4103: // German (Luxembourg)
case 16394: // Spanish (Bolivia)
case 2055: // German (Switzerland)
case 1039: // Icelandic
case 1057: // Indonesian
case 1040: // Italian (Italy)
case 2064: // Italian (Switzerland)
case 2068: // Norwegian (Nynorsk)
case 11274: // Spanish (Argentina)
case 1046: // Portuguese (Brazil)
case 1044: // Norwegian (Bokmal)
case 1086: // Malay (Malaysia)
case 2110: // Malay (Brunei Darussalam)
case 2070: // Portuguese (Portugal)
return 1252;
case 1032: // Greek
return 1253;
case 1091: // Uzbek (Latin)
case 1068: // Azeri (Latin)
case 1055: // Turkish
return 1254;
case 1037: // Hebrew
return 1255;
case 5121: // Arabic (Algeria)
case 15361: // Arabic (Bahrain)
case 9217: // Arabic (Yemen)
case 3073: // Arabic (Egypt)
case 2049: // Arabic (Iraq)
case 11265: // Arabic (Jordan)
case 13313: // Arabic (Kuwait)
case 12289: // Arabic (Lebanon)
case 4097: // Arabic (Libya)
case 6145: // Arabic (Morocco)
case 8193: // Arabic (Oman)
case 16385: // Arabic (Qatar)
case 1025: // Arabic (Saudi Arabia)
case 10241: // Arabic (Syria)
case 14337: // Arabic (U.A.E.)
case 1065: // Farsi
case 1056: // Urdu
case 7169: // Arabic (Tunisia)
return 1256;
case 1061: // Estonian
case 1062: // Latvian
case 1063: // Lithuanian
return 1257;
case 1066: // Vietnamese
return 1258;
}
return 65001; // utf-8
-}
+}
namespace
{
struct SEnvMapper
{
HWND hWnd;
irr::CIrrDeviceWin32* irrDev;
};
irr::core::list<SEnvMapper> EnvMap;
HKL KEYBOARD_INPUT_HKL=0;
- unsigned int KEYBOARD_INPUT_CODEPAGE = 1252;
+ unsigned int KEYBOARD_INPUT_CODEPAGE = 1252;
};
SEnvMapper* getEnvMapperFromHWnd(HWND hWnd)
{
irr::core::list<SEnvMapper>::Iterator it = EnvMap.begin();
for (; it!= EnvMap.end(); ++it)
if ((*it).hWnd == hWnd)
return &(*it);
return 0;
}
irr::CIrrDeviceWin32* getDeviceFromHWnd(HWND hWnd)
{
irr::core::list<SEnvMapper>::Iterator it = EnvMap.begin();
for (; it!= EnvMap.end(); ++it)
if ((*it).hWnd == hWnd)
return (*it).irrDev;
return 0;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
#ifndef WM_MOUSEWHEEL
#define WM_MOUSEWHEEL 0x020A
#endif
#ifndef WHEEL_DELTA
#define WHEEL_DELTA 120
#endif
irr::CIrrDeviceWin32* dev = 0;
irr::SEvent event;
static irr::s32 ClickCount=0;
if (GetCapture() != hWnd && ClickCount > 0)
ClickCount = 0;
struct messageMap
{
irr::s32 group;
UINT winMessage;
irr::s32 irrMessage;
};
static messageMap mouseMap[] =
{
{0, WM_LBUTTONDOWN, irr::EMIE_LMOUSE_PRESSED_DOWN},
{1, WM_LBUTTONUP, irr::EMIE_LMOUSE_LEFT_UP},
{0, WM_RBUTTONDOWN, irr::EMIE_RMOUSE_PRESSED_DOWN},
{1, WM_RBUTTONUP, irr::EMIE_RMOUSE_LEFT_UP},
{0, WM_MBUTTONDOWN, irr::EMIE_MMOUSE_PRESSED_DOWN},
{1, WM_MBUTTONUP, irr::EMIE_MMOUSE_LEFT_UP},
{2, WM_MOUSEMOVE, irr::EMIE_MOUSE_MOVED},
{3, WM_MOUSEWHEEL, irr::EMIE_MOUSE_WHEEL},
{-1, 0, 0}
};
// handle grouped events
messageMap * m = mouseMap;
while ( m->group >=0 && m->winMessage != message )
m += 1;
if ( m->group >= 0 )
{
if ( m->group == 0 ) // down
{
ClickCount++;
SetCapture(hWnd);
}
else
if ( m->group == 1 ) // up
{
ClickCount--;
if (ClickCount<1)
{
ClickCount=0;
ReleaseCapture();
}
}
event.EventType = irr::EET_MOUSE_INPUT_EVENT;
event.MouseInput.Event = (irr::EMOUSE_INPUT_EVENT) m->irrMessage;
event.MouseInput.X = (short)LOWORD(lParam);
event.MouseInput.Y = (short)HIWORD(lParam);
event.MouseInput.Shift = ((LOWORD(wParam) & MK_SHIFT) != 0);
event.MouseInput.Control = ((LOWORD(wParam) & MK_CONTROL) != 0);
// left and right mouse buttons
event.MouseInput.ButtonStates = wParam & ( MK_LBUTTON | MK_RBUTTON);
// middle and extra buttons
if (wParam & MK_MBUTTON)
event.MouseInput.ButtonStates |= irr::EMBSM_MIDDLE;
#if(_WIN32_WINNT >= 0x0500)
if (wParam & MK_XBUTTON1)
event.MouseInput.ButtonStates |= irr::EMBSM_EXTRA1;
if (wParam & MK_XBUTTON2)
event.MouseInput.ButtonStates |= irr::EMBSM_EXTRA2;
#endif
event.MouseInput.Wheel = 0.f;
// wheel
if ( m->group == 3 )
{
POINT p; // fixed by jox
p.x = 0; p.y = 0;
ClientToScreen(hWnd, &p);
event.MouseInput.X -= p.x;
event.MouseInput.Y -= p.y;
event.MouseInput.Wheel = ((irr::f32)((short)HIWORD(wParam))) / (irr::f32)WHEEL_DELTA;
}
dev = getDeviceFromHWnd(hWnd);
if (dev)
{
dev->postEventFromUser(event);
if ( event.MouseInput.Event >= irr::EMIE_LMOUSE_PRESSED_DOWN && event.MouseInput.Event <= irr::EMIE_MMOUSE_PRESSED_DOWN )
{
irr::u32 clicks = dev->checkSuccessiveClicks(event.MouseInput.X, event.MouseInput.Y, event.MouseInput.Event);
if ( clicks == 2 )
{
event.MouseInput.Event = (irr::EMOUSE_INPUT_EVENT)(irr::EMIE_LMOUSE_DOUBLE_CLICK + event.MouseInput.Event-irr::EMIE_LMOUSE_PRESSED_DOWN);
dev->postEventFromUser(event);
}
else if ( clicks == 3 )
{
event.MouseInput.Event = (irr::EMOUSE_INPUT_EVENT)(irr::EMIE_LMOUSE_TRIPLE_CLICK + event.MouseInput.Event-irr::EMIE_LMOUSE_PRESSED_DOWN);
dev->postEventFromUser(event);
}
}
}
return 0;
}
switch (message)
{
case WM_PAINT:
{
PAINTSTRUCT ps;
BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
}
return 0;
case WM_ERASEBKGND:
return 0;
case WM_SYSKEYDOWN:
case WM_SYSKEYUP:
case WM_KEYDOWN:
case WM_KEYUP:
{
BYTE allKeys[256];
event.EventType = irr::EET_KEY_INPUT_EVENT;
event.KeyInput.Key = (irr::EKEY_CODE)wParam;
event.KeyInput.PressedDown = (message==WM_KEYDOWN || message == WM_SYSKEYDOWN);
const UINT MY_MAPVK_VSC_TO_VK_EX = 3; // MAPVK_VSC_TO_VK_EX should be in SDK according to MSDN, but isn't in mine.
if ( event.KeyInput.Key == irr::KEY_SHIFT )
{
// this will fail on systems before windows NT/2000/XP, not sure _what_ will return there instead.
event.KeyInput.Key = (irr::EKEY_CODE)MapVirtualKey( ((lParam>>16) & 255), MY_MAPVK_VSC_TO_VK_EX );
}
if ( event.KeyInput.Key == irr::KEY_CONTROL )
{
event.KeyInput.Key = (irr::EKEY_CODE)MapVirtualKey( ((lParam>>16) & 255), MY_MAPVK_VSC_TO_VK_EX );
// some keyboards will just return LEFT for both - left and right keys. So also check extend bit.
if (lParam & 0x1000000)
event.KeyInput.Key = irr::KEY_RCONTROL;
}
if ( event.KeyInput.Key == irr::KEY_MENU )
{
event.KeyInput.Key = (irr::EKEY_CODE)MapVirtualKey( ((lParam>>16) & 255), MY_MAPVK_VSC_TO_VK_EX );
if (lParam & 0x1000000)
event.KeyInput.Key = irr::KEY_RMENU;
}
GetKeyboardState(allKeys);
event.KeyInput.Shift = ((allKeys[VK_SHIFT] & 0x80)!=0);
event.KeyInput.Control = ((allKeys[VK_CONTROL] & 0x80)!=0);
// Handle unicode and deadkeys in a way that works since Windows 95 and nt4.0
// Using ToUnicode instead would be shorter, but would to my knowledge not run on 95 and 98.
WORD keyChars[2];
UINT scanCode = HIWORD(lParam);
int conversionResult = ToAsciiEx(wParam,scanCode,allKeys,keyChars,0,KEYBOARD_INPUT_HKL);
if (conversionResult == 1)
{
WORD unicodeChar;
MultiByteToWideChar(
KEYBOARD_INPUT_CODEPAGE,
MB_PRECOMPOSED, // default
(LPCSTR)keyChars,
sizeof(keyChars),
(WCHAR*)&unicodeChar,
1 );
- event.KeyInput.Char = unicodeChar;
+ event.KeyInput.Char = unicodeChar;
}
else
event.KeyInput.Char = 0;
// allow composing characters like '@' with Alt Gr on non-US keyboards
if ((allKeys[VK_MENU] & 0x80) != 0)
event.KeyInput.Control = 0;
dev = getDeviceFromHWnd(hWnd);
if (dev)
dev->postEventFromUser(event);
if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
return DefWindowProc(hWnd, message, wParam, lParam);
else
return 0;
}
case WM_SIZE:
{
// resize
dev = getDeviceFromHWnd(hWnd);
if (dev)
dev->OnResized();
}
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_SYSCOMMAND:
// prevent screensaver or monitor powersave mode from starting
if ((wParam & 0xFFF0) == SC_SCREENSAVE ||
(wParam & 0xFFF0) == SC_MONITORPOWER)
return 0;
break;
case WM_ACTIVATE:
// we need to take care for screen changes, e.g. Alt-Tab
dev = getDeviceFromHWnd(hWnd);
if (dev)
{
if ((wParam&0xFF)==WA_INACTIVE)
dev->switchToFullScreen(true);
else
dev->switchToFullScreen();
}
break;
case WM_USER:
event.EventType = irr::EET_USER_EVENT;
event.UserEvent.UserData1 = (irr::s32)wParam;
event.UserEvent.UserData2 = (irr::s32)lParam;
dev = getDeviceFromHWnd(hWnd);
if (dev)
dev->postEventFromUser(event);
return 0;
case WM_SETCURSOR:
// because Windows forgot about that in the meantime
dev = getDeviceFromHWnd(hWnd);
if (dev)
dev->getCursorControl()->setVisible( dev->getCursorControl()->isVisible() );
break;
case WM_INPUTLANGCHANGE:
// get the new codepage used for keyboard input
KEYBOARD_INPUT_HKL = GetKeyboardLayout(0);
KEYBOARD_INPUT_CODEPAGE = LocaleIdToCodepage( LOWORD(KEYBOARD_INPUT_HKL) );
- return 0;
+ return 0;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
namespace irr
{
//! constructor
CIrrDeviceWin32::CIrrDeviceWin32(const SIrrlichtCreationParameters& params)
: CIrrDeviceStub(params), HWnd(0), ChangedToFullScreen(false),
IsNonNTWindows(false), Resized(false),
ExternalWindow(false), Win32CursorControl(0)
{
#ifdef _DEBUG
setDebugName("CIrrDeviceWin32");
#endif
// get windows version and create OS operator
core::stringc winversion;
getWindowsVersion(winversion);
Operator = new COSOperator(winversion.c_str());
os::Printer::log(winversion.c_str(), ELL_INFORMATION);
// get handle to exe file
HINSTANCE hInstance = GetModuleHandle(0);
// create the window if we need to and we do not use the null device
if (!CreationParams.WindowId && CreationParams.DriverType != video::EDT_NULL)
{
const fschar_t* ClassName = __TEXT("CIrrDeviceWin32");
// Register Class
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = NULL;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = 0;
wcex.lpszClassName = ClassName;
wcex.hIconSm = 0;
// if there is an icon, load it
wcex.hIcon = (HICON)LoadImage(hInstance, __TEXT("irrlicht.ico"), IMAGE_ICON, 0,0, LR_LOADFROMFILE);
RegisterClassEx(&wcex);
// calculate client size
RECT clientSize;
clientSize.top = 0;
clientSize.left = 0;
clientSize.right = CreationParams.WindowSize.Width;
clientSize.bottom = CreationParams.WindowSize.Height;
DWORD style = WS_POPUP;
if (!CreationParams.Fullscreen)
style = WS_SYSMENU | WS_BORDER | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
AdjustWindowRect(&clientSize, style, FALSE);
const s32 realWidth = clientSize.right - clientSize.left;
const s32 realHeight = clientSize.bottom - clientSize.top;
s32 windowLeft = (GetSystemMetrics(SM_CXSCREEN) - realWidth) / 2;
s32 windowTop = (GetSystemMetrics(SM_CYSCREEN) - realHeight) / 2;
if ( windowLeft < 0 )
windowLeft = 0;
if ( windowTop < 0 )
windowTop = 0; // make sure window menus are in screen on creation
if (CreationParams.Fullscreen)
{
windowLeft = 0;
windowTop = 0;
}
// create window
HWnd = CreateWindow( ClassName, __TEXT(""), style, windowLeft, windowTop,
realWidth, realHeight, NULL, NULL, hInstance, NULL);
CreationParams.WindowId = HWnd;
ShowWindow(HWnd, SW_SHOW);
UpdateWindow(HWnd);
// fix ugly ATI driver bugs. Thanks to ariaci
MoveWindow(HWnd, windowLeft, windowTop, realWidth, realHeight, TRUE);
// make sure everything gets updated to the real sizes
- Resized = true;
+ Resized = true;
}
else if (CreationParams.WindowId)
{
// attach external window
HWnd = static_cast<HWND>(CreationParams.WindowId);
RECT r;
GetWindowRect(HWnd, &r);
CreationParams.WindowSize.Width = r.right - r.left;
CreationParams.WindowSize.Height = r.bottom - r.top;
CreationParams.Fullscreen = false;
ExternalWindow = true;
}
// create cursor control
Win32CursorControl = new CCursorControl(CreationParams.WindowSize, HWnd, CreationParams.Fullscreen);
CursorControl = Win32CursorControl;
// initialize doubleclicks with system values
MouseMultiClicks.DoubleClickTime = GetDoubleClickTime();
// create driver
createDriver();
if (VideoDriver)
createGUIAndScene();
// register environment
SEnvMapper em;
em.irrDev = this;
em.hWnd = HWnd;
EnvMap.push_back(em);
// set this as active window
SetActiveWindow(HWnd);
SetForegroundWindow(HWnd);
// get the codepage used for keyboard input
KEYBOARD_INPUT_HKL = GetKeyboardLayout(0);
- KEYBOARD_INPUT_CODEPAGE = LocaleIdToCodepage( LOWORD(KEYBOARD_INPUT_HKL) );
+ KEYBOARD_INPUT_CODEPAGE = LocaleIdToCodepage( LOWORD(KEYBOARD_INPUT_HKL) );
}
//! destructor
CIrrDeviceWin32::~CIrrDeviceWin32()
{
// unregister environment
irr::core::list<SEnvMapper>::Iterator it = EnvMap.begin();
for (; it!= EnvMap.end(); ++it)
{
if ((*it).hWnd == HWnd)
{
EnvMap.erase(it);
break;
}
}
switchToFullScreen(true);
}
//! create the driver
void CIrrDeviceWin32::createDriver()
{
switch(CreationParams.DriverType)
{
case video::EDT_DIRECT3D8:
#ifdef _IRR_COMPILE_WITH_DIRECT3D_8_
VideoDriver = video::createDirectX8Driver(CreationParams.WindowSize, HWnd,
CreationParams.Bits, CreationParams.Fullscreen, CreationParams.Stencilbuffer,
FileSystem, false, CreationParams.HighPrecisionFPU, CreationParams.Vsync,
CreationParams.AntiAlias);
if (!VideoDriver)
{
os::Printer::log("Could not create DIRECT3D8 Driver.", ELL_ERROR);
}
#else
os::Printer::log("DIRECT3D8 Driver was not compiled into this dll. Try another one.", ELL_ERROR);
#endif // _IRR_COMPILE_WITH_DIRECT3D_8_
break;
case video::EDT_DIRECT3D9:
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
VideoDriver = video::createDirectX9Driver(CreationParams.WindowSize, HWnd,
CreationParams.Bits, CreationParams.Fullscreen, CreationParams.Stencilbuffer,
FileSystem, false, CreationParams.HighPrecisionFPU, CreationParams.Vsync,
CreationParams.AntiAlias);
if (!VideoDriver)
{
os::Printer::log("Could not create DIRECT3D9 Driver.", ELL_ERROR);
}
#else
os::Printer::log("DIRECT3D9 Driver was not compiled into this dll. Try another one.", ELL_ERROR);
#endif // _IRR_COMPILE_WITH_DIRECT3D_9_
break;
case video::EDT_OPENGL:
#ifdef _IRR_COMPILE_WITH_OPENGL_
switchToFullScreen();
VideoDriver = video::createOpenGLDriver(CreationParams, FileSystem, this);
if (!VideoDriver)
{
os::Printer::log("Could not create OpenGL driver.", ELL_ERROR);
}
#else
os::Printer::log("OpenGL driver was not compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_SOFTWARE:
#ifdef _IRR_COMPILE_WITH_SOFTWARE_
switchToFullScreen();
VideoDriver = video::createSoftwareDriver(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this);
#else
os::Printer::log("Software driver was not compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_BURNINGSVIDEO:
#ifdef _IRR_COMPILE_WITH_BURNINGSVIDEO_
switchToFullScreen();
VideoDriver = video::createSoftwareDriver2(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this);
#else
os::Printer::log("Burning's Video driver was not compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_NULL:
// create null driver
VideoDriver = video::createNullDriver(FileSystem, CreationParams.WindowSize);
break;
default:
os::Printer::log("Unable to create video driver of unknown type.", ELL_ERROR);
break;
}
}
//! runs the device. Returns false if device wants to be deleted
bool CIrrDeviceWin32::run()
{
os::Timer::tick();
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// No message translation because we don't use WM_CHAR and it would conflict with our
// deadkey handling.
if (ExternalWindow && msg.hwnd == HWnd)
WndProc(HWnd, msg.message, msg.wParam, msg.lParam);
else
DispatchMessage(&msg);
if (msg.message == WM_QUIT)
Close = true;
}
if (!Close)
resizeIfNecessary();
if(!Close)
pollJoysticks();
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return !Close;
}
//! Pause the current process for the minimum time allowed only to allow other processes to execute
void CIrrDeviceWin32::yield()
{
Sleep(1);
}
//! Pause execution and let other processes to run for a specified amount of time.
void CIrrDeviceWin32::sleep(u32 timeMs, bool pauseTimer)
{
const bool wasStopped = Timer ? Timer->isStopped() : true;
if (pauseTimer && !wasStopped)
Timer->stop();
Sleep(timeMs);
if (pauseTimer && !wasStopped)
Timer->start();
}
void CIrrDeviceWin32::resizeIfNecessary()
{
if (!Resized)
return;
RECT r;
GetClientRect(HWnd, &r);
char tmp[255];
if (r.right < 2 || r.bottom < 2)
{
sprintf(tmp, "Ignoring resize operation to (%ld %ld)", r.right, r.bottom);
os::Printer::log(tmp);
}
else
{
sprintf(tmp, "Resizing window (%ld %ld)", r.right, r.bottom);
os::Printer::log(tmp);
getVideoDriver()->OnResize(irr::core::dimension2du((u32)r.right, (u32)r.bottom));
getWin32CursorControl()->OnResize(getVideoDriver()->getScreenSize());
}
Resized = false;
}
//! sets the caption of the window
void CIrrDeviceWin32::setWindowCaption(const wchar_t* text)
{
DWORD dwResult;
if (IsNonNTWindows)
{
const core::stringc s = text;
#if defined(_WIN64) || defined(WIN64)
SetWindowTextA(HWnd, s.c_str());
#else
SendMessageTimeout(HWnd, WM_SETTEXT, 0,
reinterpret_cast<LPARAM>(s.c_str()),
SMTO_ABORTIFHUNG, 2000, &dwResult);
#endif
}
else
{
#if defined(_WIN64) || defined(WIN64)
SetWindowTextW(HWnd, text);
#else
SendMessageTimeoutW(HWnd, WM_SETTEXT, 0,
reinterpret_cast<LPARAM>(text),
SMTO_ABORTIFHUNG, 2000, &dwResult);
#endif
}
}
//! presents a surface in the client area
bool CIrrDeviceWin32::present(video::IImage* image, void* windowId, core::rect<s32>* src)
{
HWND hwnd = HWnd;
if ( windowId )
hwnd = reinterpret_cast<HWND>(windowId);
HDC dc = GetDC(hwnd);
if ( dc )
{
RECT rect;
GetClientRect(hwnd, &rect);
const void* memory = (const void *)image->lock();
BITMAPV4HEADER bi;
ZeroMemory (&bi, sizeof(bi));
bi.bV4Size = sizeof(BITMAPINFOHEADER);
bi.bV4BitCount = (WORD)image->getBitsPerPixel();
bi.bV4Planes = 1;
bi.bV4Width = image->getDimension().Width;
bi.bV4Height = -((s32)image->getDimension().Height);
bi.bV4V4Compression = BI_BITFIELDS;
bi.bV4AlphaMask = image->getAlphaMask();
bi.bV4RedMask = image->getRedMask();
bi.bV4GreenMask = image->getGreenMask();
bi.bV4BlueMask = image->getBlueMask();
if ( src )
{
StretchDIBits(dc, 0,0, rect.right, rect.bottom,
src->UpperLeftCorner.X, src->UpperLeftCorner.Y,
src->getWidth(), src->getHeight(),
memory, (const BITMAPINFO*)(&bi), DIB_RGB_COLORS, SRCCOPY);
}
else
{
StretchDIBits(dc, 0,0, rect.right, rect.bottom,
0, 0, image->getDimension().Width, image->getDimension().Height,
memory, (const BITMAPINFO*)(&bi), DIB_RGB_COLORS, SRCCOPY);
}
image->unlock();
ReleaseDC(hwnd, dc);
}
return true;
}
//! notifies the device that it should close itself
void CIrrDeviceWin32::closeDevice()
{
MSG msg;
PeekMessage(&msg, NULL, WM_QUIT, WM_QUIT, PM_REMOVE);
PostQuitMessage(0);
PeekMessage(&msg, NULL, WM_QUIT, WM_QUIT, PM_REMOVE);
DestroyWindow(HWnd);
Close=true;
}
//! returns if window is active. if not, nothing needs to be drawn
bool CIrrDeviceWin32::isWindowActive() const
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return (GetActiveWindow() == HWnd);
}
//! returns if window has focus
bool CIrrDeviceWin32::isWindowFocused() const
{
bool ret = (GetFocus() == HWnd);
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return ret;
}
//! returns if window is minimized
bool CIrrDeviceWin32::isWindowMinimized() const
{
WINDOWPLACEMENT plc;
plc.length=sizeof(WINDOWPLACEMENT);
bool ret=false;
if (GetWindowPlacement(HWnd,&plc))
ret=(plc.showCmd & SW_SHOWMINIMIZED)!=0;
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return ret;
}
//! switches to fullscreen
bool CIrrDeviceWin32::switchToFullScreen(bool reset)
{
if (!CreationParams.Fullscreen)
return true;
if (reset)
{
if (ChangedToFullScreen)
return (ChangeDisplaySettings(NULL,0)==DISP_CHANGE_SUCCESSFUL);
else
return true;
}
DEVMODE dm;
memset(&dm, 0, sizeof(dm));
dm.dmSize = sizeof(dm);
// use default values from current setting
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
dm.dmPelsWidth = CreationParams.WindowSize.Width;
dm.dmPelsHeight = CreationParams.WindowSize.Height;
dm.dmBitsPerPel = CreationParams.Bits;
dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY;
LONG res = ChangeDisplaySettings(&dm, CDS_FULLSCREEN);
if (res != DISP_CHANGE_SUCCESSFUL)
{ // try again without forcing display frequency
dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
res = ChangeDisplaySettings(&dm, CDS_FULLSCREEN);
}
bool ret = false;
switch(res)
{
case DISP_CHANGE_SUCCESSFUL:
ChangedToFullScreen = true;
ret = true;
break;
case DISP_CHANGE_RESTART:
os::Printer::log("Switch to fullscreen: The computer must be restarted in order for the graphics mode to work.", ELL_ERROR);
break;
case DISP_CHANGE_BADFLAGS:
os::Printer::log("Switch to fullscreen: An invalid set of flags was passed in.", ELL_ERROR);
break;
case DISP_CHANGE_BADPARAM:
os::Printer::log("Switch to fullscreen: An invalid parameter was passed in. This can include an invalid flag or combination of flags.", ELL_ERROR);
break;
case DISP_CHANGE_FAILED:
os::Printer::log("Switch to fullscreen: The display driver failed the specified graphics mode.", ELL_ERROR);
break;
case DISP_CHANGE_BADMODE:
os::Printer::log("Switch to fullscreen: The graphics mode is not supported.", ELL_ERROR);
break;
default:
os::Printer::log("An unknown error occured while changing to fullscreen.", ELL_ERROR);
break;
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return ret;
}
//! returns the win32 cursor control
CIrrDeviceWin32::CCursorControl* CIrrDeviceWin32::getWin32CursorControl()
{
return Win32CursorControl;
}
//! \return Returns a pointer to a list with all video modes supported
//! by the gfx adapter.
video::IVideoModeList* CIrrDeviceWin32::getVideoModeList()
{
if (!VideoModeList.getVideoModeCount())
{
// enumerate video modes.
DWORD i=0;
DEVMODE mode;
memset(&mode, 0, sizeof(mode));
mode.dmSize = sizeof(mode);
while (EnumDisplaySettings(NULL, i, &mode))
{
VideoModeList.addMode(core::dimension2d<u32>(mode.dmPelsWidth, mode.dmPelsHeight),
mode.dmBitsPerPel);
++i;
}
if (EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &mode))
VideoModeList.setDesktop(mode.dmBitsPerPel, core::dimension2d<u32>(mode.dmPelsWidth, mode.dmPelsHeight));
}
return &VideoModeList;
}
+typedef BOOL (WINAPI *PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD);
+// Needed for old windows apis
+#define PRODUCT_ULTIMATE 0x00000001
+#define PRODUCT_HOME_BASIC 0x00000002
+#define PRODUCT_HOME_PREMIUM 0x00000003
+#define PRODUCT_ENTERPRISE 0x00000004
+#define PRODUCT_HOME_BASIC_N 0x00000005
+#define PRODUCT_BUSINESS 0x00000006
+#define PRODUCT_STARTER 0x0000000B
+#define PRODUCT_BUSINESS_N 0x00000010
+#define PRODUCT_HOME_PREMIUM_N 0x0000001A
+#define PRODUCT_ENTERPRISE_N 0x0000001B
+#define PRODUCT_ULTIMATE_N 0x0000001C
+#define PRODUCT_STARTER_N 0x0000002F
+#define PRODUCT_PROFESSIONAL 0x00000030
+#define PRODUCT_PROFESSIONAL_N 0x00000031
+#define PRODUCT_STARTER_E 0x00000042
+#define PRODUCT_HOME_BASIC_E 0x00000043
+#define PRODUCT_HOME_PREMIUM_E 0x00000044
+#define PRODUCT_PROFESSIONAL_E 0x00000045
+#define PRODUCT_ENTERPRISE_E 0x00000046
+#define PRODUCT_ULTIMATE_E 0x00000047
void CIrrDeviceWin32::getWindowsVersion(core::stringc& out)
{
- OSVERSIONINFOEX osvi;
- BOOL bOsVersionInfoEx;
-
- ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
- osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
+ OSVERSIONINFOEX osvi;
+ PGPI pGPI;
+ BOOL bOsVersionInfoEx;
- bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO*) &osvi);
- if (!bOsVersionInfoEx)
- {
- osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
- if (! GetVersionEx((OSVERSIONINFO *) &osvi))
- return;
- }
+ ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
+ osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
- switch (osvi.dwPlatformId)
- {
- case VER_PLATFORM_WIN32_NT:
- if (osvi.dwMajorVersion <= 4)
- out.append("Microsoft Windows NT ");
- else
- if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
- out.append("Microsoft Windows 2000 ");
- else
- if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
- out.append("Microsoft Windows XP ");
- else
- if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
- out.append("Microsoft Windows Vista ");
+ bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO*) &osvi);
+ if (!bOsVersionInfoEx)
+ {
+ osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+ if (! GetVersionEx((OSVERSIONINFO *) &osvi))
+ return;
+ }
- if (bOsVersionInfoEx)
- {
- #ifdef VER_SUITE_ENTERPRISE
- if (osvi.wProductType == VER_NT_WORKSTATION)
- {
+ switch (osvi.dwPlatformId)
+ {
+ case VER_PLATFORM_WIN32_NT:
+ if (osvi.dwMajorVersion <= 4)
+ out.append("Microsoft Windows NT ");
+ else
+ if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
+ out.append("Microsoft Windows 2000 ");
+ else
+ if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
+ out.append("Microsoft Windows XP ");
+ else
+ if (osvi.dwMajorVersion == 6 )
+ {
+ if (osvi.dwMinorVersion == 0)
+ {
+ if (osvi.wProductType == VER_NT_WORKSTATION)
+ out.append("Microsoft Windows Vista ");
+ else
+ out.append("Microsoft Windows Server 2008 ");
+ }
+ else if (osvi.dwMinorVersion == 1)
+ {
+ if (osvi.wProductType == VER_NT_WORKSTATION)
+ out.append("Microsoft Windows 7 ");
+ else
+ out.append("Microsoft Windows Server 2008 R2 ");
+ }
+ }
+
+ if (bOsVersionInfoEx)
+ {
+ if (osvi.dwMajorVersion == 6)
+ {
+ DWORD dwType;
+ pGPI = (PGPI)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetProductInfo");
+ pGPI(osvi.dwMajorVersion, osvi.dwMinorVersion, 0, 0, &dwType);
+
+ switch (dwType)
+ {
+ case PRODUCT_ULTIMATE:
+ case PRODUCT_ULTIMATE_E:
+ case PRODUCT_ULTIMATE_N:
+ out.append("Ultimate Edition ");
+ break;
+ case PRODUCT_PROFESSIONAL:
+ case PRODUCT_PROFESSIONAL_E:
+ case PRODUCT_PROFESSIONAL_N:
+ out.append("Professional Edition ");
+ break;
+ case PRODUCT_HOME_BASIC:
+ case PRODUCT_HOME_BASIC_E:
+ case PRODUCT_HOME_BASIC_N:
+ out.append("Home Basic Edition ");
+ break;
+ case PRODUCT_HOME_PREMIUM:
+ case PRODUCT_HOME_PREMIUM_E:
+ case PRODUCT_HOME_PREMIUM_N:
+ out.append("Home Premium Edition ");
+ break;
+ case PRODUCT_ENTERPRISE:
+ case PRODUCT_ENTERPRISE_E:
+ case PRODUCT_ENTERPRISE_N:
+ out.append("Enterprise Edition ");
+ break;
+ case PRODUCT_BUSINESS:
+ case PRODUCT_BUSINESS_N:
+ out.append("Business Edition ");
+ break;
+ case PRODUCT_STARTER:
+ case PRODUCT_STARTER_E:
+ case PRODUCT_STARTER_N:
+ out.append("Starter Edition ");
+ break;
+ }
+ }
+#ifdef VER_SUITE_ENTERPRISE
+ else
+ if (osvi.wProductType == VER_NT_WORKSTATION)
+ {
#ifndef __BORLANDC__
- if( osvi.wSuiteMask & VER_SUITE_PERSONAL )
- out.append("Personal ");
- else
- out.append("Professional ");
+ if( osvi.wSuiteMask & VER_SUITE_PERSONAL )
+ out.append("Personal ");
+ else
+ out.append("Professional ");
#endif
- }
- else if (osvi.wProductType == VER_NT_SERVER)
- {
- if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
- out.append("DataCenter Server ");
- else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
- out.append("Advanced Server ");
- else
- out.append("Server ");
- }
- #endif
- }
- else
- {
- HKEY hKey;
- char szProductType[80];
- DWORD dwBufLen;
-
- RegOpenKeyEx( HKEY_LOCAL_MACHINE,
- __TEXT("SYSTEM\\CurrentControlSet\\Control\\ProductOptions"),
- 0, KEY_QUERY_VALUE, &hKey );
- RegQueryValueEx( hKey, __TEXT("ProductType"), NULL, NULL,
- (LPBYTE) szProductType, &dwBufLen);
- RegCloseKey( hKey );
-
- if (_strcmpi( "WINNT", szProductType) == 0 )
- out.append("Professional ");
- if (_strcmpi( "LANMANNT", szProductType) == 0)
- out.append("Server ");
- if (_strcmpi( "SERVERNT", szProductType) == 0)
- out.append("Advanced Server ");
- }
-
- // Display version, service pack (if any), and build number.
-
- char tmp[255];
-
- if (osvi.dwMajorVersion <= 4 )
- {
- sprintf(tmp, "version %ld.%ld %s (Build %ld)",
- osvi.dwMajorVersion,
- osvi.dwMinorVersion,
- osvi.szCSDVersion,
- osvi.dwBuildNumber & 0xFFFF);
- }
- else
- {
- sprintf(tmp, "%s (Build %ld)", osvi.szCSDVersion,
- osvi.dwBuildNumber & 0xFFFF);
- }
-
- out.append(tmp);
- break;
-
- case VER_PLATFORM_WIN32_WINDOWS:
-
- IsNonNTWindows = true;
-
- if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
- {
- out.append("Microsoft Windows 95 ");
- if ( osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B' )
- out.append("OSR2 " );
- }
-
- if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
- {
- out.append("Microsoft Windows 98 ");
- if ( osvi.szCSDVersion[1] == 'A' )
- out.append( "SE " );
- }
-
- if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
- out.append("Microsoft Windows Me ");
-
- break;
-
- case VER_PLATFORM_WIN32s:
-
- IsNonNTWindows = true;
- out.append("Microsoft Win32s ");
- break;
- }
+ }
+ else if (osvi.wProductType == VER_NT_SERVER)
+ {
+ if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
+ out.append("DataCenter Server ");
+ else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
+ out.append("Advanced Server ");
+ else
+ out.append("Server ");
+ }
+#endif
+ }
+ else
+ {
+ HKEY hKey;
+ char szProductType[80];
+ DWORD dwBufLen;
+
+ RegOpenKeyEx( HKEY_LOCAL_MACHINE,
+ __TEXT("SYSTEM\\CurrentControlSet\\Control\\ProductOptions"),
+ 0, KEY_QUERY_VALUE, &hKey );
+ RegQueryValueEx( hKey, __TEXT("ProductType"), NULL, NULL,
+ (LPBYTE) szProductType, &dwBufLen);
+ RegCloseKey( hKey );
+
+ if (_strcmpi( "WINNT", szProductType) == 0 )
+ out.append("Professional ");
+ if (_strcmpi( "LANMANNT", szProductType) == 0)
+ out.append("Server ");
+ if (_strcmpi( "SERVERNT", szProductType) == 0)
+ out.append("Advanced Server ");
+ }
+
+ // Display version, service pack (if any), and build number.
+
+ char tmp[255];
+
+ if (osvi.dwMajorVersion <= 4 )
+ {
+ sprintf(tmp, "version %ld.%ld %s (Build %ld)",
+ osvi.dwMajorVersion,
+ osvi.dwMinorVersion,
+ osvi.szCSDVersion,
+ osvi.dwBuildNumber & 0xFFFF);
+ }
+ else
+ {
+ sprintf(tmp, "%s (Build %ld)", osvi.szCSDVersion,
+ osvi.dwBuildNumber & 0xFFFF);
+ }
+
+ out.append(tmp);
+ break;
+
+ case VER_PLATFORM_WIN32_WINDOWS:
+
+ IsNonNTWindows = true;
+
+ if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
+ {
+ out.append("Microsoft Windows 95 ");
+ if ( osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B' )
+ out.append("OSR2 " );
+ }
+
+ if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
+ {
+ out.append("Microsoft Windows 98 ");
+ if ( osvi.szCSDVersion[1] == 'A' )
+ out.append( "SE " );
+ }
+
+ if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
+ out.append("Microsoft Windows Me ");
+
+ break;
+
+ case VER_PLATFORM_WIN32s:
+
+ IsNonNTWindows = true;
+ out.append("Microsoft Win32s ");
+ break;
+ }
}
//! Notifies the device, that it has been resized
void CIrrDeviceWin32::OnResized()
{
Resized = true;
}
//! Sets if the window should be resizable in windowed mode.
void CIrrDeviceWin32::setResizable(bool resize)
{
if (ExternalWindow || !getVideoDriver() || CreationParams.Fullscreen)
return;
LONG_PTR style = WS_POPUP;
if (!resize)
style = WS_SYSMENU | WS_BORDER | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
else
style = WS_THICKFRAME | WS_SYSMENU | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
if (!SetWindowLongPtr(HWnd, GWL_STYLE, style))
os::Printer::log("Could not change window style.");
RECT clientSize;
clientSize.top = 0;
clientSize.left = 0;
clientSize.right = getVideoDriver()->getScreenSize().Width;
clientSize.bottom = getVideoDriver()->getScreenSize().Height;
AdjustWindowRect(&clientSize, style, FALSE);
const s32 realWidth = clientSize.right - clientSize.left;
const s32 realHeight = clientSize.bottom - clientSize.top;
const s32 windowLeft = (GetSystemMetrics(SM_CXSCREEN) - realWidth) / 2;
const s32 windowTop = (GetSystemMetrics(SM_CYSCREEN) - realHeight) / 2;
SetWindowPos(HWnd, HWND_TOP, windowLeft, windowTop, realWidth, realHeight,
SWP_FRAMECHANGED | SWP_NOMOVE | SWP_SHOWWINDOW);
static_cast<CCursorControl*>(CursorControl)->updateBorderSize(CreationParams.Fullscreen, resize);
}
//! Minimizes the window.
void CIrrDeviceWin32::minimizeWindow()
{
WINDOWPLACEMENT wndpl;
wndpl.length = sizeof(WINDOWPLACEMENT);
GetWindowPlacement(HWnd, &wndpl);
wndpl.showCmd = SW_SHOWMINNOACTIVE;
SetWindowPlacement(HWnd, &wndpl);
}
//! Maximizes the window.
void CIrrDeviceWin32::maximizeWindow()
{
WINDOWPLACEMENT wndpl;
wndpl.length = sizeof(WINDOWPLACEMENT);
GetWindowPlacement(HWnd, &wndpl);
wndpl.showCmd = SW_SHOWMAXIMIZED;
SetWindowPlacement(HWnd, &wndpl);
}
//! Restores the window to its original size.
void CIrrDeviceWin32::restoreWindow()
{
WINDOWPLACEMENT wndpl;
wndpl.length = sizeof(WINDOWPLACEMENT);
GetWindowPlacement(HWnd, &wndpl);
wndpl.showCmd = SW_SHOWNORMAL;
SetWindowPlacement(HWnd, &wndpl);
}
bool CIrrDeviceWin32::activateJoysticks(core::array<SJoystickInfo> & joystickInfo)
{
#if defined _IRR_COMPILE_WITH_JOYSTICK_EVENTS_
joystickInfo.clear();
ActiveJoysticks.clear();
const u32 numberOfJoysticks = ::joyGetNumDevs();
JOYINFOEX info;
info.dwSize = sizeof(info);
info.dwFlags = JOY_RETURNALL;
JoystickInfo activeJoystick;
SJoystickInfo returnInfo;
joystickInfo.reallocate(numberOfJoysticks);
ActiveJoysticks.reallocate(numberOfJoysticks);
u32 joystick = 0;
for(; joystick < numberOfJoysticks; ++joystick)
{
if(JOYERR_NOERROR == joyGetPosEx(joystick, &info)
&&
JOYERR_NOERROR == joyGetDevCaps(joystick,
&activeJoystick.Caps,
sizeof(activeJoystick.Caps)))
{
activeJoystick.Index = joystick;
ActiveJoysticks.push_back(activeJoystick);
returnInfo.Joystick = (u8)joystick;
returnInfo.Axes = activeJoystick.Caps.wNumAxes;
returnInfo.Buttons = activeJoystick.Caps.wNumButtons;
returnInfo.Name = activeJoystick.Caps.szPname;
returnInfo.PovHat = ((activeJoystick.Caps.wCaps & JOYCAPS_HASPOV) == JOYCAPS_HASPOV)
? SJoystickInfo::POV_HAT_PRESENT : SJoystickInfo::POV_HAT_ABSENT;
joystickInfo.push_back(returnInfo);
}
}
for(joystick = 0; joystick < joystickInfo.size(); ++joystick)
{
char logString[256];
(void)sprintf(logString, "Found joystick %d, %d axes, %d buttons '%s'",
joystick, joystickInfo[joystick].Axes,
joystickInfo[joystick].Buttons, joystickInfo[joystick].Name.c_str());
os::Printer::log(logString, ELL_INFORMATION);
}
return true;
#else
return false;
#endif // _IRR_COMPILE_WITH_JOYSTICK_EVENTS_
}
void CIrrDeviceWin32::pollJoysticks()
{
#if defined _IRR_COMPILE_WITH_JOYSTICK_EVENTS_
if(0 == ActiveJoysticks.size())
return;
u32 joystick;
JOYINFOEX info;
for(joystick = 0; joystick < ActiveJoysticks.size(); ++joystick)
{
// needs to be reset for each joystick
// request ALL values and POV as continuous if possible
info.dwSize = sizeof(info);
info.dwFlags = JOY_RETURNALL|JOY_RETURNPOVCTS;
const JOYCAPS & caps = ActiveJoysticks[joystick].Caps;
// if no POV is available don't ask for POV values
if (!(caps.wCaps & JOYCAPS_HASPOV))
info.dwFlags &= ~(JOY_RETURNPOV|JOY_RETURNPOVCTS);
if(JOYERR_NOERROR == joyGetPosEx(ActiveJoysticks[joystick].Index, &info))
{
SEvent event;
event.EventType = irr::EET_JOYSTICK_INPUT_EVENT;
event.JoystickEvent.Joystick = (u8)joystick;
-
+
event.JoystickEvent.POV = (u16)info.dwPOV;
// set to undefined if no POV value was returned or the value
// is out of range
if (!(info.dwFlags & JOY_RETURNPOV) || (event.JoystickEvent.POV > 35900))
event.JoystickEvent.POV = 65535;
for(int axis = 0; axis < SEvent::SJoystickEvent::NUMBER_OF_AXES; ++axis)
event.JoystickEvent.Axis[axis] = 0;
switch(caps.wNumAxes)
{
default:
case 6:
event.JoystickEvent.Axis[SEvent::SJoystickEvent::AXIS_V] =
(s16)((65535 * (info.dwVpos - caps.wVmin)) / (caps.wVmax - caps.wVmin) - 32768);
case 5:
event.JoystickEvent.Axis[SEvent::SJoystickEvent::AXIS_U] =
(s16)((65535 * (info.dwUpos - caps.wUmin)) / (caps.wUmax - caps.wUmin) - 32768);
case 4:
event.JoystickEvent.Axis[SEvent::SJoystickEvent::AXIS_R] =
(s16)((65535 * (info.dwRpos - caps.wRmin)) / (caps.wRmax - caps.wRmin) - 32768);
case 3:
event.JoystickEvent.Axis[SEvent::SJoystickEvent::AXIS_Z] =
(s16)((65535 * (info.dwZpos - caps.wZmin)) / (caps.wZmax - caps.wZmin) - 32768);
case 2:
event.JoystickEvent.Axis[SEvent::SJoystickEvent::AXIS_Y] =
(s16)((65535 * (info.dwYpos - caps.wYmin)) / (caps.wYmax - caps.wYmin) - 32768);
case 1:
event.JoystickEvent.Axis[SEvent::SJoystickEvent::AXIS_X] =
(s16)((65535 * (info.dwXpos - caps.wXmin)) / (caps.wXmax - caps.wXmin) - 32768);
}
event.JoystickEvent.ButtonStates = info.dwButtons;
(void)postEventFromUser(event);
}
}
#endif // _IRR_COMPILE_WITH_JOYSTICK_EVENTS_
}
//! Set the current Gamma Value for the Display
bool CIrrDeviceWin32::setGammaRamp( f32 red, f32 green, f32 blue, f32 brightness, f32 contrast )
{
bool r;
u16 ramp[3][256];
calculateGammaRamp( ramp[0], red, brightness, contrast );
calculateGammaRamp( ramp[1], green, brightness, contrast );
calculateGammaRamp( ramp[2], blue, brightness, contrast );
HDC dc = GetDC(0);
r = SetDeviceGammaRamp ( dc, ramp ) == TRUE;
ReleaseDC(HWnd, dc);
return r;
}
//! Get the current Gamma Value for the Display
bool CIrrDeviceWin32::getGammaRamp( f32 &red, f32 &green, f32 &blue, f32 &brightness, f32 &contrast )
{
bool r;
u16 ramp[3][256];
HDC dc = GetDC(0);
r = GetDeviceGammaRamp ( dc, ramp ) == TRUE;
ReleaseDC(HWnd, dc);
if ( r )
{
calculateGammaFromRamp(red, ramp[0]);
calculateGammaFromRamp(green, ramp[1]);
calculateGammaFromRamp(blue, ramp[2]);
}
brightness = 0.f;
contrast = 0.f;
return r;
}
//! Remove all messages pending in the system message loop
void CIrrDeviceWin32::clearSystemMessages()
{
MSG msg;
while (PeekMessage(&msg, NULL, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE))
{}
while (PeekMessage(&msg, NULL, WM_MOUSEFIRST, WM_MOUSELAST, PM_REMOVE))
{}
}
// shows last error in a messagebox to help internal debugging.
void CIrrDeviceWin32::ReportLastWinApiError()
{
// (based on code from ovidiucucu from http://www.codeguru.com/forum/showthread.php?t=318721)
LPCTSTR pszCaption = __TEXT("Windows SDK Error Report");
DWORD dwError = GetLastError();
if(NOERROR == dwError)
{
MessageBox(NULL, __TEXT("No error"), pszCaption, MB_OK);
}
else
{
const DWORD dwFormatControl = FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM;
LPVOID pTextBuffer = NULL;
DWORD dwCount = FormatMessage(dwFormatControl,
NULL,
dwError,
0,
(LPTSTR) &pTextBuffer,
0,
NULL);
if(0 != dwCount)
{
MessageBox(NULL, (LPCTSTR)pTextBuffer, pszCaption, MB_OK|MB_ICONERROR);
LocalFree(pTextBuffer);
}
else
{
MessageBox(NULL, __TEXT("Unknown error"), pszCaption, MB_OK|MB_ICONERROR);
}
}
}
} // end namespace
#endif // _IRR_COMPILE_WITH_WINDOWS_DEVICE_
|
paupawsan/Irrlicht
|
aa53475d5eb96326244ac22700069dc86b252266
|
Fix compiling on Borland compilers (thx to mdeininger for help). By now everything except the console device should compile.
|
diff --git a/include/irrMath.h b/include/irrMath.h
index 3d75641..5a1125b 100644
--- a/include/irrMath.h
+++ b/include/irrMath.h
@@ -1,539 +1,539 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __IRR_MATH_H_INCLUDED__
#define __IRR_MATH_H_INCLUDED__
#include "IrrCompileConfig.h"
#include "irrTypes.h"
#include <math.h>
#include <float.h>
#include <stdlib.h> // for abs() etc.
#include <limits.h> // For INT_MAX / UINT_MAX
#if defined(_IRR_SOLARIS_PLATFORM_) || defined(__BORLANDC__) || defined (__BCPLUSPLUS__) || defined (_WIN32_WCE)
- #define sqrtf(X) (f32)sqrt((f64)(X))
- #define sinf(X) (f32)sin((f64)(X))
- #define cosf(X) (f32)cos((f64)(X))
- #define asinf(X) (f32)asin((f64)(X))
- #define acosf(X) (f32)acos((f64)(X))
- #define atan2f(X,Y) (f32)atan2((f64)(X),(f64)(Y))
- #define ceilf(X) (f32)ceil((f64)(X))
- #define floorf(X) (f32)floor((f64)(X))
- #define powf(X,Y) (f32)pow((f64)(X),(f64)(Y))
- #define fmodf(X,Y) (f32)fmod((f64)(X),(f64)(Y))
- #define fabsf(X) (f32)fabs((f64)(X))
- #define logf(X) (f32)log((f64)(X))
+ #define sqrtf(X) (irr::f32)sqrt((irr::f64)(X))
+ #define sinf(X) (irr::f32)sin((irr::f64)(X))
+ #define cosf(X) (irr::f32)cos((irr::f64)(X))
+ #define asinf(X) (irr::f32)asin((irr::f64)(X))
+ #define acosf(X) (irr::f32)acos((irr::f64)(X))
+ #define atan2f(X,Y) (irr::f32)atan2((irr::f64)(X),(irr::f64)(Y))
+ #define ceilf(X) (irr::f32)ceil((irr::f64)(X))
+ #define floorf(X) (irr::f32)floor((irr::f64)(X))
+ #define powf(X,Y) (irr::f32)pow((irr::f64)(X),(irr::f64)(Y))
+ #define fmodf(X,Y) (irr::f32)fmod((irr::f64)(X),(irr::f64)(Y))
+ #define fabsf(X) (irr::f32)fabs((irr::f64)(X))
+ #define logf(X) (irr::f32)log((irr::f64)(X))
#endif
#ifndef FLT_MAX
#define FLT_MAX 3.402823466E+38F
#endif
namespace irr
{
namespace core
{
//! Rounding error constant often used when comparing f32 values.
const s32 ROUNDING_ERROR_S32 = 0;
const f32 ROUNDING_ERROR_f32 = 0.000001f;
const f64 ROUNDING_ERROR_f64 = 0.00000001;
#ifdef PI // make sure we don't collide with a define
#undef PI
#endif
//! Constant for PI.
const f32 PI = 3.14159265359f;
//! Constant for reciprocal of PI.
const f32 RECIPROCAL_PI = 1.0f/PI;
//! Constant for half of PI.
const f32 HALF_PI = PI/2.0f;
#ifdef PI64 // make sure we don't collide with a define
#undef PI64
#endif
//! Constant for 64bit PI.
const f64 PI64 = 3.1415926535897932384626433832795028841971693993751;
//! Constant for 64bit reciprocal of PI.
const f64 RECIPROCAL_PI64 = 1.0/PI64;
//! 32bit Constant for converting from degrees to radians
const f32 DEGTORAD = PI / 180.0f;
//! 32bit constant for converting from radians to degrees (formally known as GRAD_PI)
const f32 RADTODEG = 180.0f / PI;
//! 64bit constant for converting from degrees to radians (formally known as GRAD_PI2)
const f64 DEGTORAD64 = PI64 / 180.0;
//! 64bit constant for converting from radians to degrees
const f64 RADTODEG64 = 180.0 / PI64;
//! Utility function to convert a radian value to degrees
/** Provided as it can be clearer to write radToDeg(X) than RADTODEG * X
\param radians The radians value to convert to degrees.
*/
inline f32 radToDeg(f32 radians)
{
return RADTODEG * radians;
}
//! Utility function to convert a radian value to degrees
/** Provided as it can be clearer to write radToDeg(X) than RADTODEG * X
\param radians The radians value to convert to degrees.
*/
inline f64 radToDeg(f64 radians)
{
return RADTODEG64 * radians;
}
//! Utility function to convert a degrees value to radians
/** Provided as it can be clearer to write degToRad(X) than DEGTORAD * X
\param degrees The degrees value to convert to radians.
*/
inline f32 degToRad(f32 degrees)
{
return DEGTORAD * degrees;
}
//! Utility function to convert a degrees value to radians
/** Provided as it can be clearer to write degToRad(X) than DEGTORAD * X
\param degrees The degrees value to convert to radians.
*/
inline f64 degToRad(f64 degrees)
{
return DEGTORAD64 * degrees;
}
//! returns minimum of two values. Own implementation to get rid of the STL (VS6 problems)
template<class T>
inline const T& min_(const T& a, const T& b)
{
return a < b ? a : b;
}
//! returns minimum of three values. Own implementation to get rid of the STL (VS6 problems)
template<class T>
inline const T& min_(const T& a, const T& b, const T& c)
{
return a < b ? min_(a, c) : min_(b, c);
}
//! returns maximum of two values. Own implementation to get rid of the STL (VS6 problems)
template<class T>
inline const T& max_(const T& a, const T& b)
{
return a < b ? b : a;
}
//! returns maximum of three values. Own implementation to get rid of the STL (VS6 problems)
template<class T>
inline const T& max_(const T& a, const T& b, const T& c)
{
return a < b ? max_(b, c) : max_(a, c);
}
//! returns abs of two values. Own implementation to get rid of STL (VS6 problems)
template<class T>
inline T abs_(const T& a)
{
return a < (T)0 ? -a : a;
}
//! returns linear interpolation of a and b with ratio t
//! \return: a if t==0, b if t==1, and the linear interpolation else
template<class T>
inline T lerp(const T& a, const T& b, const f32 t)
{
return (T)(a*(1.f-t)) + (b*t);
}
//! clamps a value between low and high
template <class T>
inline const T clamp (const T& value, const T& low, const T& high)
{
return min_ (max_(value,low), high);
}
//! swaps the content of the passed parameters
template <class T>
inline void swap(T& a, T& b)
{
T c(a);
a = b;
b = c;
}
//! returns if a equals b, taking possible rounding errors into account
inline bool equals(const f64 a, const f64 b, const f64 tolerance = ROUNDING_ERROR_f64)
{
return (a + tolerance >= b) && (a - tolerance <= b);
}
//! returns if a equals b, taking possible rounding errors into account
inline bool equals(const f32 a, const f32 b, const f32 tolerance = ROUNDING_ERROR_f32)
{
return (a + tolerance >= b) && (a - tolerance <= b);
}
#if 0
//! returns if a equals b, not using any rounding tolerance
inline bool equals(const s32 a, const s32 b)
{
return (a == b);
}
//! returns if a equals b, not using any rounding tolerance
inline bool equals(const u32 a, const u32 b)
{
return (a == b);
}
#endif
//! returns if a equals b, taking an explicit rounding tolerance into account
inline bool equals(const s32 a, const s32 b, const s32 tolerance = ROUNDING_ERROR_S32)
{
return (a + tolerance >= b) && (a - tolerance <= b);
}
//! returns if a equals b, taking an explicit rounding tolerance into account
inline bool equals(const u32 a, const u32 b, const s32 tolerance = ROUNDING_ERROR_S32)
{
return (a + tolerance >= b) && (a - tolerance <= b);
}
//! returns if a equals zero, taking rounding errors into account
inline bool iszero(const f64 a, const f64 tolerance = ROUNDING_ERROR_f64)
{
return fabs(a) <= tolerance;
}
//! returns if a equals zero, taking rounding errors into account
inline bool iszero(const f32 a, const f32 tolerance = ROUNDING_ERROR_f32)
{
return fabsf(a) <= tolerance;
}
//! returns if a equals not zero, taking rounding errors into account
inline bool isnotzero(const f32 a, const f32 tolerance = ROUNDING_ERROR_f32)
{
return fabsf(a) > tolerance;
}
//! returns if a equals zero, taking rounding errors into account
inline bool iszero(const s32 a, const s32 tolerance = 0)
{
return ( a & 0x7ffffff ) <= tolerance;
}
//! returns if a equals zero, taking rounding errors into account
inline bool iszero(const u32 a, const u32 tolerance = 0)
{
return a <= tolerance;
}
inline s32 s32_min(s32 a, s32 b)
{
const s32 mask = (a - b) >> 31;
return (a & mask) | (b & ~mask);
}
inline s32 s32_max(s32 a, s32 b)
{
const s32 mask = (a - b) >> 31;
return (b & mask) | (a & ~mask);
}
inline s32 s32_clamp (s32 value, s32 low, s32 high)
{
return s32_min(s32_max(value,low), high);
}
/*
float IEEE-754 bit represenation
0 0x00000000
1.0 0x3f800000
0.5 0x3f000000
3 0x40400000
+inf 0x7f800000
-inf 0xff800000
+NaN 0x7fc00000 or 0x7ff00000
in general: number = (sign ? -1:1) * 2^(exponent) * 1.(mantissa bits)
*/
typedef union { u32 u; s32 s; f32 f; } inttofloat;
#define F32_AS_S32(f) (*((s32 *) &(f)))
#define F32_AS_U32(f) (*((u32 *) &(f)))
#define F32_AS_U32_POINTER(f) ( ((u32 *) &(f)))
#define F32_VALUE_0 0x00000000
#define F32_VALUE_1 0x3f800000
#define F32_SIGN_BIT 0x80000000U
#define F32_EXPON_MANTISSA 0x7FFFFFFFU
//! code is taken from IceFPU
//! Integer representation of a floating-point value.
#ifdef IRRLICHT_FAST_MATH
#define IR(x) ((u32&)(x))
#else
inline u32 IR(f32 x) {inttofloat tmp; tmp.f=x; return tmp.u;}
#endif
//! Absolute integer representation of a floating-point value
#define AIR(x) (IR(x)&0x7fffffff)
//! Floating-point representation of an integer value.
#ifdef IRRLICHT_FAST_MATH
#define FR(x) ((f32&)(x))
#else
inline f32 FR(u32 x) {inttofloat tmp; tmp.u=x; return tmp.f;}
inline f32 FR(s32 x) {inttofloat tmp; tmp.s=x; return tmp.f;}
#endif
//! integer representation of 1.0
#define IEEE_1_0 0x3f800000
//! integer representation of 255.0
#define IEEE_255_0 0x437f0000
#ifdef IRRLICHT_FAST_MATH
#define F32_LOWER_0(f) (F32_AS_U32(f) > F32_SIGN_BIT)
#define F32_LOWER_EQUAL_0(f) (F32_AS_S32(f) <= F32_VALUE_0)
#define F32_GREATER_0(f) (F32_AS_S32(f) > F32_VALUE_0)
#define F32_GREATER_EQUAL_0(f) (F32_AS_U32(f) <= F32_SIGN_BIT)
#define F32_EQUAL_1(f) (F32_AS_U32(f) == F32_VALUE_1)
#define F32_EQUAL_0(f) ( (F32_AS_U32(f) & F32_EXPON_MANTISSA ) == F32_VALUE_0)
// only same sign
#define F32_A_GREATER_B(a,b) (F32_AS_S32((a)) > F32_AS_S32((b)))
#else
#define F32_LOWER_0(n) ((n) < 0.0f)
#define F32_LOWER_EQUAL_0(n) ((n) <= 0.0f)
#define F32_GREATER_0(n) ((n) > 0.0f)
#define F32_GREATER_EQUAL_0(n) ((n) >= 0.0f)
#define F32_EQUAL_1(n) ((n) == 1.0f)
#define F32_EQUAL_0(n) ((n) == 0.0f)
#define F32_A_GREATER_B(a,b) ((a) > (b))
#endif
#ifndef REALINLINE
#ifdef _MSC_VER
#define REALINLINE __forceinline
#else
#define REALINLINE inline
#endif
#endif
#if defined(__BORLANDC__) || defined (__BCPLUSPLUS__)
// 8-bit bools in borland builder
//! conditional set based on mask and arithmetic shift
REALINLINE u32 if_c_a_else_b ( const c8 condition, const u32 a, const u32 b )
{
return ( ( -condition >> 7 ) & ( a ^ b ) ) ^ b;
}
//! conditional set based on mask and arithmetic shift
REALINLINE u32 if_c_a_else_0 ( const c8 condition, const u32 a )
{
return ( -condition >> 31 ) & a;
}
#else
//! conditional set based on mask and arithmetic shift
REALINLINE u32 if_c_a_else_b ( const s32 condition, const u32 a, const u32 b )
{
return ( ( -condition >> 31 ) & ( a ^ b ) ) ^ b;
}
//! conditional set based on mask and arithmetic shift
REALINLINE u16 if_c_a_else_b ( const s16 condition, const u16 a, const u16 b )
{
return ( ( -condition >> 15 ) & ( a ^ b ) ) ^ b;
}
//! conditional set based on mask and arithmetic shift
REALINLINE u32 if_c_a_else_0 ( const s32 condition, const u32 a )
{
return ( -condition >> 31 ) & a;
}
#endif
/*
if (condition) state |= m; else state &= ~m;
*/
REALINLINE void setbit_cond ( u32 &state, s32 condition, u32 mask )
{
// 0, or any postive to mask
//s32 conmask = -condition >> 31;
state ^= ( ( -condition >> 31 ) ^ state ) & mask;
}
inline f32 round_( f32 x )
{
return floorf( x + 0.5f );
}
REALINLINE void clearFPUException ()
{
#ifdef IRRLICHT_FAST_MATH
return;
#ifdef feclearexcept
feclearexcept(FE_ALL_EXCEPT);
#elif defined(_MSC_VER)
__asm fnclex;
#elif defined(__GNUC__) && defined(__x86__)
__asm__ __volatile__ ("fclex \n\t");
#else
# warn clearFPUException not supported.
#endif
#endif
}
// calculate: sqrt ( x )
REALINLINE f32 squareroot(const f32 f)
{
return sqrtf(f);
}
// calculate: sqrt ( x )
REALINLINE f64 squareroot(const f64 f)
{
return sqrt(f);
}
// calculate: sqrt ( x )
REALINLINE s32 squareroot(const s32 f)
{
return static_cast<s32>(squareroot(static_cast<f32>(f)));
}
// calculate: 1 / sqrt ( x )
REALINLINE f64 reciprocal_squareroot(const f64 x)
{
return 1.0 / sqrt(x);
}
// calculate: 1 / sqrtf ( x )
REALINLINE f32 reciprocal_squareroot(const f32 f)
{
#if defined ( IRRLICHT_FAST_MATH )
#if defined(_MSC_VER)
// SSE reciprocal square root estimate, accurate to 12 significant
// bits of the mantissa
f32 recsqrt;
__asm rsqrtss xmm0, f // xmm0 = rsqrtss(f)
__asm movss recsqrt, xmm0 // return xmm0
return recsqrt;
/*
// comes from Nvidia
u32 tmp = (u32(IEEE_1_0 << 1) + IEEE_1_0 - *(u32*)&x) >> 1;
f32 y = *(f32*)&tmp;
return y * (1.47f - 0.47f * x * y * y);
*/
#else
return 1.f / sqrtf(f);
#endif
#else // no fast math
return 1.f / sqrtf(f);
#endif
}
// calculate: 1 / sqrtf( x )
REALINLINE s32 reciprocal_squareroot(const s32 x)
{
return static_cast<s32>(reciprocal_squareroot(static_cast<f32>(x)));
}
// calculate: 1 / x
REALINLINE f32 reciprocal( const f32 f )
{
#if defined (IRRLICHT_FAST_MATH)
// SSE Newton-Raphson reciprocal estimate, accurate to 23 significant
// bi ts of the mantissa
// One Newtown-Raphson Iteration:
// f(i+1) = 2 * rcpss(f) - f * rcpss(f) * rcpss(f)
f32 rec;
__asm rcpss xmm0, f // xmm0 = rcpss(f)
__asm movss xmm1, f // xmm1 = f
__asm mulss xmm1, xmm0 // xmm1 = f * rcpss(f)
__asm mulss xmm1, xmm0 // xmm2 = f * rcpss(f) * rcpss(f)
__asm addss xmm0, xmm0 // xmm0 = 2 * rcpss(f)
__asm subss xmm0, xmm1 // xmm0 = 2 * rcpss(f)
// - f * rcpss(f) * rcpss(f)
__asm movss rec, xmm0 // return xmm0
return rec;
//! i do not divide through 0.. (fpu expection)
// instead set f to a high value to get a return value near zero..
// -1000000000000.f.. is use minus to stay negative..
// must test's here (plane.normal dot anything ) checks on <= 0.f
//u32 x = (-(AIR(f) != 0 ) >> 31 ) & ( IR(f) ^ 0xd368d4a5 ) ^ 0xd368d4a5;
//return 1.f / FR ( x );
#else // no fast math
return 1.f / f;
#endif
}
// calculate: 1 / x
REALINLINE f64 reciprocal ( const f64 f )
{
return 1.0 / f;
}
// calculate: 1 / x, low precision allowed
REALINLINE f32 reciprocal_approxim ( const f32 f )
{
#if defined( IRRLICHT_FAST_MATH)
// SSE Newton-Raphson reciprocal estimate, accurate to 23 significant
// bi ts of the mantissa
// One Newtown-Raphson Iteration:
// f(i+1) = 2 * rcpss(f) - f * rcpss(f) * rcpss(f)
f32 rec;
__asm rcpss xmm0, f // xmm0 = rcpss(f)
__asm movss xmm1, f // xmm1 = f
__asm mulss xmm1, xmm0 // xmm1 = f * rcpss(f)
__asm mulss xmm1, xmm0 // xmm2 = f * rcpss(f) * rcpss(f)
__asm addss xmm0, xmm0 // xmm0 = 2 * rcpss(f)
__asm subss xmm0, xmm1 // xmm0 = 2 * rcpss(f)
// - f * rcpss(f) * rcpss(f)
__asm movss rec, xmm0 // return xmm0
return rec;
/*
// SSE reciprocal estimate, accurate to 12 significant bits of
f32 rec;
__asm rcpss xmm0, f // xmm0 = rcpss(f)
__asm movss rec , xmm0 // return xmm0
return rec;
*/
/*
register u32 x = 0x7F000000 - IR ( p );
const f32 r = FR ( x );
return r * (2.0f - p * r);
*/
#else // no fast math
return 1.f / f;
#endif
}
REALINLINE s32 floor32(f32 x)
{
diff --git a/include/irrTypes.h b/include/irrTypes.h
index d371f8a..a9591b7 100644
--- a/include/irrTypes.h
+++ b/include/irrTypes.h
@@ -1,221 +1,225 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __IRR_TYPES_H_INCLUDED__
#define __IRR_TYPES_H_INCLUDED__
#include "IrrCompileConfig.h"
namespace irr
{
//! 8 bit unsigned variable.
/** This is a typedef for unsigned char, it ensures portability of the engine. */
#ifdef _MSC_VER
typedef unsigned __int8 u8;
#else
typedef unsigned char u8;
#endif
//! 8 bit signed variable.
/** This is a typedef for signed char, it ensures portability of the engine. */
#ifdef _MSC_VER
typedef __int8 s8;
#else
typedef signed char s8;
#endif
//! 8 bit character variable.
/** This is a typedef for char, it ensures portability of the engine. */
typedef char c8;
//! 16 bit unsigned variable.
/** This is a typedef for unsigned short, it ensures portability of the engine. */
#ifdef _MSC_VER
typedef unsigned __int16 u16;
#else
typedef unsigned short u16;
#endif
//! 16 bit signed variable.
/** This is a typedef for signed short, it ensures portability of the engine. */
#ifdef _MSC_VER
typedef __int16 s16;
#else
typedef signed short s16;
#endif
//! 32 bit unsigned variable.
/** This is a typedef for unsigned int, it ensures portability of the engine. */
#ifdef _MSC_VER
typedef unsigned __int32 u32;
#else
typedef unsigned int u32;
#endif
//! 32 bit signed variable.
/** This is a typedef for signed int, it ensures portability of the engine. */
#ifdef _MSC_VER
typedef __int32 s32;
#else
typedef signed int s32;
#endif
// 64 bit signed variable.
// This is a typedef for __int64, it ensures portability of the engine.
// This type is currently not used by the engine and not supported by compilers
// other than Microsoft Compilers, so it is outcommented.
//typedef __int64 s64;
//! 32 bit floating point variable.
/** This is a typedef for float, it ensures portability of the engine. */
typedef float f32;
//! 64 bit floating point variable.
/** This is a typedef for double, it ensures portability of the engine. */
typedef double f64;
} // end namespace irr
#include <wchar.h>
#ifdef _IRR_WINDOWS_API_
//! Defines for s{w,n}printf because these methods do not match the ISO C
//! standard on Windows platforms, but it does on all others.
//! These should be int snprintf(char *str, size_t size, const char *format, ...);
//! and int swprintf(wchar_t *wcs, size_t maxlen, const wchar_t *format, ...);
#if defined(_MSC_VER) && _MSC_VER > 1310 && !defined (_WIN32_WCE)
#define swprintf swprintf_s
#define snprintf sprintf_s
#else
#define swprintf _snwprintf
#define snprintf _snprintf
#endif
// define the wchar_t type if not already built in.
#ifdef _MSC_VER
#ifndef _WCHAR_T_DEFINED
//! A 16 bit wide character type.
/**
Defines the wchar_t-type.
In VS6, its not possible to tell
the standard compiler to treat wchar_t as a built-in type, and
sometimes we just don't want to include the huge stdlib.h or wchar.h,
so we'll use this.
*/
typedef unsigned short wchar_t;
#define _WCHAR_T_DEFINED
#endif // wchar is not defined
#endif // microsoft compiler
#endif // _IRR_WINDOWS_API_
namespace irr
{
//! Type name for character type used by the file system.
/** Should the wide character version of the FileSystem be used it is a
16 bit character variable. Used for unicode Filesystem and unicode strings.
Else it is a 8 bit character variable. Used for ansi Filesystem and non-unicode
strings
*/
#if defined(_IRR_WCHAR_FILESYSTEM)
typedef wchar_t fschar_t;
#else
typedef char fschar_t;
#endif
} // end namespace irr
//! define a break macro for debugging.
#if defined(_DEBUG)
#if defined(_IRR_WINDOWS_API_) && defined(_MSC_VER) && !defined (_WIN32_WCE)
#if defined(WIN64) || defined(_WIN64) // using portable common solution for x64 configuration
#include <crtdbg.h>
#define _IRR_DEBUG_BREAK_IF( _CONDITION_ ) if (_CONDITION_) {_CrtDbgBreak();}
#else
#define _IRR_DEBUG_BREAK_IF( _CONDITION_ ) if (_CONDITION_) {_asm int 3}
#endif
#else
#include "assert.h"
#define _IRR_DEBUG_BREAK_IF( _CONDITION_ ) assert( !(_CONDITION_) );
#endif
#else
#define _IRR_DEBUG_BREAK_IF( _CONDITION_ )
#endif
//! Defines a deprecated macro which generates a warning at compile time
/** The usage is simple
For typedef: typedef _IRR_DEPRECATED_ int test1;
For classes/structs: class _IRR_DEPRECATED_ test2 { ... };
For methods: class test3 { _IRR_DEPRECATED_ virtual void foo() {} };
For functions: template<class T> _IRR_DEPRECATED_ void test4(void) {}
**/
#if defined(IGNORE_DEPRECATED_WARNING)
#define _IRR_DEPRECATED_
#elif _MSC_VER >= 1310 //vs 2003 or higher
#define _IRR_DEPRECATED_ __declspec(deprecated)
#elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) // all versions above 3.0 should support this feature
#define _IRR_DEPRECATED_ __attribute__ ((deprecated))
#else
#define _IRR_DEPRECATED_
#endif
//! Defines a small statement to work around a microsoft compiler bug.
/** The microsoft compiler 7.0 - 7.1 has a bug:
When you call unmanaged code that returns a bool type value of false from managed code,
the return value may appear as true. See
http://support.microsoft.com/default.aspx?kbid=823071 for details.
Compiler version defines: VC6.0 : 1200, VC7.0 : 1300, VC7.1 : 1310, VC8.0 : 1400*/
#if defined(_IRR_WINDOWS_API_) && defined(_MSC_VER) && (_MSC_VER > 1299) && (_MSC_VER < 1400)
#define _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX __asm mov eax,100
#else
#define _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX
#endif // _IRR_MANAGED_MARSHALLING_BUGFIX
// memory debugging
#if defined(_DEBUG) && defined(IRRLICHT_EXPORTS) && defined(_MSC_VER) && \
(_MSC_VER > 1299) && !defined(_IRR_DONT_DO_MEMORY_DEBUGGING_HERE) && !defined(_WIN32_WCE)
#define CRTDBG_MAP_ALLOC
#define _CRTDBG_MAP_ALLOC
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#include <stdlib.h>
#include <crtdbg.h>
#define new DEBUG_CLIENTBLOCK
#endif
// disable truncated debug information warning in visual studio 6 by default
#if defined(_MSC_VER) && (_MSC_VER < 1300 )
#pragma warning( disable: 4786)
#endif // _MSC
//! ignore VC8 warning deprecated
/** The microsoft compiler */
#if defined(_IRR_WINDOWS_API_) && defined(_MSC_VER) && (_MSC_VER >= 1400)
//#pragma warning( disable: 4996)
//#define _CRT_SECURE_NO_DEPRECATE 1
//#define _CRT_NONSTDC_NO_DEPRECATE 1
#endif
//! creates four CC codes used in Irrlicht for simple ids
/** some compilers can create those by directly writing the
code like 'code', but some generate warnings so we use this macro here */
#define MAKE_IRR_ID(c0, c1, c2, c3) \
((irr::u32)(irr::u8)(c0) | ((irr::u32)(irr::u8)(c1) << 8) | \
((irr::u32)(irr::u8)(c2) << 16) | ((irr::u32)(irr::u8)(c3) << 24 ))
+#if defined(__BORLANDC__) || defined (__BCPLUSPLUS__)
+#define _strcmpi(a,b) strcmpi(a,b)
+#endif
+
#endif // __IRR_TYPES_H_INCLUDED__
diff --git a/source/Irrlicht/CD3D9Driver.h b/source/Irrlicht/CD3D9Driver.h
index 8e6448a..7b6b12c 100644
--- a/source/Irrlicht/CD3D9Driver.h
+++ b/source/Irrlicht/CD3D9Driver.h
@@ -1,445 +1,446 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_VIDEO_DIRECTX_9_H_INCLUDED__
#define __C_VIDEO_DIRECTX_9_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
#ifdef _IRR_WINDOWS_
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include "CNullDriver.h"
#include "IMaterialRendererServices.h"
+#include "irrMath.h" // needed by borland for sqrtf define
#include <d3d9.h>
namespace irr
{
namespace video
{
struct SDepthSurface : public IReferenceCounted
{
SDepthSurface() : Surface(0)
{
#ifdef _DEBUG
setDebugName("SDepthSurface");
#endif
}
virtual ~SDepthSurface()
{
if (Surface)
Surface->Release();
}
IDirect3DSurface9* Surface;
core::dimension2du Size;
};
class CD3D9Driver : public CNullDriver, IMaterialRendererServices
{
public:
friend class CD3D9Texture;
//! constructor
CD3D9Driver(const core::dimension2d<u32>& screenSize, HWND window, bool fullscreen,
bool stencibuffer, io::IFileSystem* io, bool pureSoftware=false);
//! destructor
virtual ~CD3D9Driver();
//! applications must call this method before performing any rendering. returns false if failed.
virtual bool beginScene(bool backBuffer=true, bool zBuffer=true,
SColor color=SColor(255,0,0,0),
const SExposedVideoData& videoData=SExposedVideoData(),
core::rect<s32>* sourceRect=0);
//! applications must call this method after performing any rendering. returns false if failed.
virtual bool endScene();
//! queries the features of the driver, returns true if feature is available
virtual bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const;
//! sets transformation
virtual void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat);
//! sets a material
virtual void setMaterial(const SMaterial& material);
//! sets a render target
virtual bool setRenderTarget(video::ITexture* texture,
bool clearBackBuffer=true, bool clearZBuffer=true,
SColor color=video::SColor(0,0,0,0));
//! Sets multiple render targets
virtual bool setRenderTarget(const core::array<video::IRenderTarget>& texture,
bool clearBackBuffer=true, bool clearZBuffer=true,
SColor color=video::SColor(0,0,0,0));
//! sets a viewport
virtual void setViewPort(const core::rect<s32>& area);
//! gets the area of the current viewport
virtual const core::rect<s32>& getViewPort() const;
struct SHWBufferLink_d3d9 : public SHWBufferLink
{
SHWBufferLink_d3d9(const scene::IMeshBuffer *_MeshBuffer):
SHWBufferLink(_MeshBuffer),
vertexBuffer(0), indexBuffer(0),
vertexBufferSize(0), indexBufferSize(0) {}
IDirect3DVertexBuffer9* vertexBuffer;
IDirect3DIndexBuffer9* indexBuffer;
u32 vertexBufferSize;
u32 indexBufferSize;
};
bool updateVertexHardwareBuffer(SHWBufferLink_d3d9 *HWBuffer);
bool updateIndexHardwareBuffer(SHWBufferLink_d3d9 *HWBuffer);
//! updates hardware buffer if needed
virtual bool updateHardwareBuffer(SHWBufferLink *HWBuffer);
//! Create hardware buffer from mesh
virtual SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer* mb);
//! Delete hardware buffer (only some drivers can)
virtual void deleteHardwareBuffer(SHWBufferLink *HWBuffer);
//! Draw hardware buffer
virtual void drawHardwareBuffer(SHWBufferLink *HWBuffer);
//! draws a vertex primitive list
virtual void drawVertexPrimitiveList(const void* vertices, u32 vertexCount,
const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType,
E_INDEX_TYPE iType);
//! draws a vertex primitive list in 2d
virtual void draw2DVertexPrimitiveList(const void* vertices, u32 vertexCount,
const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType,
E_INDEX_TYPE iType);
//! draws an 2d image, using a color (if color is other then Color(255,255,255,255)) and the alpha channel of the texture if wanted.
virtual void draw2DImage(const video::ITexture* texture, const core::position2d<s32>& destPos,
const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect = 0,
SColor color=SColor(255,255,255,255), bool useAlphaChannelOfTexture=false);
//! Draws a part of the texture into the rectangle.
virtual void draw2DImage(const video::ITexture* texture, const core::rect<s32>& destRect,
const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect = 0,
const video::SColor* const colors=0, bool useAlphaChannelOfTexture=false);
//! Draws a set of 2d images, using a color and the alpha channel of the texture.
virtual void draw2DImageBatch(const video::ITexture* texture,
const core::array<core::position2d<s32> >& positions,
const core::array<core::rect<s32> >& sourceRects,
const core::rect<s32>* clipRect=0,
SColor color=SColor(255,255,255,255),
bool useAlphaChannelOfTexture=false);
//!Draws an 2d rectangle with a gradient.
virtual void draw2DRectangle(const core::rect<s32>& pos,
SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown,
const core::rect<s32>* clip);
//! Draws a 2d line.
virtual void draw2DLine(const core::position2d<s32>& start,
const core::position2d<s32>& end,
SColor color=SColor(255,255,255,255));
//! Draws a pixel.
virtual void drawPixel(u32 x, u32 y, const SColor & color);
//! Draws a 3d line.
virtual void draw3DLine(const core::vector3df& start,
const core::vector3df& end, SColor color = SColor(255,255,255,255));
//! initialises the Direct3D API
bool initDriver(const core::dimension2d<u32>& screenSize, HWND hwnd,
u32 bits, bool fullScreen, bool pureSoftware,
bool highPrecisionFPU, bool vsync, u8 antiAlias);
//! \return Returns the name of the video driver. Example: In case of the DIRECT3D8
//! driver, it would return "Direct3D8.1".
virtual const wchar_t* getName() const;
//! deletes all dynamic lights there are
virtual void deleteAllDynamicLights();
//! adds a dynamic light, returning an index to the light
//! \param light: the light data to use to create the light
//! \return An index to the light, or -1 if an error occurs
virtual s32 addDynamicLight(const SLight& light);
//! Turns a dynamic light on or off
//! \param lightIndex: the index returned by addDynamicLight
//! \param turnOn: true to turn the light on, false to turn it off
virtual void turnLightOn(s32 lightIndex, bool turnOn);
//! returns the maximal amount of dynamic lights the device can handle
virtual u32 getMaximalDynamicLightAmount() const;
//! Sets the dynamic ambient light color. The default color is
//! (0,0,0,0) which means it is dark.
//! \param color: New color of the ambient light.
virtual void setAmbientLight(const SColorf& color);
//! Draws a shadow volume into the stencil buffer.
virtual void drawStencilShadowVolume(const core::vector3df* triangles, s32 count, bool zfail);
//! Fills the stencil shadow with color.
virtual void drawStencilShadow(bool clearStencilBuffer=false,
video::SColor leftUpEdge = video::SColor(0,0,0,0),
video::SColor rightUpEdge = video::SColor(0,0,0,0),
video::SColor leftDownEdge = video::SColor(0,0,0,0),
video::SColor rightDownEdge = video::SColor(0,0,0,0));
//! Returns the maximum amount of primitives (mostly vertices) which
//! the device is able to render with one drawIndexedTriangleList
//! call.
virtual u32 getMaximalPrimitiveCount() const;
//! Enables or disables a texture creation flag.
virtual void setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag, bool enabled);
//! Sets the fog mode.
virtual void setFog(SColor color, E_FOG_TYPE fogType, f32 start,
f32 end, f32 density, bool pixelFog, bool rangeFog);
//! Only used by the internal engine. Used to notify the driver that
//! the window was resized.
virtual void OnResize(const core::dimension2d<u32>& size);
//! Can be called by an IMaterialRenderer to make its work easier.
virtual void setBasicRenderStates(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates);
//! Returns type of video driver
virtual E_DRIVER_TYPE getDriverType() const;
//! Returns the transformation set by setTransform
virtual const core::matrix4& getTransform(E_TRANSFORMATION_STATE state) const;
//! Sets a vertex shader constant.
virtual void setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1);
//! Sets a pixel shader constant.
virtual void setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1);
//! Sets a constant for the vertex shader based on a name.
virtual bool setVertexShaderConstant(const c8* name, const f32* floats, int count);
//! Sets a constant for the pixel shader based on a name.
virtual bool setPixelShaderConstant(const c8* name, const f32* floats, int count);
//! Returns a pointer to the IVideoDriver interface. (Implementation for
//! IMaterialRendererServices)
virtual IVideoDriver* getVideoDriver();
//! Creates a render target texture.
virtual ITexture* addRenderTargetTexture(const core::dimension2d<u32>& size,
const io::path& name, const ECOLOR_FORMAT format = ECF_UNKNOWN);
//! Clears the ZBuffer.
virtual void clearZBuffer();
//! Returns an image created from the last rendered frame.
virtual IImage* createScreenShot();
//! Set/unset a clipping plane.
virtual bool setClipPlane(u32 index, const core::plane3df& plane, bool enable=false);
//! Enable/disable a clipping plane.
virtual void enableClipPlane(u32 index, bool enable);
//! Returns the graphics card vendor name.
virtual core::stringc getVendorInfo() {return VendorName;}
//! Enable the 2d override material
virtual void enableMaterial2D(bool enable=true);
//! Check if the driver was recently reset.
virtual bool checkDriverReset() {return DriverWasReset;}
// removes the depth struct from the DepthSurface array
void removeDepthSurface(SDepthSurface* depth);
//! Get the current color format of the color buffer
/** \return Color format of the color buffer. */
virtual ECOLOR_FORMAT getColorFormat() const;
//! Returns the maximum texture size supported.
virtual core::dimension2du getMaxTextureSize() const;
//! Get the current color format of the color buffer
/** \return Color format of the color buffer as D3D color value. */
D3DFORMAT getD3DColorFormat() const;
//! Get D3D color format from Irrlicht color format.
D3DFORMAT getD3DFormatFromColorFormat(ECOLOR_FORMAT format) const;
//! Get Irrlicht color format from D3D color format.
ECOLOR_FORMAT getColorFormatFromD3DFormat(D3DFORMAT format) const;
private:
//! enumeration for rendering modes such as 2d and 3d for minizing the switching of renderStates.
enum E_RENDER_MODE
{
ERM_NONE = 0, // no render state has been set yet.
ERM_2D, // 2d drawing rendermode
ERM_3D, // 3d rendering mode
ERM_STENCIL_FILL, // stencil fill mode
ERM_SHADOW_VOLUME_ZFAIL, // stencil volume draw mode
ERM_SHADOW_VOLUME_ZPASS // stencil volume draw mode
};
//! sets right vertex shader
void setVertexShader(video::E_VERTEX_TYPE newType);
//! sets the needed renderstates
bool setRenderStates3DMode();
//! sets the needed renderstates
void setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel);
//! sets the needed renderstates
void setRenderStatesStencilFillMode(bool alpha);
//! sets the needed renderstates
void setRenderStatesStencilShadowMode(bool zfail);
//! sets the current Texture
bool setActiveTexture(u32 stage, const video::ITexture* texture);
//! resets the device
bool reset();
//! returns a device dependent texture from a software surface (IImage)
//! THIS METHOD HAS TO BE OVERRIDDEN BY DERIVED DRIVERS WITH OWN TEXTURES
virtual video::ITexture* createDeviceDependentTexture(IImage* surface, const io::path& name, void* mipmapData=0);
//! returns the current size of the screen or rendertarget
virtual const core::dimension2d<u32>& getCurrentRenderTargetSize() const;
//! Check if a proper depth buffer for the RTT is available, otherwise create it.
void checkDepthBuffer(ITexture* tex);
//! Adds a new material renderer to the VideoDriver, using pixel and/or
//! vertex shaders to render geometry.
s32 addShaderMaterial(const c8* vertexShaderProgram, const c8* pixelShaderProgram,
IShaderConstantSetCallBack* callback,
E_MATERIAL_TYPE baseMaterial, s32 userData);
//! Adds a new material renderer to the VideoDriver, based on a high level shading
//! language.
virtual s32 addHighLevelShaderMaterial(
const c8* vertexShaderProgram,
const c8* vertexShaderEntryPointName,
E_VERTEX_SHADER_TYPE vsCompileTarget,
const c8* pixelShaderProgram,
const c8* pixelShaderEntryPointName,
E_PIXEL_SHADER_TYPE psCompileTarget,
const c8* geometryShaderProgram,
const c8* geometryShaderEntryPointName = "main",
E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0,
scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES,
scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP,
u32 verticesOut = 0,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData=0);
void createMaterialRenderers();
void draw2D3DVertexPrimitiveList(const void* vertices,
u32 vertexCount, const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType,
E_INDEX_TYPE iType, bool is3D);
D3DTEXTUREADDRESS getTextureWrapMode(const u8 clamp);
inline D3DCOLORVALUE colorToD3D(const SColor& col)
{
const f32 f = 1.0f / 255.0f;
D3DCOLORVALUE v;
v.r = col.getRed() * f;
v.g = col.getGreen() * f;
v.b = col.getBlue() * f;
v.a = col.getAlpha() * f;
return v;
}
E_RENDER_MODE CurrentRenderMode;
D3DPRESENT_PARAMETERS present;
SMaterial Material, LastMaterial;
bool ResetRenderStates; // bool to make all renderstates be reseted if set.
bool Transformation3DChanged;
bool StencilBuffer;
u8 AntiAliasing;
const ITexture* CurrentTexture[MATERIAL_MAX_TEXTURES];
bool LastTextureMipMapsAvailable[MATERIAL_MAX_TEXTURES];
core::matrix4 Matrices[ETS_COUNT]; // matrizes of the 3d mode we need to restore when we switch back from the 2d mode.
HINSTANCE D3DLibrary;
IDirect3D9* pID3D;
IDirect3DDevice9* pID3DDevice;
IDirect3DSurface9* PrevRenderTarget;
core::dimension2d<u32> CurrentRendertargetSize;
core::dimension2d<u32> CurrentDepthBufferSize;
HWND WindowId;
core::rect<s32>* SceneSourceRect;
D3DCAPS9 Caps;
E_VERTEX_TYPE LastVertexType;
SColorf AmbientLight;
core::stringc VendorName;
u16 VendorID;
core::array<SDepthSurface*> DepthBuffers;
u32 MaxTextureUnits;
u32 MaxUserClipPlanes;
f32 MaxLightDistance;
s32 LastSetLight;
enum E_CACHE_2D_ATTRIBUTES
{
EC2D_ALPHA = 0x1,
EC2D_TEXTURE = 0x2,
EC2D_ALPHA_CHANNEL = 0x4
};
u32 Cached2DModeSignature;
ECOLOR_FORMAT ColorFormat;
D3DFORMAT D3DColorFormat;
bool DeviceLost;
bool Fullscreen;
bool DriverWasReset;
bool AlphaToCoverageSupport;
};
} // end namespace video
} // end namespace irr
#endif // _IRR_COMPILE_WITH_DIRECT3D_9_
#endif // __C_VIDEO_DIRECTX_9_H_INCLUDED__
diff --git a/source/Irrlicht/CD3D9MaterialRenderer.h b/source/Irrlicht/CD3D9MaterialRenderer.h
index 782e167..f108ad7 100644
--- a/source/Irrlicht/CD3D9MaterialRenderer.h
+++ b/source/Irrlicht/CD3D9MaterialRenderer.h
@@ -1,523 +1,524 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_D3D9_MATERIAL_RENDERER_H_INCLUDED__
#define __C_D3D9_MATERIAL_RENDERER_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_WINDOWS_
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
+#include "irrMath.h" // needed by borland for sqrtf define
#include <d3d9.h>
#include "IMaterialRenderer.h"
namespace irr
{
namespace video
{
D3DMATRIX UnitMatrixD3D9;
D3DMATRIX SphereMapMatrixD3D9;
//! Base class for all internal D3D9 material renderers
class CD3D9MaterialRenderer : public IMaterialRenderer
{
public:
//! Constructor
CD3D9MaterialRenderer(IDirect3DDevice9* d3ddev, video::IVideoDriver* driver)
: pID3DDevice(d3ddev), Driver(driver)
{
}
~CD3D9MaterialRenderer()
{
}
//! sets a variable in the shader.
//! \param vertexShader: True if this should be set in the vertex shader, false if
//! in the pixel shader.
//! \param name: Name of the variable
//! \param floats: Pointer to array of floats
//! \param count: Amount of floats in array.
virtual bool setVariable(bool vertexShader, const c8* name, const f32* floats, int count)
{
os::Printer::log("Invalid material to set variable in.");
return false;
}
protected:
IDirect3DDevice9* pID3DDevice;
video::IVideoDriver* Driver;
};
//! Solid material renderer
class CD3D9MaterialRenderer_SOLID : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_SOLID(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
pID3DDevice->SetTextureStageState (0, D3DTSS_COLOROP, D3DTOP_MODULATE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
}
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
};
//! Generic Texture Blend
class CD3D9MaterialRenderer_ONETEXTURE_BLEND : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_ONETEXTURE_BLEND(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType ||
material.MaterialTypeParam != lastMaterial.MaterialTypeParam ||
resetAllRenderstates)
{
E_BLEND_FACTOR srcFact,dstFact;
E_MODULATE_FUNC modulate;
u32 alphaSource;
unpack_texureBlendFunc ( srcFact, dstFact, modulate, alphaSource, material.MaterialTypeParam );
if (srcFact == EBF_SRC_COLOR && dstFact == EBF_ZERO)
{
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
}
else
{
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
pID3DDevice->SetRenderState(D3DRS_SRCBLEND, getD3DBlend ( srcFact ) );
pID3DDevice->SetRenderState(D3DRS_DESTBLEND, getD3DBlend ( dstFact ) );
}
pID3DDevice->SetTextureStageState (0, D3DTSS_COLOROP, getD3DModulate ( modulate ) );
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
if ( textureBlendFunc_hasAlpha ( srcFact ) || textureBlendFunc_hasAlpha ( dstFact ) )
{
if (alphaSource==EAS_VERTEX_COLOR)
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE );
}
else if (alphaSource==EAS_TEXTURE)
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
}
else
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
}
}
else
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
}
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
//! Returns if the material is transparent.
/** The scene management needs to know this for being able to sort the
materials by opaque and transparent.
The return value could be optimized, but we'd need to know the
MaterialTypeParam for it. */
virtual bool isTransparent() const
{
return true;
}
private:
u32 getD3DBlend ( E_BLEND_FACTOR factor ) const
{
u32 r = 0;
switch ( factor )
{
case EBF_ZERO: r = D3DBLEND_ZERO; break;
case EBF_ONE: r = D3DBLEND_ONE; break;
case EBF_DST_COLOR: r = D3DBLEND_DESTCOLOR; break;
case EBF_ONE_MINUS_DST_COLOR: r = D3DBLEND_INVDESTCOLOR; break;
case EBF_SRC_COLOR: r = D3DBLEND_SRCCOLOR; break;
case EBF_ONE_MINUS_SRC_COLOR: r = D3DBLEND_INVSRCCOLOR; break;
case EBF_SRC_ALPHA: r = D3DBLEND_SRCALPHA; break;
case EBF_ONE_MINUS_SRC_ALPHA: r = D3DBLEND_INVSRCALPHA; break;
case EBF_DST_ALPHA: r = D3DBLEND_DESTALPHA; break;
case EBF_ONE_MINUS_DST_ALPHA: r = D3DBLEND_INVDESTALPHA; break;
case EBF_SRC_ALPHA_SATURATE: r = D3DBLEND_SRCALPHASAT; break;
}
return r;
}
u32 getD3DModulate ( E_MODULATE_FUNC func ) const
{
u32 r = D3DTOP_MODULATE;
switch ( func )
{
case EMFN_MODULATE_1X: r = D3DTOP_MODULATE; break;
case EMFN_MODULATE_2X: r = D3DTOP_MODULATE2X; break;
case EMFN_MODULATE_4X: r = D3DTOP_MODULATE4X; break;
}
return r;
}
bool transparent;
};
//! Solid 2 layer material renderer
class CD3D9MaterialRenderer_SOLID_2_LAYER : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_SOLID_2_LAYER(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
pID3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
pID3DDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 0);
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_BLENDDIFFUSEALPHA);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
};
//! Transparent add color material renderer
class CD3D9MaterialRenderer_TRANSPARENT_ADD_COLOR : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_TRANSPARENT_ADD_COLOR(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
pID3DDevice->SetTextureStageState (0, D3DTSS_COLOROP, D3DTOP_MODULATE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
pID3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
pID3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCCOLOR);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
//! Returns if the material is transparent. The scene management needs to know this
//! for being able to sort the materials by opaque and transparent.
virtual bool isTransparent() const
{
return true;
}
};
//! Transparent vertex alpha material renderer
class CD3D9MaterialRenderer_TRANSPARENT_VERTEX_ALPHA : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_TRANSPARENT_VERTEX_ALPHA(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
pID3DDevice->SetTextureStageState (0, D3DTSS_COLOROP, D3DTOP_MODULATE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
pID3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
pID3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
//! Returns if the material is transparent. The scene managment needs to know this
//! for being able to sort the materials by opaque and transparent.
virtual bool isTransparent() const
{
return true;
}
};
//! Transparent alpha channel material renderer
class CD3D9MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates
|| material.MaterialTypeParam != lastMaterial.MaterialTypeParam )
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_CURRENT );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE );
pID3DDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
pID3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
pID3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
pID3DDevice->SetRenderState(D3DRS_ALPHAREF, core::floor32(material.MaterialTypeParam * 255.f));
pID3DDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
pID3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
virtual void OnUnsetMaterial()
{
pID3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
}
//! Returns if the material is transparent. The scene managment needs to know this
//! for being able to sort the materials by opaque and transparent.
virtual bool isTransparent() const
{
return true;
}
};
//! Transparent alpha channel material renderer
class CD3D9MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL_REF : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL_REF(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_CURRENT );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
pID3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
pID3DDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE );
pID3DDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
// 127 is required by EMT_TRANSPARENT_ALPHA_CHANNEL_REF
pID3DDevice->SetRenderState(D3DRS_ALPHAREF, 127);
pID3DDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
pID3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
virtual void OnUnsetMaterial()
{
pID3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
}
//! Returns if the material is transparent. The scene managment needs to know this
//! for being able to sort the materials by opaque and transparent.
virtual bool isTransparent() const
{
return false; // this material is not really transparent because it does no blending.
}
};
//! material renderer for all kinds of lightmaps
class CD3D9MaterialRenderer_LIGHTMAP : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_LIGHTMAP(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
if (material.MaterialType >= EMT_LIGHTMAP_LIGHTING)
{
// with lighting
pID3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
pID3DDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
}
else
{
pID3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
pID3DDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
}
pID3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 1);
if (material.MaterialType == EMT_LIGHTMAP_ADD)
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_ADD);
else
if (material.MaterialType == EMT_LIGHTMAP_M4 || material.MaterialType == EMT_LIGHTMAP_LIGHTING_M4)
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE4X);
else
if (material.MaterialType == EMT_LIGHTMAP_M2 || material.MaterialType == EMT_LIGHTMAP_LIGHTING_M2)
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE2X);
else
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE);
pID3DDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT);
pID3DDevice->SetTextureStageState (1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
};
//! material renderer for detail maps
class CD3D9MaterialRenderer_DETAIL_MAP : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_DETAIL_MAP(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
pID3DDevice->SetTextureStageState (0, D3DTSS_COLOROP, D3DTOP_MODULATE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState (1, D3DTSS_COLOROP, D3DTOP_ADDSIGNED);
pID3DDevice->SetTextureStageState (1, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState (1, D3DTSS_COLORARG2, D3DTA_CURRENT);
pID3DDevice->SetTextureStageState (1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 1);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
};
//! sphere map material renderer
class CD3D9MaterialRenderer_SPHERE_MAP : public CD3D9MaterialRenderer
{
public:
CD3D9MaterialRenderer_SPHERE_MAP(IDirect3DDevice9* p, video::IVideoDriver* d)
: CD3D9MaterialRenderer(p, d) {}
virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates, IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
pID3DDevice->SetTextureStageState (0, D3DTSS_COLOROP, D3DTOP_MODULATE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pID3DDevice->SetTextureStageState (0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
pID3DDevice->SetTextureStageState (0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
pID3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
pID3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
pID3DDevice->SetTransform( D3DTS_TEXTURE0, &SphereMapMatrixD3D9 );
pID3DDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2 );
pID3DDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACENORMAL );
}
services->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
virtual void OnUnsetMaterial()
{
pID3DDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE );
pID3DDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 0);
pID3DDevice->SetTransform( D3DTS_TEXTURE0, &UnitMatrixD3D9 );
}
};
diff --git a/source/Irrlicht/CD3D9NormalMapRenderer.h b/source/Irrlicht/CD3D9NormalMapRenderer.h
index 7f9f88b..3e2f25f 100644
--- a/source/Irrlicht/CD3D9NormalMapRenderer.h
+++ b/source/Irrlicht/CD3D9NormalMapRenderer.h
@@ -1,53 +1,54 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_D3D9_NORMAL_MAPMATERIAL_RENDERER_H_INCLUDED__
#define __C_D3D9_NORMAL_MAPMATERIAL_RENDERER_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_WINDOWS_
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
+#include "irrMath.h" // needed by borland for sqrtf define
#include <d3d9.h>
#include "CD3D9ShaderMaterialRenderer.h"
#include "IShaderConstantSetCallBack.h"
namespace irr
{
namespace video
{
//! Renderer for normal maps
class CD3D9NormalMapRenderer :
public CD3D9ShaderMaterialRenderer, IShaderConstantSetCallBack
{
public:
CD3D9NormalMapRenderer(
IDirect3DDevice9* d3ddev, video::IVideoDriver* driver,
s32& outMaterialTypeNr, IMaterialRenderer* baseMaterial);
~CD3D9NormalMapRenderer();
//! Called by the engine when the vertex and/or pixel shader constants for an
//! material renderer should be set.
virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData);
virtual bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype);
//! Returns the render capability of the material.
virtual s32 getRenderCapability() const;
private:
};
} // end namespace video
} // end namespace irr
#endif
#endif
#endif
diff --git a/source/Irrlicht/CD3D9ParallaxMapRenderer.h b/source/Irrlicht/CD3D9ParallaxMapRenderer.h
index f57a09f..15cb527 100644
--- a/source/Irrlicht/CD3D9ParallaxMapRenderer.h
+++ b/source/Irrlicht/CD3D9ParallaxMapRenderer.h
@@ -1,60 +1,61 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_D3D9_PARALLAX_MAPMATERIAL_RENDERER_H_INCLUDED__
#define __C_D3D9_PARALLAX_MAPMATERIAL_RENDERER_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_WINDOWS_
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
+#include "irrMath.h" // needed by borland for sqrtf define
#include <d3d9.h>
#include "CD3D9ShaderMaterialRenderer.h"
#include "IShaderConstantSetCallBack.h"
namespace irr
{
namespace video
{
//! Renderer for normal maps using parallax mapping
class CD3D9ParallaxMapRenderer :
public CD3D9ShaderMaterialRenderer, IShaderConstantSetCallBack
{
public:
CD3D9ParallaxMapRenderer(
IDirect3DDevice9* d3ddev, video::IVideoDriver* driver,
s32& outMaterialTypeNr, IMaterialRenderer* baseMaterial);
~CD3D9ParallaxMapRenderer();
//! Called by the engine when the vertex and/or pixel shader constants for an
//! material renderer should be set.
virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData);
virtual bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype);
//! Returns the render capability of the material.
virtual s32 getRenderCapability() const;
virtual void OnSetMaterial(const SMaterial& material) { }
virtual void OnSetMaterial(const video::SMaterial& material,
const video::SMaterial& lastMaterial,
bool resetAllRenderstates, video::IMaterialRendererServices* services);
private:
f32 CurrentScale;
};
} // end namespace video
} // end namespace irr
#endif
#endif
#endif
diff --git a/source/Irrlicht/CD3D9ShaderMaterialRenderer.h b/source/Irrlicht/CD3D9ShaderMaterialRenderer.h
index b035eb6..e69fc34 100644
--- a/source/Irrlicht/CD3D9ShaderMaterialRenderer.h
+++ b/source/Irrlicht/CD3D9ShaderMaterialRenderer.h
@@ -1,100 +1,101 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_D3D9_SHADER_MATERIAL_RENDERER_H_INCLUDED__
#define __C_D3D9_SHADER_MATERIAL_RENDERER_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_WINDOWS_
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
+#include "irrMath.h" // needed by borland for sqrtf define
#include <d3d9.h>
#include <d3dx9shader.h>
#include "IMaterialRenderer.h"
namespace irr
{
namespace video
{
class IVideoDriver;
class IShaderConstantSetCallBack;
class IMaterialRenderer;
//! Class for using vertex and pixel shaders with D3D9
class CD3D9ShaderMaterialRenderer : public IMaterialRenderer
{
public:
//! Public constructor
CD3D9ShaderMaterialRenderer(IDirect3DDevice9* d3ddev, video::IVideoDriver* driver,
s32& outMaterialTypeNr, const c8* vertexShaderProgram, const c8* pixelShaderProgram,
IShaderConstantSetCallBack* callback, IMaterialRenderer* baseMaterial, s32 userData);
//! Destructor
~CD3D9ShaderMaterialRenderer();
virtual void OnSetMaterial(const video::SMaterial& material, const video::SMaterial& lastMaterial,
bool resetAllRenderstates, video::IMaterialRendererServices* services);
virtual void OnUnsetMaterial();
virtual bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype);
//! Returns if the material is transparent.
virtual bool isTransparent() const;
protected:
//! constructor only for use by derived classes who want to
//! create a fall back material for example.
CD3D9ShaderMaterialRenderer(IDirect3DDevice9* d3ddev,
video::IVideoDriver* driver,
IShaderConstantSetCallBack* callback,
IMaterialRenderer* baseMaterial,
s32 userData=0);
void init(s32& outMaterialTypeNr, const c8* vertexShaderProgram, const c8* pixelShaderProgram);
bool createPixelShader(const c8* pxsh);
bool createVertexShader(const char* vtxsh);
HRESULT stubD3DXAssembleShader(LPCSTR pSrcData, UINT SrcDataLen,
CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude,
DWORD Flags, LPD3DXBUFFER* ppShader,
LPD3DXBUFFER* ppErrorMsgs);
HRESULT stubD3DXAssembleShaderFromFile(LPCSTR pSrcFile,
CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, DWORD Flags,
LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs);
HRESULT stubD3DXCompileShader(LPCSTR pSrcData, UINT SrcDataLen, CONST D3DXMACRO* pDefines,
LPD3DXINCLUDE pInclude, LPCSTR pFunctionName,
LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader,
LPD3DXBUFFER* ppErrorMsgs, LPD3DXCONSTANTTABLE* ppConstantTable);
HRESULT stubD3DXCompileShaderFromFile(LPCSTR pSrcFile, CONST D3DXMACRO* pDefines,
LPD3DXINCLUDE pInclude, LPCSTR pFunctionName,
LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs,
LPD3DXCONSTANTTABLE* ppConstantTable);
IDirect3DDevice9* pID3DDevice;
video::IVideoDriver* Driver;
IShaderConstantSetCallBack* CallBack;
IMaterialRenderer* BaseMaterial;
IDirect3DVertexShader9* VertexShader;
IDirect3DVertexShader9* OldVertexShader;
IDirect3DPixelShader9* PixelShader;
s32 UserData;
};
} // end namespace video
} // end namespace irr
#endif
#endif
#endif
diff --git a/source/Irrlicht/CD3D9Texture.h b/source/Irrlicht/CD3D9Texture.h
index efc2a85..73130f9 100644
--- a/source/Irrlicht/CD3D9Texture.h
+++ b/source/Irrlicht/CD3D9Texture.h
@@ -1,127 +1,128 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_DIRECTX9_TEXTURE_H_INCLUDED__
#define __C_DIRECTX9_TEXTURE_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
#include "ITexture.h"
#include "IImage.h"
+#include "irrMath.h" // needed by borland for sqrtf define
#include <d3d9.h>
namespace irr
{
namespace video
{
class CD3D9Driver;
// forward declaration for RTT depth buffer handling
struct SDepthSurface;
/*!
interface for a Video Driver dependent Texture.
*/
class CD3D9Texture : public ITexture
{
public:
//! constructor
CD3D9Texture(IImage* image, CD3D9Driver* driver,
u32 flags, const io::path& name, void* mipmapData=0);
//! rendertarget constructor
CD3D9Texture(CD3D9Driver* driver, const core::dimension2d<u32>& size, const io::path& name,
const ECOLOR_FORMAT format = ECF_UNKNOWN);
//! destructor
virtual ~CD3D9Texture();
//! lock function
virtual void* lock(bool readOnly = false, u32 mipmapLevel=0);
//! unlock function
virtual void unlock();
//! Returns original size of the texture.
virtual const core::dimension2d<u32>& getOriginalSize() const;
//! Returns (=size) of the texture.
virtual const core::dimension2d<u32>& getSize() const;
//! returns driver type of texture (=the driver, who created the texture)
virtual E_DRIVER_TYPE getDriverType() const;
//! returns color format of texture
virtual ECOLOR_FORMAT getColorFormat() const;
//! returns pitch of texture (in bytes)
virtual u32 getPitch() const;
//! returns the DIRECT3D9 Texture
IDirect3DBaseTexture9* getDX9Texture() const;
//! returns if texture has mipmap levels
bool hasMipMaps() const;
//! Regenerates the mip map levels of the texture. Useful after locking and
//! modifying the texture
virtual void regenerateMipMapLevels(void* mipmapData=0);
//! returns if it is a render target
virtual bool isRenderTarget() const;
//! Returns pointer to the render target surface
IDirect3DSurface9* getRenderTargetSurface();
private:
friend class CD3D9Driver;
void createRenderTarget(const ECOLOR_FORMAT format = ECF_UNKNOWN);
//! creates the hardware texture
bool createTexture(u32 flags, IImage * image);
//! copies the image to the texture
bool copyTexture(IImage * image);
//! Helper function for mipmap generation.
bool createMipMaps(u32 level=1);
//! Helper function for mipmap generation.
void copy16BitMipMap(char* src, char* tgt,
s32 width, s32 height, s32 pitchsrc, s32 pitchtgt) const;
//! Helper function for mipmap generation.
void copy32BitMipMap(char* src, char* tgt,
s32 width, s32 height, s32 pitchsrc, s32 pitchtgt) const;
//! set Pitch based on the d3d format
void setPitch(D3DFORMAT d3dformat);
IDirect3DDevice9* Device;
IDirect3DTexture9* Texture;
IDirect3DSurface9* RTTSurface;
CD3D9Driver* Driver;
SDepthSurface* DepthSurface;
core::dimension2d<u32> TextureSize;
core::dimension2d<u32> ImageSize;
s32 Pitch;
u32 MipLevelLocked;
ECOLOR_FORMAT ColorFormat;
bool HasMipMaps;
bool HardwareMipMaps;
bool IsRenderTarget;
};
} // end namespace video
} // end namespace irr
#endif // _IRR_COMPILE_WITH_DIRECT3D_9_
#endif // __C_DIRECTX9_TEXTURE_H_INCLUDED__
diff --git a/source/Irrlicht/CFileSystem.cpp b/source/Irrlicht/CFileSystem.cpp
index 709ffd4..b07271d 100644
--- a/source/Irrlicht/CFileSystem.cpp
+++ b/source/Irrlicht/CFileSystem.cpp
@@ -242,600 +242,602 @@ bool CFileSystem::addFileArchive(const io::path& filename, bool ignoreCase,
file->drop();
}
}
}
else
{
// try to open archive based on archive loader type
io::IReadFile* file = 0;
for (i = 0; i < ArchiveLoader.size(); ++i)
{
if (ArchiveLoader[i]->isALoadableFileFormat(archiveType))
{
// attempt to open file
if (!file)
file = createAndOpenFile(filename);
// is the file open?
if (file)
{
// attempt to open archive
file->seek(0);
if (ArchiveLoader[i]->isALoadableFileFormat(file))
{
file->seek(0);
archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
if (archive)
break;
}
}
else
{
// couldn't open file
break;
}
}
}
// if open, close the file
if (file)
file->drop();
}
if (archive)
{
FileArchives.push_back(archive);
if (password.size())
archive->Password=password;
ret = true;
}
else
{
os::Printer::log("Could not create archive for", filename, ELL_ERROR);
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return ret;
}
//! removes an archive from the file system.
bool CFileSystem::removeFileArchive(u32 index)
{
bool ret = false;
if (index < FileArchives.size())
{
FileArchives[index]->drop();
FileArchives.erase(index);
ret = true;
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return ret;
}
//! removes an archive from the file system.
bool CFileSystem::removeFileArchive(const io::path& filename)
{
for (u32 i=0; i < FileArchives.size(); ++i)
{
if (filename == FileArchives[i]->getFileList()->getPath())
return removeFileArchive(i);
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
//! gets an archive
u32 CFileSystem::getFileArchiveCount() const
{
return FileArchives.size();
}
IFileArchive* CFileSystem::getFileArchive(u32 index)
{
return index < getFileArchiveCount() ? FileArchives[index] : 0;
}
//! Returns the string of the current working directory
const io::path& CFileSystem::getWorkingDirectory()
{
EFileSystemType type = FileSystemType;
if (type != FILESYSTEM_NATIVE)
{
type = FILESYSTEM_VIRTUAL;
}
else
{
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
// does not need this
#elif defined(_IRR_WINDOWS_API_)
fschar_t tmp[_MAX_PATH];
#if defined(_IRR_WCHAR_FILESYSTEM )
_wgetcwd(tmp, _MAX_PATH);
WorkingDirectory[FILESYSTEM_NATIVE] = tmp;
WorkingDirectory[FILESYSTEM_NATIVE].replace(L'\\', L'/');
#else
_getcwd(tmp, _MAX_PATH);
WorkingDirectory[FILESYSTEM_NATIVE] = tmp;
WorkingDirectory[FILESYSTEM_NATIVE].replace('\\', '/');
#endif
#endif
#if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
// getting the CWD is rather complex as we do not know the size
// so try it until the call was successful
// Note that neither the first nor the second parameter may be 0 according to POSIX
#if defined(_IRR_WCHAR_FILESYSTEM )
u32 pathSize=256;
wchar_t *tmpPath = new wchar_t[pathSize];
while ((pathSize < (1<<16)) && !(wgetcwd(tmpPath,pathSize)))
{
delete [] tmpPath;
pathSize *= 2;
tmpPath = new char[pathSize];
}
if (tmpPath)
{
WorkingDirectory[FILESYSTEM_NATIVE] = tmpPath;
delete [] tmpPath;
}
#else
u32 pathSize=256;
char *tmpPath = new char[pathSize];
while ((pathSize < (1<<16)) && !(getcwd(tmpPath,pathSize)))
{
delete [] tmpPath;
pathSize *= 2;
tmpPath = new char[pathSize];
}
if (tmpPath)
{
WorkingDirectory[FILESYSTEM_NATIVE] = tmpPath;
delete [] tmpPath;
}
#endif
#endif
WorkingDirectory[type].validate();
}
return WorkingDirectory[type];
}
//! Changes the current Working Directory to the given string.
bool CFileSystem::changeWorkingDirectoryTo(const io::path& newDirectory)
{
bool success=false;
if (FileSystemType != FILESYSTEM_NATIVE)
{
WorkingDirectory[FILESYSTEM_VIRTUAL] = newDirectory;
flattenFilename(WorkingDirectory[FILESYSTEM_VIRTUAL], "");
success = 1;
}
else
{
WorkingDirectory[FILESYSTEM_NATIVE] = newDirectory;
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
success = true;
#elif defined(_MSC_VER)
#if defined(_IRR_WCHAR_FILESYSTEM)
success=(_wchdir(newDirectory.c_str()) == 0);
#else
success=(_chdir(newDirectory.c_str()) == 0);
#endif
#else
success=(chdir(newDirectory.c_str()) == 0);
#endif
}
return success;
}
io::path CFileSystem::getAbsolutePath(const io::path& filename) const
{
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
return filename;
#elif defined(_IRR_WINDOWS_API_)
fschar_t *p=0;
fschar_t fpath[_MAX_PATH];
#if defined(_IRR_WCHAR_FILESYSTEM )
p = _wfullpath(fpath, filename.c_str(), _MAX_PATH);
core::stringw tmp(p);
tmp.replace(L'\\', L'/');
#else
p = _fullpath(fpath, filename.c_str(), _MAX_PATH);
core::stringc tmp(p);
tmp.replace('\\', '/');
#endif
return tmp;
#elif (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
c8* p=0;
c8 fpath[4096];
fpath[0]=0;
p = realpath(filename.c_str(), fpath);
if (!p)
{
// content in fpath is unclear at this point
if (!fpath[0]) // seems like fpath wasn't altered, use our best guess
{
io::path tmp(filename);
return flattenFilename(tmp);
}
else
return io::path(fpath);
}
if (filename[filename.size()-1]=='/')
return io::path(p)+"/";
else
return io::path(p);
#else
return io::path(filename);
#endif
}
//! returns the directory part of a filename, i.e. all until the first
//! slash or backslash, excluding it. If no directory path is prefixed, a '.'
//! is returned.
io::path CFileSystem::getFileDir(const io::path& filename) const
{
// find last forward or backslash
s32 lastSlash = filename.findLast('/');
const s32 lastBackSlash = filename.findLast('\\');
lastSlash = lastSlash > lastBackSlash ? lastSlash : lastBackSlash;
if ((u32)lastSlash < filename.size())
return filename.subString(0, lastSlash);
else
return ".";
}
//! returns the base part of a filename, i.e. all except for the directory
//! part. If no directory path is prefixed, the full name is returned.
io::path CFileSystem::getFileBasename(const io::path& filename, bool keepExtension) const
{
// find last forward or backslash
s32 lastSlash = filename.findLast('/');
const s32 lastBackSlash = filename.findLast('\\');
lastSlash = core::max_(lastSlash, lastBackSlash);
// get number of chars after last dot
s32 end = 0;
if (!keepExtension)
{
// take care to search only after last slash to check only for
// dots in the filename
end = filename.findLast('.');
if (end == -1 || end < lastSlash)
end=0;
else
end = filename.size()-end;
}
if ((u32)lastSlash < filename.size())
return filename.subString(lastSlash+1, filename.size()-lastSlash-1-end);
else if (end != 0)
return filename.subString(0, filename.size()-end);
else
return filename;
}
//! flatten a path and file name for example: "/you/me/../." becomes "/you"
io::path& CFileSystem::flattenFilename(io::path& directory, const io::path& root) const
{
directory.replace('\\', '/');
if (directory.lastChar() != '/')
directory.append('/');
io::path dir;
io::path subdir;
s32 lastpos = 0;
s32 pos = 0;
bool lastWasRealDir=false;
while ((pos = directory.findNext('/', lastpos)) >= 0)
{
subdir = directory.subString(lastpos, pos - lastpos + 1);
if (subdir == "../")
{
if (lastWasRealDir)
{
deletePathFromPath(dir, 2);
lastWasRealDir=(dir.size()!=0);
}
else
{
dir.append(subdir);
lastWasRealDir=false;
}
}
else if (subdir == "/")
{
dir = root;
}
else if (subdir != "./" )
{
dir.append(subdir);
lastWasRealDir=true;
}
lastpos = pos + 1;
}
directory = dir;
return directory;
}
//! Creates a list of files and directories in the current working directory
EFileSystemType CFileSystem::setFileListSystem(EFileSystemType listType)
{
EFileSystemType current = FileSystemType;
FileSystemType = listType;
return current;
}
//! Creates a list of files and directories in the current working directory
IFileList* CFileSystem::createFileList()
{
CFileList* r = 0;
io::path Path = getWorkingDirectory();
Path.replace('\\', '/');
if (Path.lastChar() != '/')
Path.append('/');
//! Construct from native filesystem
if (FileSystemType == FILESYSTEM_NATIVE)
{
io::path fullPath;
// --------------------------------------------
//! Windows version
#ifdef _IRR_WINDOWS_API_
#if !defined ( _WIN32_WCE )
r = new CFileList(Path, true, false);
struct _finddata_t c_file;
long hFile;
if( (hFile = _findfirst( "*", &c_file )) != -1L )
{
do
{
fullPath = Path + c_file.name;
r->addItem(fullPath, c_file.size, (_A_SUBDIR & c_file.attrib) != 0, 0);
}
while( _findnext( hFile, &c_file ) == 0 );
_findclose( hFile );
}
#endif
//TODO add drives
//entry.Name = "E:\\";
//entry.isDirectory = true;
//Files.push_back(entry);
#endif
// --------------------------------------------
//! Linux version
#if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
r = new CFileList(Path, false, false);
r->addItem(Path + "..", 0, true, 0);
//! We use the POSIX compliant methods instead of scandir
DIR* dirHandle=opendir(Path.c_str());
if (dirHandle)
{
struct dirent *dirEntry;
while ((dirEntry=readdir(dirHandle)))
{
u32 size = 0;
bool isDirectory = false;
fullPath = Path + dirEntry->d_name;
if((strcmp(dirEntry->d_name, ".")==0) ||
(strcmp(dirEntry->d_name, "..")==0))
{
continue;
}
struct stat buf;
if (stat(dirEntry->d_name, &buf)==0)
{
size = buf.st_size;
isDirectory = S_ISDIR(buf.st_mode);
}
#if !defined(_IRR_SOLARIS_PLATFORM_) && !defined(__CYGWIN__)
// only available on some systems
else
{
isDirectory = dirEntry->d_type == DT_DIR;
}
#endif
r->addItem(fullPath, size, isDirectory, 0);
}
closedir(dirHandle);
}
#endif
}
else
{
//! create file list for the virtual filesystem
r = new CFileList(Path, false, false);
//! add relative navigation
SFileListEntry e2;
SFileListEntry e3;
//! PWD
r->addItem(Path + ".", 0, true, 0);
//! parent
r->addItem(Path + "..", 0, true, 0);
//! merge archives
for (u32 i=0; i < FileArchives.size(); ++i)
{
const IFileList *merge = FileArchives[i]->getFileList();
for (u32 j=0; j < merge->getFileCount(); ++j)
{
if (core::isInSameDirectory(Path, merge->getFullFileName(j)) == 0)
{
io::path fullPath = merge->getFullFileName(j);
r->addItem(fullPath, merge->getFileSize(j), merge->isDirectory(j), 0);
}
}
}
}
if (r)
r->sort();
return r;
}
//! Creates an empty filelist
IFileList* CFileSystem::createEmptyFileList(const io::path& path, bool ignoreCase, bool ignorePaths)
{
return new CFileList(path, ignoreCase, ignorePaths);
}
//! determines if a file exists and would be able to be opened.
bool CFileSystem::existFile(const io::path& filename) const
{
for (u32 i=0; i < FileArchives.size(); ++i)
if (FileArchives[i]->getFileList()->findFile(filename)!=-1)
return true;
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
#if defined(_IRR_WCHAR_FILESYSTEM)
HANDLE hFile = CreateFileW(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
#else
HANDLE hFile = CreateFileW(core::stringw(filename).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
#endif
if (hFile == INVALID_HANDLE_VALUE)
return false;
else
{
CloseHandle(hFile);
return true;
}
#else
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
#if defined(_MSC_VER)
#if defined(_IRR_WCHAR_FILESYSTEM)
return (_waccess(filename.c_str(), 0) != -1);
#else
return (_access(filename.c_str(), 0) != -1);
#endif
-#else
+#elif defined(F_OK)
return (access(filename.c_str(), F_OK) != -1);
+#else
+ return (access(filename.c_str(), 0) != -1);
#endif
#endif
}
//! Creates a XML Reader from a file.
IXMLReader* CFileSystem::createXMLReader(const io::path& filename)
{
IReadFile* file = createAndOpenFile(filename);
if (!file)
return 0;
IXMLReader* reader = createXMLReader(file);
file->drop();
return reader;
}
//! Creates a XML Reader from a file.
IXMLReader* CFileSystem::createXMLReader(IReadFile* file)
{
if (!file)
return 0;
return createIXMLReader(file);
}
//! Creates a XML Reader from a file.
IXMLReaderUTF8* CFileSystem::createXMLReaderUTF8(const io::path& filename)
{
IReadFile* file = createAndOpenFile(filename);
if (!file)
return 0;
IXMLReaderUTF8* reader = createIXMLReaderUTF8(file);
file->drop();
return reader;
}
//! Creates a XML Reader from a file.
IXMLReaderUTF8* CFileSystem::createXMLReaderUTF8(IReadFile* file)
{
if (!file)
return 0;
return createIXMLReaderUTF8(file);
}
//! Creates a XML Writer from a file.
IXMLWriter* CFileSystem::createXMLWriter(const io::path& filename)
{
IWriteFile* file = createAndWriteFile(filename);
IXMLWriter* writer = createXMLWriter(file);
file->drop();
return writer;
}
//! Creates a XML Writer from a file.
IXMLWriter* CFileSystem::createXMLWriter(IWriteFile* file)
{
return new CXMLWriter(file);
}
//! creates a filesystem which is able to open files from the ordinary file system,
//! and out of zipfiles, which are able to be added to the filesystem.
IFileSystem* createFileSystem()
{
return new CFileSystem();
}
//! Creates a new empty collection of attributes, usable for serialization and more.
IAttributes* CFileSystem::createEmptyAttributes(video::IVideoDriver* driver)
{
return new CAttributes(driver);
}
} // end namespace irr
} // end namespace io
diff --git a/source/Irrlicht/CGUIModalScreen.cpp b/source/Irrlicht/CGUIModalScreen.cpp
index 0b204cf..1e93df8 100644
--- a/source/Irrlicht/CGUIModalScreen.cpp
+++ b/source/Irrlicht/CGUIModalScreen.cpp
@@ -1,215 +1,215 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CGUIModalScreen.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include "IGUIEnvironment.h"
#include "os.h"
#include "IVideoDriver.h"
#include "IGUISkin.h"
namespace irr
{
namespace gui
{
//! constructor
CGUIModalScreen::CGUIModalScreen(IGUIEnvironment* environment, IGUIElement* parent, s32 id)
: IGUIElement(EGUIET_MODAL_SCREEN, environment, parent, id, core::recti(0, 0, parent->getAbsolutePosition().getWidth(), parent->getAbsolutePosition().getHeight()) ),
MouseDownTime(0)
{
#ifdef _DEBUG
setDebugName("CGUIModalScreen");
#endif
setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT);
// this element is a tab group
setTabGroup(true);
}
bool CGUIModalScreen::canTakeFocus(IGUIElement* target) const
{
- return (target && (target == this // this element can take it
+ return (target && ((const IGUIElement*)target == this // this element can take it
|| isMyChild(target) // own childs also
|| (target->getType() == EGUIET_MODAL_SCREEN )// other modals also fine
|| (target->getParent() && target->getParent()->getType() == EGUIET_MODAL_SCREEN ))) // childs of other modals will do
;
}
bool CGUIModalScreen::isVisible() const
{
// any parent invisible?
IGUIElement * parentElement = getParent();
while ( parentElement )
{
if ( !parentElement->isVisible() )
return false;
parentElement = parentElement->getParent();
}
// if we have no children then the modal is probably abused as a way to block input
if ( Children.empty() )
{
return IGUIElement::isVisible();
}
// any child visible?
bool visible = false;
core::list<IGUIElement*>::ConstIterator it = Children.begin();
for (; it != Children.end(); ++it)
{
if ( (*it)->isVisible() )
{
visible = true;
break;
}
}
return visible;
}
bool CGUIModalScreen::isPointInside(const core::position2d<s32>& point) const
{
return true;
}
//! called if an event happened.
bool CGUIModalScreen::OnEvent(const SEvent& event)
{
if (!IsEnabled || !isVisible() )
return IGUIElement::OnEvent(event);
switch(event.EventType)
{
case EET_GUI_EVENT:
switch(event.GUIEvent.EventType)
{
case EGET_ELEMENT_FOCUSED:
if ( !canTakeFocus(event.GUIEvent.Caller))
{
Environment->setFocus(this);
}
IGUIElement::OnEvent(event);
return false;
case EGET_ELEMENT_FOCUS_LOST:
if ( !canTakeFocus(event.GUIEvent.Element))
{
MouseDownTime = os::Timer::getTime();
return true;
}
else
{
return IGUIElement::OnEvent(event);
}
case EGET_ELEMENT_CLOSED:
// do not interfere with children being removed
return IGUIElement::OnEvent(event);
default:
break;
}
break;
case EET_MOUSE_INPUT_EVENT:
if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
{
MouseDownTime = os::Timer::getTime();
}
default:
break;
}
IGUIElement::OnEvent(event);
return true; // absorb everything else
}
//! draws the element and its children
void CGUIModalScreen::draw()
{
IGUISkin *skin = Environment->getSkin();
if (!skin)
return;
u32 now = os::Timer::getTime();
if (now - MouseDownTime < 300 && (now / 70)%2)
{
core::list<IGUIElement*>::Iterator it = Children.begin();
core::rect<s32> r;
video::SColor c = Environment->getSkin()->getColor(gui::EGDC_3D_HIGH_LIGHT);
for (; it != Children.end(); ++it)
{
if ((*it)->isVisible())
{
r = (*it)->getAbsolutePosition();
r.LowerRightCorner.X += 1;
r.LowerRightCorner.Y += 1;
r.UpperLeftCorner.X -= 1;
r.UpperLeftCorner.Y -= 1;
skin->draw2DRectangle(this, c, r, &AbsoluteClippingRect);
}
}
}
IGUIElement::draw();
}
//! Removes a child.
void CGUIModalScreen::removeChild(IGUIElement* child)
{
IGUIElement::removeChild(child);
if (Children.empty())
{
remove();
}
}
//! adds a child
void CGUIModalScreen::addChild(IGUIElement* child)
{
IGUIElement::addChild(child);
Environment->setFocus(child);
}
void CGUIModalScreen::updateAbsolutePosition()
{
core::rect<s32> parentRect(0,0,0,0);
if (Parent)
{
parentRect = Parent->getAbsolutePosition();
RelativeRect.UpperLeftCorner.X = 0;
RelativeRect.UpperLeftCorner.Y = 0;
RelativeRect.LowerRightCorner.X = parentRect.getWidth();
RelativeRect.LowerRightCorner.Y = parentRect.getHeight();
}
IGUIElement::updateAbsolutePosition();
}
//! Writes attributes of the element.
void CGUIModalScreen::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const
{
IGUIElement::serializeAttributes(out,options);
}
//! Reads attributes of the element
void CGUIModalScreen::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0)
{
IGUIElement::deserializeAttributes(in, options);
}
} // end namespace gui
} // end namespace irr
#endif // _IRR_COMPILE_WITH_GUI_
diff --git a/source/Irrlicht/CNPKReader.cpp b/source/Irrlicht/CNPKReader.cpp
index 806b963..a2ef73a 100644
--- a/source/Irrlicht/CNPKReader.cpp
+++ b/source/Irrlicht/CNPKReader.cpp
@@ -1,279 +1,279 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// Copyright (C) 2009 Christian Stehno
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
// Based on the NPK reader from Irrlicht
#include "CNPKReader.h"
#ifdef __IRR_COMPILE_WITH_NPK_ARCHIVE_LOADER_
#include "os.h"
#include "coreutil.h"
#ifdef _DEBUG
#define IRR_DEBUG_NPK_READER
#endif
namespace irr
{
namespace io
{
namespace
{
bool isHeaderValid(const SNPKHeader& header)
{
const c8* const tag = header.Tag;
return tag[0] == '0' &&
tag[1] == 'K' &&
tag[2] == 'P' &&
tag[3] == 'N';
}
} // end namespace
//! Constructor
CArchiveLoaderNPK::CArchiveLoaderNPK( io::IFileSystem* fs)
: FileSystem(fs)
{
#ifdef _DEBUG
setDebugName("CArchiveLoaderNPK");
#endif
}
//! returns true if the file maybe is able to be loaded by this class
bool CArchiveLoaderNPK::isALoadableFileFormat(const io::path& filename) const
{
return core::hasFileExtension(filename, "npk");
}
//! Check to see if the loader can create archives of this type.
bool CArchiveLoaderNPK::isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) const
{
return fileType == EFAT_NPK;
}
//! Creates an archive from the filename
/** \param file File handle to check.
\return Pointer to newly created archive, or 0 upon error. */
IFileArchive* CArchiveLoaderNPK::createArchive(const io::path& filename, bool ignoreCase, bool ignorePaths) const
{
IFileArchive *archive = 0;
io::IReadFile* file = FileSystem->createAndOpenFile(filename);
if (file)
{
archive = createArchive(file, ignoreCase, ignorePaths);
file->drop ();
}
return archive;
}
//! creates/loads an archive from the file.
//! \return Pointer to the created archive. Returns 0 if loading failed.
IFileArchive* CArchiveLoaderNPK::createArchive(io::IReadFile* file, bool ignoreCase, bool ignorePaths) const
{
IFileArchive *archive = 0;
if ( file )
{
file->seek ( 0 );
archive = new CNPKReader(file, ignoreCase, ignorePaths);
}
return archive;
}
//! Check if the file might be loaded by this class
/** Check might look into the file.
\param file File handle to check.
\return True if file seems to be loadable. */
bool CArchiveLoaderNPK::isALoadableFileFormat(io::IReadFile* file) const
{
SNPKHeader header;
file->read(&header, sizeof(header));
return isHeaderValid(header);
}
/*!
NPK Reader
*/
CNPKReader::CNPKReader(IReadFile* file, bool ignoreCase, bool ignorePaths)
-: CFileList(file ? file->getFileName() : "", ignoreCase, ignorePaths), File(file)
+: CFileList((file ? file->getFileName() : io::path("")), ignoreCase, ignorePaths), File(file)
{
#ifdef _DEBUG
setDebugName("CNPKReader");
#endif
if (File)
{
File->grab();
if (scanLocalHeader())
sort();
else
os::Printer::log("Failed to load NPK archive.");
}
}
CNPKReader::~CNPKReader()
{
if (File)
File->drop();
}
const IFileList* CNPKReader::getFileList() const
{
return this;
}
bool CNPKReader::scanLocalHeader()
{
SNPKHeader header;
-
+
// Read and validate the header
File->read(&header, sizeof(header));
if (!isHeaderValid(header))
return false;
- // Seek to the table of contents
+ // Seek to the table of contents
#ifdef __BIG_ENDIAN__
header.Offset = os::Byteswap::byteswap(header.Offset);
header.Length = os::Byteswap::byteswap(header.Length);
#endif
header.Offset += 8;
core::stringc dirName;
bool inTOC=true;
// Loop through each entry in the table of contents
while (inTOC && (File->getPos() < File->getSize()))
{
// read an entry
char tag[4]={0};
SNPKFileEntry entry;
File->read(tag, 4);
const int numTag = MAKE_IRR_ID(tag[3],tag[2],tag[1],tag[0]);
int size;
bool isDir=true;
switch (numTag)
{
case MAKE_IRR_ID('D','I','R','_'):
{
File->read(&size, 4);
readString(entry.Name);
entry.Length=0;
entry.Offset=0;
#ifdef IRR_DEBUG_NPK_READER
os::Printer::log("Dir", entry.Name);
#endif
}
break;
case MAKE_IRR_ID('F','I','L','E'):
{
File->read(&size, 4);
File->read(&entry.Offset, 4);
File->read(&entry.Length, 4);
readString(entry.Name);
isDir=false;
#ifdef IRR_DEBUG_NPK_READER
os::Printer::log("File", entry.Name);
#endif
#ifdef __BIG_ENDIAN__
entry.Offset = os::Byteswap::byteswap(entry.Offset);
entry.Length = os::Byteswap::byteswap(entry.Length);
#endif
}
break;
case MAKE_IRR_ID('D','E','N','D'):
{
File->read(&size, 4);
entry.Name="";
entry.Length=0;
entry.Offset=0;
const s32 pos = dirName.findLast('/', dirName.size()-2);
if (pos==-1)
dirName="";
else
dirName=dirName.subString(0, pos);
#ifdef IRR_DEBUG_NPK_READER
os::Printer::log("Dirend", dirName);
#endif
}
break;
default:
inTOC=false;
}
// skip root dir
if (isDir)
{
if (!entry.Name.size() || (entry.Name==".") || (entry.Name=="<noname>"))
continue;
dirName += entry.Name;
dirName += "/";
}
#ifdef IRR_DEBUG_NPK_READER
os::Printer::log("Name", entry.Name);
#endif
- addItem(isDir?dirName:dirName+entry.Name, entry.Length, isDir, Offsets.size());
+ addItem((isDir?dirName:dirName+entry.Name), entry.Length, isDir, Offsets.size());
Offsets.push_back(entry.Offset+header.Offset);
}
return true;
}
//! opens a file by file name
IReadFile* CNPKReader::createAndOpenFile(const io::path& filename)
{
s32 index = findFile(filename, false);
if (index != -1)
return createAndOpenFile(index);
return 0;
}
//! opens a file by index
IReadFile* CNPKReader::createAndOpenFile(u32 index)
{
if (index < Files.size())
{
return createLimitReadFile(Files[index].FullName, File, Offsets[Files[index].ID], Files[index].Size);
}
else
return 0;
}
void CNPKReader::readString(core::stringc& name)
{
short stringSize;
char buf[256];
File->read(&stringSize, 2);
#ifdef __BIG_ENDIAN__
stringSize = os::Byteswap::byteswap(stringSize);
#endif
name.reserve(stringSize);
while(stringSize)
{
const short next = core::min_(stringSize, (short)255);
File->read(buf,next);
buf[next]=0;
name.append(buf);
stringSize -= next;
}
}
} // end namespace io
} // end namespace irr
#endif // __IRR_COMPILE_WITH_NPK_ARCHIVE_LOADER_
diff --git a/source/Irrlicht/CNullDriver.cpp b/source/Irrlicht/CNullDriver.cpp
index 3a2e72e..3cca75c 100644
--- a/source/Irrlicht/CNullDriver.cpp
+++ b/source/Irrlicht/CNullDriver.cpp
@@ -217,1025 +217,1025 @@ u32 CNullDriver::getImageLoaderCount() const
{
return SurfaceLoader.size();
}
//! Retrieve the given image loader
IImageLoader* CNullDriver::getImageLoader(u32 n)
{
if(n < SurfaceLoader.size())
return SurfaceLoader[n];
return 0;
}
//! Retrieve the number of image writers
u32 CNullDriver::getImageWriterCount() const
{
return SurfaceWriter.size();
}
//! Retrieve the given image writer
IImageWriter* CNullDriver::getImageWriter(u32 n)
{
if(n < SurfaceWriter.size())
return SurfaceWriter[n];
return 0;
}
//! deletes all textures
void CNullDriver::deleteAllTextures()
{
// we need to remove previously set textures which might otherwise be kept in the
// last set material member. Could be optimized to reduce state changes.
setMaterial(SMaterial());
for (u32 i=0; i<Textures.size(); ++i)
Textures[i].Surface->drop();
Textures.clear();
}
//! applications must call this method before performing any rendering. returns false if failed.
bool CNullDriver::beginScene(bool backBuffer, bool zBuffer, SColor color,
const SExposedVideoData& videoData, core::rect<s32>* sourceRect)
{
core::clearFPUException();
PrimitivesDrawn = 0;
return true;
}
//! applications must call this method after performing any rendering. returns false if failed.
bool CNullDriver::endScene()
{
FPSCounter.registerFrame(os::Timer::getRealTime(), PrimitivesDrawn);
updateAllHardwareBuffers();
return true;
}
//! Disable a feature of the driver.
void CNullDriver::disableFeature(E_VIDEO_DRIVER_FEATURE feature, bool flag)
{
FeatureEnabled[feature]=!flag;
}
//! queries the features of the driver, returns true if feature is available
bool CNullDriver::queryFeature(E_VIDEO_DRIVER_FEATURE feature) const
{
return false;
}
//! sets transformation
void CNullDriver::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat)
{
}
//! Returns the transformation set by setTransform
const core::matrix4& CNullDriver::getTransform(E_TRANSFORMATION_STATE state) const
{
return TransformationMatrix;
}
//! sets a material
void CNullDriver::setMaterial(const SMaterial& material)
{
}
//! Removes a texture from the texture cache and deletes it, freeing lot of
//! memory.
void CNullDriver::removeTexture(ITexture* texture)
{
if (!texture)
return;
for (u32 i=0; i<Textures.size(); ++i)
{
if (Textures[i].Surface == texture)
{
texture->drop();
Textures.erase(i);
}
}
}
//! Removes all texture from the texture cache and deletes them, freeing lot of
//! memory.
void CNullDriver::removeAllTextures()
{
setMaterial ( SMaterial() );
deleteAllTextures();
}
//! Returns a texture by index
ITexture* CNullDriver::getTextureByIndex(u32 i)
{
if ( i < Textures.size() )
return Textures[i].Surface;
return 0;
}
//! Returns amount of textures currently loaded
u32 CNullDriver::getTextureCount() const
{
return Textures.size();
}
//! Renames a texture
void CNullDriver::renameTexture(ITexture* texture, const io::path& newName)
{
// we can do a const_cast here safely, the name of the ITexture interface
// is just readonly to prevent the user changing the texture name without invoking
// this method, because the textures will need resorting afterwards
io::SNamedPath& name = const_cast<io::SNamedPath&>(texture->getName());
name.setPath(newName);
Textures.sort();
}
//! loads a Texture
ITexture* CNullDriver::getTexture(const io::path& filename)
{
// Identify textures by their absolute filenames if possible.
const io::path absolutePath = FileSystem->getAbsolutePath(filename);
ITexture* texture = findTexture(absolutePath);
if (texture)
return texture;
// Then try the raw filename, which might be in an Archive
texture = findTexture(filename);
if (texture)
return texture;
// Now try to open the file using the complete path.
io::IReadFile* file = FileSystem->createAndOpenFile(absolutePath);
if(!file)
{
// Try to open it using the raw filename.
file = FileSystem->createAndOpenFile(filename);
}
if (file)
{
// Re-check name for actual archive names
texture = findTexture(file->getFileName());
if (texture)
{
file->drop();
return texture;
}
texture = loadTextureFromFile(file);
file->drop();
if (texture)
{
addTexture(texture);
texture->drop(); // drop it because we created it, one grab too much
}
else
os::Printer::log("Could not load texture", filename, ELL_ERROR);
return texture;
}
else
{
os::Printer::log("Could not open file of texture", filename, ELL_WARNING);
return 0;
}
}
//! loads a Texture
ITexture* CNullDriver::getTexture(io::IReadFile* file)
{
ITexture* texture = 0;
if (file)
{
texture = findTexture(file->getFileName());
if (texture)
return texture;
texture = loadTextureFromFile(file);
if (texture)
{
addTexture(texture);
texture->drop(); // drop it because we created it, one grab too much
}
}
if (!texture)
os::Printer::log("Could not load texture", file->getFileName(), ELL_WARNING);
return texture;
}
//! opens the file and loads it into the surface
video::ITexture* CNullDriver::loadTextureFromFile(io::IReadFile* file, const io::path& hashName )
{
ITexture* texture = 0;
IImage* image = createImageFromFile(file);
if (image)
{
// create texture from surface
texture = createDeviceDependentTexture(image, hashName.size() ? hashName : file->getFileName() );
os::Printer::log("Loaded texture", file->getFileName());
image->drop();
}
return texture;
}
//! adds a surface, not loaded or created by the Irrlicht Engine
void CNullDriver::addTexture(video::ITexture* texture)
{
if (texture)
{
SSurface s;
s.Surface = texture;
texture->grab();
Textures.push_back(s);
// the new texture is now at the end of the texture list. when searching for
// the next new texture, the texture array will be sorted and the index of this texture
// will be changed. to let the order be more consistent to the user, sort
// the textures now already although this isn't necessary:
Textures.sort();
}
}
//! looks if the image is already loaded
video::ITexture* CNullDriver::findTexture(const io::path& filename)
{
SSurface s;
SDummyTexture dummy(filename);
s.Surface = &dummy;
s32 index = Textures.binary_search(s);
if (index != -1)
return Textures[index].Surface;
return 0;
}
//! Creates a texture from a loaded IImage.
ITexture* CNullDriver::addTexture(const io::path& name, IImage* image, void* mipmapData)
{
if ( 0 == name.size() || !image)
return 0;
ITexture* t = createDeviceDependentTexture(image, name, mipmapData);
if (t)
{
addTexture(t);
t->drop();
}
return t;
}
//! creates a Texture
ITexture* CNullDriver::addTexture(const core::dimension2d<u32>& size,
const io::path& name, ECOLOR_FORMAT format)
{
if(IImage::isRenderTargetOnlyFormat(format))
{
os::Printer::log("Could not create ITexture, format only supported for render target textures.", ELL_WARNING);
return 0;
}
if ( 0 == name.size () )
return 0;
IImage* image = new CImage(format, size);
ITexture* t = createDeviceDependentTexture(image, name);
image->drop();
addTexture(t);
if (t)
t->drop();
return t;
}
//! returns a device dependent texture from a software surface (IImage)
//! THIS METHOD HAS TO BE OVERRIDDEN BY DERIVED DRIVERS WITH OWN TEXTURES
ITexture* CNullDriver::createDeviceDependentTexture(IImage* surface, const io::path& name, void* mipmapData)
{
return new SDummyTexture(name);
}
//! set or reset special render targets
bool CNullDriver::setRenderTarget(video::E_RENDER_TARGET target, bool clearTarget,
bool clearZBuffer, SColor color)
{
if (ERT_FRAME_BUFFER==target)
return setRenderTarget(0,clearTarget, clearZBuffer, color);
else
return false;
}
//! sets a render target
bool CNullDriver::setRenderTarget(video::ITexture* texture, bool clearBackBuffer,
bool clearZBuffer, SColor color)
{
return false;
}
//! Sets multiple render targets
bool CNullDriver::setRenderTarget(const core::array<video::IRenderTarget>& texture,
bool clearBackBuffer, bool clearZBuffer, SColor color)
{
return false;
}
//! sets a viewport
void CNullDriver::setViewPort(const core::rect<s32>& area)
{
}
//! gets the area of the current viewport
const core::rect<s32>& CNullDriver::getViewPort() const
{
return ViewPort;
}
//! draws a vertex primitive list
void CNullDriver::drawVertexPrimitiveList(const void* vertices, u32 vertexCount, const void* indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType)
{
if ((iType==EIT_16BIT) && (vertexCount>65536))
os::Printer::log("Too many vertices for 16bit index type, render artifacts may occur.");
PrimitivesDrawn += primitiveCount;
}
//! draws a vertex primitive list in 2d
void CNullDriver::draw2DVertexPrimitiveList(const void* vertices, u32 vertexCount, const void* indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType)
{
if ((iType==EIT_16BIT) && (vertexCount>65536))
os::Printer::log("Too many vertices for 16bit index type, render artifacts may occur.");
PrimitivesDrawn += primitiveCount;
}
//! Draws a 3d line.
void CNullDriver::draw3DLine(const core::vector3df& start,
const core::vector3df& end, SColor color)
{
}
//! Draws a 3d triangle.
void CNullDriver::draw3DTriangle(const core::triangle3df& triangle, SColor color)
{
S3DVertex vertices[3];
vertices[0].Pos=triangle.pointA;
vertices[0].Color=color;
vertices[0].Normal=triangle.getNormal().normalize();
vertices[0].TCoords.set(0.f,0.f);
vertices[1].Pos=triangle.pointB;
vertices[1].Color=color;
vertices[1].Normal=vertices[0].Normal;
vertices[1].TCoords.set(0.5f,1.f);
vertices[2].Pos=triangle.pointC;
vertices[2].Color=color;
vertices[2].Normal=vertices[0].Normal;
vertices[2].TCoords.set(1.f,0.f);
const u16 indexList[] = {0,1,2};
drawVertexPrimitiveList(vertices, 3, indexList, 1, EVT_STANDARD, scene::EPT_TRIANGLES, EIT_16BIT);
}
//! Draws a 3d axis aligned box.
void CNullDriver::draw3DBox(const core::aabbox3d<f32>& box, SColor color)
{
core::vector3df edges[8];
box.getEdges(edges);
// TODO: optimize into one big drawIndexPrimitive call.
draw3DLine(edges[5], edges[1], color);
draw3DLine(edges[1], edges[3], color);
draw3DLine(edges[3], edges[7], color);
draw3DLine(edges[7], edges[5], color);
draw3DLine(edges[0], edges[2], color);
draw3DLine(edges[2], edges[6], color);
draw3DLine(edges[6], edges[4], color);
draw3DLine(edges[4], edges[0], color);
draw3DLine(edges[1], edges[0], color);
draw3DLine(edges[3], edges[2], color);
draw3DLine(edges[7], edges[6], color);
draw3DLine(edges[5], edges[4], color);
}
//! draws an 2d image
void CNullDriver::draw2DImage(const video::ITexture* texture, const core::position2d<s32>& destPos)
{
if (!texture)
return;
draw2DImage(texture,destPos, core::rect<s32>(core::position2d<s32>(0,0),
core::dimension2di(texture->getOriginalSize())));
}
//! draws a set of 2d images, using a color and the alpha channel of the
//! texture if desired. The images are drawn beginning at pos and concatenated
//! in one line. All drawings are clipped against clipRect (if != 0).
//! The subtextures are defined by the array of sourceRects and are chosen
//! by the indices given.
void CNullDriver::draw2DImageBatch(const video::ITexture* texture,
const core::position2d<s32>& pos,
const core::array<core::rect<s32> >& sourceRects,
const core::array<s32>& indices,
s32 kerningWidth,
const core::rect<s32>* clipRect, SColor color,
bool useAlphaChannelOfTexture)
{
core::position2d<s32> target(pos);
for (u32 i=0; i<indices.size(); ++i)
{
draw2DImage(texture, target, sourceRects[indices[i]],
clipRect, color, useAlphaChannelOfTexture);
target.X += sourceRects[indices[i]].getWidth();
target.X += kerningWidth;
}
}
//! draws a set of 2d images, using a color and the alpha channel of the
//! texture if desired.
void CNullDriver::draw2DImageBatch(const video::ITexture* texture,
const core::array<core::position2d<s32> >& positions,
const core::array<core::rect<s32> >& sourceRects,
const core::rect<s32>* clipRect,
SColor color,
bool useAlphaChannelOfTexture)
{
const irr::u32 drawCount = core::min_<u32>(positions.size(), sourceRects.size());
for (u32 i=0; i<drawCount; ++i)
{
draw2DImage(texture, positions[i], sourceRects[i],
clipRect, color, useAlphaChannelOfTexture);
}
}
//! Draws a part of the texture into the rectangle.
void CNullDriver::draw2DImage(const video::ITexture* texture, const core::rect<s32>& destRect,
const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect,
const video::SColor* const colors, bool useAlphaChannelOfTexture)
{
draw2DImage(texture, core::position2d<s32>(destRect.UpperLeftCorner),
- sourceRect, clipRect, colors?colors[0]:0xffffffff,
+ sourceRect, clipRect, colors?colors[0]:video::SColor(0xffffffff),
useAlphaChannelOfTexture);
}
//! Draws a 2d image, using a color (if color is other then Color(255,255,255,255)) and the alpha channel of the texture if wanted.
void CNullDriver::draw2DImage(const video::ITexture* texture, const core::position2d<s32>& destPos,
const core::rect<s32>& sourceRect,
const core::rect<s32>* clipRect, SColor color,
bool useAlphaChannelOfTexture)
{
}
//! Draws the outline of a 2d rectangle
void CNullDriver::draw2DRectangleOutline(const core::recti& pos, SColor color)
{
draw2DLine(pos.UpperLeftCorner, core::position2di(pos.LowerRightCorner.X, pos.UpperLeftCorner.Y), color);
draw2DLine(core::position2di(pos.LowerRightCorner.X, pos.UpperLeftCorner.Y), pos.LowerRightCorner, color);
draw2DLine(pos.LowerRightCorner, core::position2di(pos.UpperLeftCorner.X, pos.LowerRightCorner.Y), color);
draw2DLine(core::position2di(pos.UpperLeftCorner.X, pos.LowerRightCorner.Y), pos.UpperLeftCorner, color);
}
//! Draw a 2d rectangle
void CNullDriver::draw2DRectangle(SColor color, const core::rect<s32>& pos, const core::rect<s32>* clip)
{
draw2DRectangle(pos, color, color, color, color, clip);
}
//! Draws a 2d rectangle with a gradient.
void CNullDriver::draw2DRectangle(const core::rect<s32>& pos,
SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown,
const core::rect<s32>* clip)
{
}
//! Draws a 2d line.
void CNullDriver::draw2DLine(const core::position2d<s32>& start,
const core::position2d<s32>& end, SColor color)
{
}
//! Draws a pixel
void CNullDriver::drawPixel(u32 x, u32 y, const SColor & color)
{
}
//! Draws a non filled concyclic regular 2d polyon.
void CNullDriver::draw2DPolygon(core::position2d<s32> center,
f32 radius, video::SColor color, s32 count)
{
if (count < 2)
return;
core::position2d<s32> first;
core::position2d<s32> a,b;
for (s32 j=0; j<count; ++j)
{
b = a;
f32 p = j / (f32)count * (core::PI*2);
a = center + core::position2d<s32>((s32)(sin(p)*radius), (s32)(cos(p)*radius));
if (j==0)
first = a;
else
draw2DLine(a, b, color);
}
draw2DLine(a, first, color);
}
//! returns color format
ECOLOR_FORMAT CNullDriver::getColorFormat() const
{
return ECF_R5G6B5;
}
//! returns screen size
const core::dimension2d<u32>& CNullDriver::getScreenSize() const
{
return ScreenSize;
}
//! returns the current render target size,
//! or the screen size if render targets are not implemented
const core::dimension2d<u32>& CNullDriver::getCurrentRenderTargetSize() const
{
return ScreenSize;
}
// returns current frames per second value
s32 CNullDriver::getFPS() const
{
return FPSCounter.getFPS();
}
//! returns amount of primitives (mostly triangles) were drawn in the last frame.
//! very useful method for statistics.
u32 CNullDriver::getPrimitiveCountDrawn( u32 param ) const
{
return (0 == param) ? FPSCounter.getPrimitive() : (1 == param) ? FPSCounter.getPrimitiveAverage() : FPSCounter.getPrimitiveTotal();
}
//! Sets the dynamic ambient light color. The default color is
//! (0,0,0,0) which means it is dark.
//! \param color: New color of the ambient light.
void CNullDriver::setAmbientLight(const SColorf& color)
{
}
//! \return Returns the name of the video driver. Example: In case of the DIRECT3D8
//! driver, it would return "Direct3D8".
const wchar_t* CNullDriver::getName() const
{
return L"Irrlicht NullDevice";
}
//! Draws a shadow volume into the stencil buffer. To draw a stencil shadow, do
//! this: Frist, draw all geometry. Then use this method, to draw the shadow
//! volume. Then, use IVideoDriver::drawStencilShadow() to visualize the shadow.
void CNullDriver::drawStencilShadowVolume(const core::vector3df* triangles, s32 count, bool zfail)
{
}
//! Fills the stencil shadow with color. After the shadow volume has been drawn
//! into the stencil buffer using IVideoDriver::drawStencilShadowVolume(), use this
//! to draw the color of the shadow.
void CNullDriver::drawStencilShadow(bool clearStencilBuffer,
video::SColor leftUpEdge, video::SColor rightUpEdge,
video::SColor leftDownEdge, video::SColor rightDownEdge)
{
}
//! deletes all dynamic lights there are
void CNullDriver::deleteAllDynamicLights()
{
Lights.set_used(0);
}
//! adds a dynamic light
s32 CNullDriver::addDynamicLight(const SLight& light)
{
Lights.push_back(light);
return Lights.size() - 1;
}
//! Turns a dynamic light on or off
//! \param lightIndex: the index returned by addDynamicLight
//! \param turnOn: true to turn the light on, false to turn it off
void CNullDriver::turnLightOn(s32 lightIndex, bool turnOn)
{
// Do nothing
}
//! returns the maximal amount of dynamic lights the device can handle
u32 CNullDriver::getMaximalDynamicLightAmount() const
{
return 0;
}
//! Returns current amount of dynamic lights set
//! \return Current amount of dynamic lights set
u32 CNullDriver::getDynamicLightCount() const
{
return Lights.size();
}
//! Returns light data which was previously set by IVideoDriver::addDynamicLight().
//! \param idx: Zero based index of the light. Must be greater than 0 and smaller
//! than IVideoDriver()::getDynamicLightCount.
//! \return Light data.
const SLight& CNullDriver::getDynamicLight(u32 idx) const
{
if ( idx < Lights.size() )
return Lights[idx];
else
return *((SLight*)0);
}
//! Creates a boolean alpha channel of the texture based of an color key.
void CNullDriver::makeColorKeyTexture(video::ITexture* texture,
video::SColor color,
bool zeroTexels) const
{
if (!texture)
return;
if (texture->getColorFormat() != ECF_A1R5G5B5 &&
texture->getColorFormat() != ECF_A8R8G8B8 )
{
os::Printer::log("Error: Unsupported texture color format for making color key channel.", ELL_ERROR);
return;
}
if (texture->getColorFormat() == ECF_A1R5G5B5)
{
u16 *p = (u16*)texture->lock();
if (!p)
{
os::Printer::log("Could not lock texture for making color key channel.", ELL_ERROR);
return;
}
const core::dimension2d<u32> dim = texture->getSize();
const u32 pitch = texture->getPitch() / 2;
// color with alpha disabled (i.e. fully transparent)
const u16 refZeroAlpha = (0x7fff & color.toA1R5G5B5());
const u32 pixels = pitch * dim.Height;
for (u32 pixel = 0; pixel < pixels; ++ pixel)
{
// If the colour matches the reference colour, ignoring alphas,
// set the alpha to zero.
if(((*p) & 0x7fff) == refZeroAlpha)
{
if(zeroTexels)
(*p) = 0;
else
(*p) = refZeroAlpha;
}
++p;
}
texture->unlock();
}
else
{
u32 *p = (u32*)texture->lock();
if (!p)
{
os::Printer::log("Could not lock texture for making color key channel.", ELL_ERROR);
return;
}
core::dimension2d<u32> dim = texture->getSize();
u32 pitch = texture->getPitch() / 4;
// color with alpha disabled (fully transparent)
const u32 refZeroAlpha = 0x00ffffff & color.color;
const u32 pixels = pitch * dim.Height;
for (u32 pixel = 0; pixel < pixels; ++ pixel)
{
// If the colour matches the reference colour, ignoring alphas,
// set the alpha to zero.
if(((*p) & 0x00ffffff) == refZeroAlpha)
{
if(zeroTexels)
(*p) = 0;
else
(*p) = refZeroAlpha;
}
++p;
}
texture->unlock();
}
}
//! Creates an boolean alpha channel of the texture based of an color key position.
void CNullDriver::makeColorKeyTexture(video::ITexture* texture,
core::position2d<s32> colorKeyPixelPos,
bool zeroTexels) const
{
if (!texture)
return;
if (texture->getColorFormat() != ECF_A1R5G5B5 &&
texture->getColorFormat() != ECF_A8R8G8B8 )
{
os::Printer::log("Error: Unsupported texture color format for making color key channel.", ELL_ERROR);
return;
}
SColor colorKey;
if (texture->getColorFormat() == ECF_A1R5G5B5)
{
u16 *p = (u16*)texture->lock(true);
if (!p)
{
os::Printer::log("Could not lock texture for making color key channel.", ELL_ERROR);
return;
}
u32 pitch = texture->getPitch() / 2;
const u16 key16Bit = 0x7fff & p[colorKeyPixelPos.Y*pitch + colorKeyPixelPos.X];
colorKey = video::A1R5G5B5toA8R8G8B8(key16Bit);
}
else
{
u32 *p = (u32*)texture->lock(true);
if (!p)
{
os::Printer::log("Could not lock texture for making color key channel.", ELL_ERROR);
return;
}
u32 pitch = texture->getPitch() / 4;
colorKey = 0x00ffffff & p[colorKeyPixelPos.Y*pitch + colorKeyPixelPos.X];
}
texture->unlock();
makeColorKeyTexture(texture, colorKey, zeroTexels);
}
//! Creates a normal map from a height map texture.
//! \param amplitude: Constant value by which the height information is multiplied.
void CNullDriver::makeNormalMapTexture(video::ITexture* texture, f32 amplitude) const
{
if (!texture)
return;
if (texture->getColorFormat() != ECF_A1R5G5B5 &&
texture->getColorFormat() != ECF_A8R8G8B8 )
{
os::Printer::log("Error: Unsupported texture color format for making normal map.", ELL_ERROR);
return;
}
core::dimension2d<u32> dim = texture->getSize();
amplitude = amplitude / 255.0f;
f32 vh = dim.Height / (f32)dim.Width;
f32 hh = dim.Width / (f32)dim.Height;
if (texture->getColorFormat() == ECF_A8R8G8B8)
{
// ECF_A8R8G8B8 version
s32 *p = (s32*)texture->lock();
if (!p)
{
os::Printer::log("Could not lock texture for making normal map.", ELL_ERROR);
return;
}
// copy texture
u32 pitch = texture->getPitch() / 4;
s32* in = new s32[dim.Height * pitch];
memcpy(in, p, dim.Height * pitch * 4);
for (s32 x=0; x < s32(pitch); ++x)
for (s32 y=0; y < s32(dim.Height); ++y)
{
// TODO: this could be optimized really a lot
core::vector3df h1((x-1)*hh, nml32(x-1, y, pitch, dim.Height, in)*amplitude, y*vh);
core::vector3df h2((x+1)*hh, nml32(x+1, y, pitch, dim.Height, in)*amplitude, y*vh);
//core::vector3df v1(x*hh, nml32(x, y-1, pitch, dim.Height, in)*amplitude, (y-1)*vh);
//core::vector3df v2(x*hh, nml32(x, y+1, pitch, dim.Height, in)*amplitude, (y+1)*vh);
core::vector3df v1(x*hh, nml32(x, y+1, pitch, dim.Height, in)*amplitude, (y-1)*vh);
core::vector3df v2(x*hh, nml32(x, y-1, pitch, dim.Height, in)*amplitude, (y+1)*vh);
core::vector3df v = v1-v2;
core::vector3df h = h1-h2;
core::vector3df n = v.crossProduct(h);
n.normalize();
n *= 0.5f;
n += core::vector3df(0.5f,0.5f,0.5f); // now between 0 and 1
n *= 255.0f;
s32 height = (s32)nml32(x, y, pitch, dim.Height, in);
p[y*pitch + x] = video::SColor(
height, // store height in alpha
(s32)n.X, (s32)n.Z, (s32)n.Y).color;
}
delete [] in;
texture->unlock();
}
else
{
// ECF_A1R5G5B5 version
s16 *p = (s16*)texture->lock();
if (!p)
{
os::Printer::log("Could not lock texture for making normal map.", ELL_ERROR);
return;
}
u32 pitch = texture->getPitch() / 2;
// copy texture
s16* in = new s16[dim.Height * pitch];
memcpy(in, p, dim.Height * pitch * 2);
for (s32 x=0; x < s32(pitch); ++x)
for (s32 y=0; y < s32(dim.Height); ++y)
{
// TODO: this could be optimized really a lot
core::vector3df h1((x-1)*hh, nml16(x-1, y, pitch, dim.Height, in)*amplitude, y*vh);
core::vector3df h2((x+1)*hh, nml16(x+1, y, pitch, dim.Height, in)*amplitude, y*vh);
core::vector3df v1(x*hh, nml16(x, y-1, pitch, dim.Height, in)*amplitude, (y-1)*vh);
core::vector3df v2(x*hh, nml16(x, y+1, pitch, dim.Height, in)*amplitude, (y+1)*vh);
core::vector3df v = v1-v2;
core::vector3df h = h1-h2;
core::vector3df n = v.crossProduct(h);
n.normalize();
n *= 0.5f;
n += core::vector3df(0.5f,0.5f,0.5f); // now between 0 and 1
n *= 255.0f;
p[y*pitch + x] = video::RGBA16((u32)n.X, (u32)n.Z, (u32)n.Y);
}
delete [] in;
texture->unlock();
}
texture->regenerateMipMapLevels();
}
//! Returns the maximum amount of primitives (mostly vertices) which
//! the device is able to render with one drawIndexedTriangleList
//! call.
u32 CNullDriver::getMaximalPrimitiveCount() const
{
return 0xFFFFFFFF;
}
//! checks triangle count and print warning if wrong
bool CNullDriver::checkPrimitiveCount(u32 prmCount) const
{
const u32 m = getMaximalPrimitiveCount();
if (prmCount > m)
{
char tmp[1024];
sprintf(tmp,"Could not draw triangles, too many primitives(%u), maxium is %u.", prmCount, m);
os::Printer::log(tmp, ELL_ERROR);
return false;
}
return true;
}
//! Enables or disables a texture creation flag.
void CNullDriver::setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag, bool enabled)
{
if (enabled && ((flag == ETCF_ALWAYS_16_BIT) || (flag == ETCF_ALWAYS_32_BIT)
|| (flag == ETCF_OPTIMIZED_FOR_QUALITY) || (flag == ETCF_OPTIMIZED_FOR_SPEED)))
{
// disable other formats
setTextureCreationFlag(ETCF_ALWAYS_16_BIT, false);
setTextureCreationFlag(ETCF_ALWAYS_32_BIT, false);
setTextureCreationFlag(ETCF_OPTIMIZED_FOR_QUALITY, false);
setTextureCreationFlag(ETCF_OPTIMIZED_FOR_SPEED, false);
}
// set flag
TextureCreationFlags = (TextureCreationFlags & (~flag)) |
((((u32)!enabled)-1) & flag);
}
//! Returns if a texture creation flag is enabled or disabled.
bool CNullDriver::getTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag) const
{
return (TextureCreationFlags & flag)!=0;
}
diff --git a/source/Irrlicht/CPakReader.cpp b/source/Irrlicht/CPakReader.cpp
index a173aa3..0587172 100644
--- a/source/Irrlicht/CPakReader.cpp
+++ b/source/Irrlicht/CPakReader.cpp
@@ -1,199 +1,199 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
// Code contributed by skreamz
#include "CPakReader.h"
#ifdef __IRR_COMPILE_WITH_PAK_ARCHIVE_LOADER_
#include "os.h"
#include "coreutil.h"
namespace irr
{
namespace io
{
namespace
{
inline bool isHeaderValid(const SPAKFileHeader& header)
{
const c8* tag = header.tag;
return tag[0] == 'P' &&
tag[1] == 'A' &&
tag[2] == 'C' &&
tag[3] == 'K';
}
} // end namespace
//! Constructor
CArchiveLoaderPAK::CArchiveLoaderPAK( io::IFileSystem* fs)
: FileSystem(fs)
{
#ifdef _DEBUG
setDebugName("CArchiveLoaderPAK");
#endif
}
//! returns true if the file maybe is able to be loaded by this class
bool CArchiveLoaderPAK::isALoadableFileFormat(const io::path& filename) const
{
return core::hasFileExtension(filename, "pak");
}
//! Check to see if the loader can create archives of this type.
bool CArchiveLoaderPAK::isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) const
{
return fileType == EFAT_PAK;
}
//! Creates an archive from the filename
/** \param file File handle to check.
\return Pointer to newly created archive, or 0 upon error. */
IFileArchive* CArchiveLoaderPAK::createArchive(const io::path& filename, bool ignoreCase, bool ignorePaths) const
{
IFileArchive *archive = 0;
io::IReadFile* file = FileSystem->createAndOpenFile(filename);
if (file)
{
archive = createArchive(file, ignoreCase, ignorePaths);
file->drop ();
}
return archive;
}
//! creates/loads an archive from the file.
//! \return Pointer to the created archive. Returns 0 if loading failed.
IFileArchive* CArchiveLoaderPAK::createArchive(io::IReadFile* file, bool ignoreCase, bool ignorePaths) const
{
IFileArchive *archive = 0;
if ( file )
{
file->seek ( 0 );
archive = new CPakReader(file, ignoreCase, ignorePaths);
}
return archive;
}
//! Check if the file might be loaded by this class
/** Check might look into the file.
\param file File handle to check.
\return True if file seems to be loadable. */
bool CArchiveLoaderPAK::isALoadableFileFormat(io::IReadFile* file) const
{
SPAKFileHeader header;
file->read(&header, sizeof(header));
return isHeaderValid(header);
}
/*!
PAK Reader
*/
CPakReader::CPakReader(IReadFile* file, bool ignoreCase, bool ignorePaths)
-: CFileList(file ? file->getFileName() : "", ignoreCase, ignorePaths), File(file)
+: CFileList((file ? file->getFileName() : io::path("")), ignoreCase, ignorePaths), File(file)
{
#ifdef _DEBUG
setDebugName("CPakReader");
#endif
if (File)
{
File->grab();
scanLocalHeader();
sort();
}
}
CPakReader::~CPakReader()
{
if (File)
File->drop();
}
const IFileList* CPakReader::getFileList() const
{
return this;
}
bool CPakReader::scanLocalHeader()
{
SPAKFileHeader header;
-
+
// Read and validate the header
File->read(&header, sizeof(header));
if (!isHeaderValid(header))
return false;
- // Seek to the table of contents
+ // Seek to the table of contents
#ifdef __BIG_ENDIAN__
header.offset = os::Byteswap::byteswap(header.offset);
header.length = os::Byteswap::byteswap(header.length);
#endif
File->seek(header.offset);
const int numberOfFiles = header.length / sizeof(SPAKFileEntry);
Offsets.reallocate(numberOfFiles);
// Loop through each entry in the table of contents
for(int i = 0; i < numberOfFiles; i++)
{
// read an entry
SPAKFileEntry entry;
File->read(&entry, sizeof(entry));
#ifdef _DEBUG
os::Printer::log(entry.name);
#endif
#ifdef __BIG_ENDIAN__
entry.offset = os::Byteswap::byteswap(entry.offset);
entry.length = os::Byteswap::byteswap(entry.length);
#endif
addItem(io::path(entry.name), entry.length, false, Offsets.size());
Offsets.push_back(entry.offset);
}
return true;
}
//! opens a file by file name
IReadFile* CPakReader::createAndOpenFile(const io::path& filename)
{
s32 index = findFile(filename, false);
if (index != -1)
return createAndOpenFile(index);
return 0;
}
//! opens a file by index
IReadFile* CPakReader::createAndOpenFile(u32 index)
{
if (index < Files.size())
{
return createLimitReadFile(Files[index].FullName, File, Offsets[Files[index].ID], Files[index].Size);
}
else
return 0;
}
} // end namespace io
} // end namespace irr
#endif // __IRR_COMPILE_WITH_PAK_ARCHIVE_LOADER_
diff --git a/source/Irrlicht/CTarReader.cpp b/source/Irrlicht/CTarReader.cpp
index 13604dc..1b92f4c 100644
--- a/source/Irrlicht/CTarReader.cpp
+++ b/source/Irrlicht/CTarReader.cpp
@@ -1,258 +1,258 @@
// Copyright (C) 2009 Gaz Davidson
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CTarReader.h"
#ifdef __IRR_COMPILE_WITH_TAR_ARCHIVE_LOADER_
#include "CFileList.h"
#include "CLimitReadFile.h"
#include "os.h"
#include "coreutil.h"
#if !defined(_IRR_WINDOWS_CE_PLATFORM_)
#include "errno.h"
#endif
namespace irr
{
namespace io
{
//! Constructor
CArchiveLoaderTAR::CArchiveLoaderTAR(io::IFileSystem* fs)
: FileSystem(fs)
{
#ifdef _DEBUG
setDebugName("CArchiveLoaderTAR");
#endif
}
//! returns true if the file maybe is able to be loaded by this class
bool CArchiveLoaderTAR::isALoadableFileFormat(const io::path& filename) const
{
return core::hasFileExtension(filename, "tar");
}
//! Check to see if the loader can create archives of this type.
bool CArchiveLoaderTAR::isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) const
{
return fileType == EFAT_TAR;
}
//! Creates an archive from the filename
/** \param file File handle to check.
\return Pointer to newly created archive, or 0 upon error. */
IFileArchive* CArchiveLoaderTAR::createArchive(const io::path& filename, bool ignoreCase, bool ignorePaths) const
{
IFileArchive *archive = 0;
io::IReadFile* file = FileSystem->createAndOpenFile(filename);
if (file)
{
archive = createArchive(file, ignoreCase, ignorePaths);
file->drop();
}
return archive;
}
//! creates/loads an archive from the file.
//! \return Pointer to the created archive. Returns 0 if loading failed.
IFileArchive* CArchiveLoaderTAR::createArchive(io::IReadFile* file, bool ignoreCase, bool ignorePaths) const
{
IFileArchive *archive = 0;
if (file)
{
file->seek(0);
archive = new CTarReader(file, ignoreCase, ignorePaths);
}
return archive;
}
//! Check if the file might be loaded by this class
/** Check might look into the file.
\param file File handle to check.
\return True if file seems to be loadable. */
bool CArchiveLoaderTAR::isALoadableFileFormat(io::IReadFile* file) const
{
// TAR files consist of blocks of 512 bytes
// if it isn't a multiple of 512 then it's not a TAR file.
if (file->getSize() % 512)
return false;
file->seek(0);
// read header of first file
STarHeader fHead;
file->read(&fHead, sizeof(STarHeader));
u32 checksum = 0;
sscanf(fHead.Checksum, "%o", &checksum);
// verify checksum
// some old TAR writers assume that chars are signed, others assume unsigned
// USTAR archives have a longer header, old TAR archives end after linkname
u32 checksum1=0;
s32 checksum2=0;
// remember to blank the checksum field!
memset(fHead.Checksum, ' ', 8);
// old header
for (u8* p = (u8*)(&fHead); p < (u8*)(&fHead.Magic[0]); ++p)
{
checksum1 += *p;
checksum2 += c8(*p);
}
if (!strcmp(fHead.Magic, "star"))
{
for (u8* p = (u8*)(&fHead.Magic[0]); p < (u8*)(&fHead) + sizeof(fHead); ++p)
{
checksum1 += *p;
checksum2 += c8(*p);
}
}
return checksum1 == checksum || checksum2 == (s32)checksum;
}
/*
TAR Archive
*/
CTarReader::CTarReader(IReadFile* file, bool ignoreCase, bool ignorePaths)
- : CFileList(file ? file->getFileName() : "", ignoreCase, ignorePaths), File(file)
+ : CFileList((file ? file->getFileName() : io::path("")), ignoreCase, ignorePaths), File(file)
{
#ifdef _DEBUG
setDebugName("CTarReader");
#endif
if (File)
{
File->grab();
// fill the file list
populateFileList();
sort();
}
}
CTarReader::~CTarReader()
{
if (File)
File->drop();
}
const IFileList* CTarReader::getFileList() const
{
return this;
}
u32 CTarReader::populateFileList()
{
STarHeader fHead;
Files.clear();
u32 pos = 0;
while ( s32(pos + sizeof(STarHeader)) < File->getSize())
{
// seek to next file header
File->seek(pos);
// read the header
File->read(&fHead, sizeof(fHead));
// only add standard files for now
if (fHead.Link == ETLI_REGULAR_FILE || ETLI_REGULAR_FILE_OLD)
{
io::path fullPath = "";
fullPath.reserve(255);
// USTAR archives have a filename prefix
// may not be null terminated, copy carefully!
if (!strcmp(fHead.Magic, "ustar"))
{
c8* np = fHead.FileNamePrefix;
while(*np && (np - fHead.FileNamePrefix) < 155)
fullPath.append(*np);
np++;
}
// append the file name
c8* np = fHead.FileName;
while(*np && (np - fHead.FileName) < 100)
{
fullPath.append(*np);
np++;
}
// get size
core::stringc sSize = "";
sSize.reserve(12);
np = fHead.Size;
while(*np && (np - fHead.Size) < 12)
{
sSize.append(*np);
np++;
}
u32 size = strtoul(sSize.c_str(), NULL, 8);
#if !defined(_IRR_WINDOWS_CE_PLATFORM_)
if (errno == ERANGE)
os::Printer::log("File too large", fullPath, ELL_WARNING);
#endif
// save start position
u32 offset = pos + 512;
// move to next file header block
pos = offset + (size / 512) * 512 + ((size % 512) ? 512 : 0);
// add file to list
addItem(fullPath, size, false, Offsets.size());
Offsets.push_back(offset);
}
else
{
// todo: ETLI_DIRECTORY, ETLI_LINK_TO_ARCHIVED_FILE
// move to next block
pos += 512;
}
}
return Files.size();
}
//! opens a file by file name
IReadFile* CTarReader::createAndOpenFile(const io::path& filename)
{
const s32 index = findFile(filename, false);
if (index != -1)
return createAndOpenFile(index);
return 0;
}
//! opens a file by index
IReadFile* CTarReader::createAndOpenFile(u32 index)
{
if (index < Files.size())
return createLimitReadFile(Files[index].FullName, File, Offsets[Files[index].ID], Files[index].Size);
else
return 0;
}
} // end namespace io
} // end namespace irr
#endif // __IRR_COMPILE_WITH_TAR_ARCHIVE_LOADER_
diff --git a/source/Irrlicht/CZipReader.cpp b/source/Irrlicht/CZipReader.cpp
index 2834af1..7895d74 100644
--- a/source/Irrlicht/CZipReader.cpp
+++ b/source/Irrlicht/CZipReader.cpp
@@ -1,654 +1,654 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CZipReader.h"
#ifdef __IRR_COMPILE_WITH_ZIP_ARCHIVE_LOADER_
#include "CFileList.h"
#include "CReadFile.h"
#include "os.h"
#include "coreutil.h"
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_ZLIB_
#ifndef _IRR_USE_NON_SYSTEM_ZLIB_
#include <zlib.h> // use system lib
#else
#include "zlib/zlib.h"
#endif
#ifdef _IRR_COMPILE_WITH_ZIP_ENCRYPTION_
#include "aesGladman/fileenc.h"
#endif
#ifdef _IRR_COMPILE_WITH_BZIP2_
#ifndef _IRR_USE_NON_SYSTEM_BZLIB_
#include <bzlib.h>
#else
#include "bzip2/bzlib.h"
#endif
#endif
#ifdef _IRR_COMPILE_WITH_LZMA_
#include "lzma/LzmaDec.h"
#endif
#endif
#ifdef BZ_NO_STDIO
// This method is used for error output from bzip2.
extern "C" void bz_internal_error(int errorCode)
{
irr::os::Printer::log("Error in bzip2 handling", irr::core::stringc(errorCode), irr::ELL_ERROR);
}
#endif
namespace irr
{
namespace io
{
// -----------------------------------------------------------------------------
// zip loader
// -----------------------------------------------------------------------------
//! Constructor
CArchiveLoaderZIP::CArchiveLoaderZIP(io::IFileSystem* fs)
: FileSystem(fs)
{
#ifdef _DEBUG
setDebugName("CArchiveLoaderZIP");
#endif
}
//! returns true if the file maybe is able to be loaded by this class
bool CArchiveLoaderZIP::isALoadableFileFormat(const io::path& filename) const
{
return core::hasFileExtension(filename, "zip", "pk3") ||
core::hasFileExtension(filename, "gz", "tgz");
}
//! Check to see if the loader can create archives of this type.
bool CArchiveLoaderZIP::isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) const
{
return (fileType == EFAT_ZIP || fileType == EFAT_GZIP);
}
//! Creates an archive from the filename
/** \param file File handle to check.
\return Pointer to newly created archive, or 0 upon error. */
IFileArchive* CArchiveLoaderZIP::createArchive(const io::path& filename, bool ignoreCase, bool ignorePaths) const
{
IFileArchive *archive = 0;
io::IReadFile* file = FileSystem->createAndOpenFile(filename);
if (file)
{
archive = createArchive(file, ignoreCase, ignorePaths);
file->drop();
}
return archive;
}
//! creates/loads an archive from the file.
//! \return Pointer to the created archive. Returns 0 if loading failed.
IFileArchive* CArchiveLoaderZIP::createArchive(io::IReadFile* file, bool ignoreCase, bool ignorePaths) const
{
IFileArchive *archive = 0;
if (file)
{
file->seek(0);
u16 sig;
file->read(&sig, 2);
#ifdef __BIG_ENDIAN__
os::Byteswap::byteswap(sig);
#endif
file->seek(0);
bool isGZip = (sig == 0x8b1f);
archive = new CZipReader(file, ignoreCase, ignorePaths, isGZip);
}
return archive;
}
//! Check if the file might be loaded by this class
/** Check might look into the file.
\param file File handle to check.
\return True if file seems to be loadable. */
bool CArchiveLoaderZIP::isALoadableFileFormat(io::IReadFile* file) const
{
SZIPFileHeader header;
file->read( &header.Sig, 4 );
#ifdef __BIG_ENDIAN__
os::Byteswap::byteswap(header.Sig);
#endif
return header.Sig == 0x04034b50 || // ZIP
(header.Sig&0xffff) == 0x8b1f; // gzip
}
// -----------------------------------------------------------------------------
// zip archive
// -----------------------------------------------------------------------------
CZipReader::CZipReader(IReadFile* file, bool ignoreCase, bool ignorePaths, bool isGZip)
- : CFileList(file ? file->getFileName() : "", ignoreCase, ignorePaths), File(file), IsGZip(isGZip)
+ : CFileList((file ? file->getFileName() : io::path("")), ignoreCase, ignorePaths), File(file), IsGZip(isGZip)
{
#ifdef _DEBUG
setDebugName("CZipReader");
#endif
if (File)
{
File->grab();
// load file entries
if (IsGZip)
while (scanGZipHeader()) { }
else
while (scanZipHeader()) { }
sort();
}
}
CZipReader::~CZipReader()
{
if (File)
File->drop();
}
//! get the archive type
E_FILE_ARCHIVE_TYPE CZipReader::getType() const
{
return IsGZip ? EFAT_GZIP : EFAT_ZIP;
}
const IFileList* CZipReader::getFileList() const
{
return this;
}
#if 0
#include <windows.h>
const c8 *sigName( u32 sig )
{
switch ( sig )
{
case 0x04034b50: return "PK0304";
case 0x02014b50: return "PK0102";
case 0x06054b50: return "PK0506";
}
return "unknown";
}
bool CZipReader::scanLocalHeader2()
{
c8 buf [ 128 ];
c8 *c;
File->read( &temp.header.Sig, 4 );
#ifdef __BIG_ENDIAN__
os::Byteswap::byteswap(temp.header.Sig);
#endif
sprintf ( buf, "sig: %08x,%s,", temp.header.Sig, sigName ( temp.header.Sig ) );
OutputDebugStringA ( buf );
// Local File Header
if ( temp.header.Sig == 0x04034b50 )
{
File->read( &temp.header.VersionToExtract, sizeof( temp.header ) - 4 );
temp.zipFileName.reserve( temp.header.FilenameLength+2);
c = (c8*) temp.zipFileName.c_str();
File->read( c, temp.header.FilenameLength);
c [ temp.header.FilenameLength ] = 0;
temp.zipFileName.verify();
sprintf ( buf, "%d,'%s'\n", temp.header.CompressionMethod, c );
OutputDebugStringA ( buf );
if (temp.header.ExtraFieldLength)
{
File->seek( temp.header.ExtraFieldLength, true);
}
if (temp.header.GeneralBitFlag & ZIP_INFO_IN_DATA_DESCRIPTOR)
{
// read data descriptor
File->seek(sizeof(SZIPFileDataDescriptor), true );
}
// compressed data
temp.fileDataPosition = File->getPos();
File->seek( temp.header.DataDescriptor.CompressedSize, true);
FileList.push_back( temp );
return true;
}
// Central directory structure
if ( temp.header.Sig == 0x04034b50 )
{
//SZIPFileCentralDirFileHeader h;
//File->read( &h, sizeof( h ) - 4 );
return true;
}
// End of central dir
if ( temp.header.Sig == 0x06054b50 )
{
return true;
}
// eof
if ( temp.header.Sig == 0x02014b50 )
{
return false;
}
return false;
}
#endif
//! scans for a local header, returns false if there is no more local file header.
//! The gzip file format seems to think that there can be multiple files in a gzip file
//! but none
bool CZipReader::scanGZipHeader()
{
SZipFileEntry entry;
entry.Offset = 0;
memset(&entry.header, 0, sizeof(SZIPFileHeader));
// read header
SGZIPMemberHeader header;
if (File->read(&header, sizeof(SGZIPMemberHeader)) == sizeof(SGZIPMemberHeader))
{
#ifdef __BIG_ENDIAN__
os::Byteswap::byteswap(header.sig);
os::Byteswap::byteswap(header.time);
#endif
// check header value
if (header.sig != 0x8b1f)
return false;
// now get the file info
if (header.flags & EGZF_EXTRA_FIELDS)
{
// read lenth of extra data
u16 dataLen;
File->read(&dataLen, 2);
#ifdef __BIG_ENDIAN__
os::Byteswap::byteswap(dataLen);
#endif
// skip it
File->seek(dataLen, true);
}
io::path ZipFileName = "";
if (header.flags & EGZF_FILE_NAME)
{
c8 c;
File->read(&c, 1);
while (c)
{
ZipFileName.append(c);
File->read(&c, 1);
}
}
else
{
// no file name?
ZipFileName = Path;
core::deletePathFromFilename(ZipFileName);
// rename tgz to tar or remove gz extension
if (core::hasFileExtension(ZipFileName, "tgz"))
{
ZipFileName[ ZipFileName.size() - 2] = 'a';
ZipFileName[ ZipFileName.size() - 1] = 'r';
}
else if (core::hasFileExtension(ZipFileName, "gz"))
{
ZipFileName[ ZipFileName.size() - 3] = 0;
ZipFileName.validate();
}
}
if (header.flags & EGZF_COMMENT)
{
c8 c='a';
while (c)
File->read(&c, 1);
}
if (header.flags & EGZF_CRC16)
File->seek(2, true);
// we are now at the start of the data blocks
entry.Offset = File->getPos();
entry.header.FilenameLength = ZipFileName.size();
entry.header.CompressionMethod = header.compressionMethod;
entry.header.DataDescriptor.CompressedSize = (File->getSize() - 8) - File->getPos();
// seek to file end
File->seek(entry.header.DataDescriptor.CompressedSize, true);
// read CRC
File->read(&entry.header.DataDescriptor.CRC32, 4);
// read uncompressed size
File->read(&entry.header.DataDescriptor.UncompressedSize, 4);
#ifdef __BIG_ENDIAN__
os::Byteswap::byteswap(entry.header.DataDescriptor.CRC32);
os::Byteswap::byteswap(entry.header.DataDescriptor.UncompressedSize);
#endif
// now we've filled all the fields, this is just a standard deflate block
addItem(ZipFileName, entry.header.DataDescriptor.UncompressedSize, false, 0);
FileInfo.push_back(entry);
}
// there's only one block of data in a gzip file
return false;
}
//! scans for a local header, returns false if there is no more local file header.
bool CZipReader::scanZipHeader()
{
io::path ZipFileName = "";
SZipFileEntry entry;
entry.Offset = 0;
memset(&entry.header, 0, sizeof(SZIPFileHeader));
File->read(&entry.header, sizeof(SZIPFileHeader));
#ifdef __BIG_ENDIAN__
entry.header.Sig = os::Byteswap::byteswap(entry.header.Sig);
entry.header.VersionToExtract = os::Byteswap::byteswap(entry.header.VersionToExtract);
entry.header.GeneralBitFlag = os::Byteswap::byteswap(entry.header.GeneralBitFlag);
entry.header.CompressionMethod = os::Byteswap::byteswap(entry.header.CompressionMethod);
entry.header.LastModFileTime = os::Byteswap::byteswap(entry.header.LastModFileTime);
entry.header.LastModFileDate = os::Byteswap::byteswap(entry.header.LastModFileDate);
entry.header.DataDescriptor.CRC32 = os::Byteswap::byteswap(entry.header.DataDescriptor.CRC32);
entry.header.DataDescriptor.CompressedSize = os::Byteswap::byteswap(entry.header.DataDescriptor.CompressedSize);
entry.header.DataDescriptor.UncompressedSize = os::Byteswap::byteswap(entry.header.DataDescriptor.UncompressedSize);
entry.header.FilenameLength = os::Byteswap::byteswap(entry.header.FilenameLength);
entry.header.ExtraFieldLength = os::Byteswap::byteswap(entry.header.ExtraFieldLength);
#endif
if (entry.header.Sig != 0x04034b50)
return false; // local file headers end here.
// read filename
{
c8 *tmp = new c8 [ entry.header.FilenameLength + 2 ];
File->read(tmp, entry.header.FilenameLength);
tmp[entry.header.FilenameLength] = 0;
ZipFileName = tmp;
delete [] tmp;
}
#ifdef _IRR_COMPILE_WITH_ZIP_ENCRYPTION_
// AES encryption
if ((entry.header.GeneralBitFlag & ZIP_FILE_ENCRYPTED) && (entry.header.CompressionMethod == 99))
{
s16 restSize = entry.header.ExtraFieldLength;
SZipFileExtraHeader extraHeader;
while (restSize)
{
File->read(&extraHeader, sizeof(extraHeader));
#ifdef __BIG_ENDIAN__
extraHeader.ID = os::Byteswap::byteswap(extraHeader.ID);
extraHeader.Size = os::Byteswap::byteswap(extraHeader.Size);
#endif
restSize -= sizeof(extraHeader);
if (extraHeader.ID==(s16)0x9901)
{
SZipFileAESExtraData data;
File->read(&data, sizeof(data));
#ifdef __BIG_ENDIAN__
data.Version = os::Byteswap::byteswap(data.Version);
data.CompressionMode = os::Byteswap::byteswap(data.CompressionMode);
#endif
restSize -= sizeof(data);
if (data.Vendor[0]=='A' && data.Vendor[1]=='E')
{
// encode values into Sig
// AE-Version | Strength | ActualMode
entry.header.Sig =
((data.Version & 0xff) << 24) |
(data.EncryptionStrength << 16) |
(data.CompressionMode);
File->seek(restSize, true);
break;
}
}
}
}
// move forward length of extra field.
else
#endif
if (entry.header.ExtraFieldLength)
File->seek(entry.header.ExtraFieldLength, true);
// if bit 3 was set, read DataDescriptor, following after the compressed data
if (entry.header.GeneralBitFlag & ZIP_INFO_IN_DATA_DESCRIPTOR)
{
// read data descriptor
File->read(&entry.header.DataDescriptor, sizeof(entry.header.DataDescriptor));
#ifdef __BIG_ENDIAN__
entry.header.DataDescriptor.CRC32 = os::Byteswap::byteswap(entry.header.DataDescriptor.CRC32);
entry.header.DataDescriptor.CompressedSize = os::Byteswap::byteswap(entry.header.DataDescriptor.CompressedSize);
entry.header.DataDescriptor.UncompressedSize = os::Byteswap::byteswap(entry.header.DataDescriptor.UncompressedSize);
#endif
}
// store position in file
entry.Offset = File->getPos();
// move forward length of data
File->seek(entry.header.DataDescriptor.CompressedSize, true);
#ifdef _DEBUG
//os::Debuginfo::print("added file from archive", ZipFileName.c_str());
#endif
addItem(ZipFileName, entry.header.DataDescriptor.UncompressedSize, false, FileInfo.size());
FileInfo.push_back(entry);
return true;
}
//! opens a file by file name
IReadFile* CZipReader::createAndOpenFile(const io::path& filename)
{
s32 index = findFile(filename, false);
if (index != -1)
return createAndOpenFile(index);
return 0;
}
#ifdef _IRR_COMPILE_WITH_LZMA_
//! Used for LZMA decompression. The lib has no default memory management
namespace
{
void *SzAlloc(void *p, size_t size) { p = p; return malloc(size); }
void SzFree(void *p, void *address) { p = p; free(address); }
ISzAlloc lzmaAlloc = { SzAlloc, SzFree };
}
#endif
//! opens a file by index
IReadFile* CZipReader::createAndOpenFile(u32 index)
{
// Irrlicht supports 0, 8, 12, 14, 99
//0 - The file is stored (no compression)
//1 - The file is Shrunk
//2 - The file is Reduced with compression factor 1
//3 - The file is Reduced with compression factor 2
//4 - The file is Reduced with compression factor 3
//5 - The file is Reduced with compression factor 4
//6 - The file is Imploded
//7 - Reserved for Tokenizing compression algorithm
//8 - The file is Deflated
//9 - Reserved for enhanced Deflating
//10 - PKWARE Date Compression Library Imploding
//12 - bzip2 - Compression Method from libbz2, WinZip 10
//14 - LZMA - Compression Method, WinZip 12
//96 - Jpeg compression - Compression Method, WinZip 12
//97 - WavPack - Compression Method, WinZip 11
//98 - PPMd - Compression Method, WinZip 10
//99 - AES encryption, WinZip 9
const SZipFileEntry &e = FileInfo[Files[index].ID];
wchar_t buf[64];
s16 actualCompressionMethod=e.header.CompressionMethod;
IReadFile* decrypted=0;
u8* decryptedBuf=0;
u32 decryptedSize=e.header.DataDescriptor.CompressedSize;
#ifdef _IRR_COMPILE_WITH_ZIP_ENCRYPTION_
if ((e.header.GeneralBitFlag & ZIP_FILE_ENCRYPTED) && (e.header.CompressionMethod == 99))
{
os::Printer::log("Reading encrypted file.");
u8 salt[16]={0};
const u16 saltSize = (((e.header.Sig & 0x00ff0000) >>16)+1)*4;
File->seek(e.Offset);
File->read(salt, saltSize);
char pwVerification[2];
char pwVerificationFile[2];
File->read(pwVerification, 2);
fcrypt_ctx zctx; // the encryption context
int rc = fcrypt_init(
(e.header.Sig & 0x00ff0000) >>16,
(const unsigned char*)Password.c_str(), // the password
Password.size(), // number of bytes in password
salt, // the salt
(unsigned char*)pwVerificationFile, // on return contains password verifier
&zctx); // encryption context
if (strncmp(pwVerificationFile, pwVerification, 2))
{
os::Printer::log("Wrong password");
return 0;
}
decryptedSize= e.header.DataDescriptor.CompressedSize-saltSize-12;
decryptedBuf= new u8[decryptedSize];
u32 c = 0;
while ((c+32768)<=decryptedSize)
{
File->read(decryptedBuf+c, 32768);
fcrypt_decrypt(
decryptedBuf+c, // pointer to the data to decrypt
32768, // how many bytes to decrypt
&zctx); // decryption context
c+=32768;
}
File->read(decryptedBuf+c, decryptedSize-c);
fcrypt_decrypt(
decryptedBuf+c, // pointer to the data to decrypt
decryptedSize-c, // how many bytes to decrypt
&zctx); // decryption context
char fileMAC[10];
char resMAC[10];
rc = fcrypt_end(
(unsigned char*)resMAC, // on return contains the authentication code
&zctx); // encryption context
if (rc != 10)
{
os::Printer::log("Error on encryption closing");
delete [] decryptedBuf;
return 0;
}
File->read(fileMAC, 10);
if (strncmp(fileMAC, resMAC, 10))
{
os::Printer::log("Error on encryption check");
delete [] decryptedBuf;
return 0;
}
decrypted = io::createMemoryReadFile(decryptedBuf, decryptedSize, Files[index].FullName, true);
actualCompressionMethod = (e.header.Sig & 0xffff);
#if 0
if ((e.header.Sig & 0xff000000)==0x01000000)
{
}
else if ((e.header.Sig & 0xff000000)==0x02000000)
{
}
else
{
os::Printer::log("Unknown encryption method");
return 0;
}
#endif
}
#endif
switch(actualCompressionMethod)
{
case 0: // no compression
{
if (decrypted)
return decrypted;
else
return createLimitReadFile(Files[index].FullName, File, e.Offset, decryptedSize);
}
case 8:
{
#ifdef _IRR_COMPILE_WITH_ZLIB_
const u32 uncompressedSize = e.header.DataDescriptor.UncompressedSize;
c8* pBuf = new c8[ uncompressedSize ];
if (!pBuf)
{
swprintf ( buf, 64, L"Not enough memory for decompressing %s", Files[index].FullName.c_str() );
os::Printer::log( buf, ELL_ERROR);
if (decrypted)
decrypted->drop();
return 0;
}
u8 *pcData = decryptedBuf;
if (!pcData)
{
pcData = new u8[decryptedSize];
if (!pcData)
{
swprintf ( buf, 64, L"Not enough memory for decompressing %s", Files[index].FullName.c_str() );
os::Printer::log( buf, ELL_ERROR);
delete [] pBuf;
return 0;
}
//memset(pcData, 0, decryptedSize);
File->seek(e.Offset);
File->read(pcData, decryptedSize);
}
// Setup the inflate stream.
z_stream stream;
s32 err;
stream.next_in = (Bytef*)pcData;
stream.avail_in = (uInt)decryptedSize;
|
paupawsan/Irrlicht
|
48b49b3a1da210de423029dbc8064e2f57b6e769
|
- Fix that clones got dropped too often when SceneNodes without parent got cloned (found by Ulf). - Make sure that CAnimatedMeshSceneNode::clone calls the virtual updateAbsolutePosition for the new object. - Some whitespace changes.
|
diff --git a/changes.txt b/changes.txt
index 647ceaa..8df93e7 100644
--- a/changes.txt
+++ b/changes.txt
@@ -1,515 +1,533 @@
-----------------------------
Changes in 1.7.1 (17.02.2010)
+ - Make sure that CAnimatedMeshSceneNode::clone calls the virtual updateAbsolutePosition for the new object
+
+ - Fix that clones got dropped too often when SceneNodes without parent got cloned (found by Ulf)
+
+ - Make sure TAB is still recognized on X11 when shift+tab is pressed. This does also fix going to the previous tabstop on X11.
+
+ - Send EGET_ELEMENT_LEFT also when there won't be a new hovered element
+
+ - Update docs for EGET_ELEMENT_LEFT and EGET_ELEMENT_HOVERED
+
+ - Fix tooltips: Remove them when the element is hidden or removed (thx to seven for finding)
+
+ - Fix tooltips: Make (more) sure they don't get confused by gui-subelements
+
+ - Fix tooltips: Get faster relaunch times working
+
+ - Fix tooltips: Make sure hovered element is never the tooltip itself
+
- Fix string::remove which got in an endless loop when remove was called with an empty string (found and fixed by Ulf)
- Correctly release the GLSL shaders
- Make sure we only release an X11 atom when it was actually created
- Fix aabbox collision test, which not only broke the collision test routines, but also frustum culling, octree tests, etc.
- Fix compilation problem under OSX due to wrong glProgramParameteri usage
- mem leak in OBJ loader fixed
- Removed some default parameters to reduce ambigious situations
---------------------------
Changes in 1.7 (03.02.2010)
- Implement minimize and deminimize under OSX.
- Define sorting order for vector2d and vector3d in operators <, <=, > and >= to fix bugs 2783509 and 2783510. Operators order now by X,Y,Z and use float tolerances.
- Ogre mesh 32bit indices fixed.
- Fix tooltips for gui-elements with sub-element like IGUISpinBox (id: 2927079, found by ArakisTheKitsune)
- ITimer no longer stops when started twice
- wchar_t filesystem updates under Windows.
- Joystick POV fixed under Windows, ids fixed under OSX.
- Some updates to skinned mesh for better bones support and scaling animations.
- OSX supports external window id in creation parameters now.
- Fix bbox collision tests.
- Updates for win32 key handling
- new convenience method for flat plane creation.
- Sky dome and other meshes use VBOs by default now.
- Speed up b3d loading for files with many frames, material color flags and vertex color support enhanced.
- Add hasType to IGUIElement as a dynamic_cast substitute.
- Add another parameter to IGUISkin::draw3DWindowBackground to allow getting the client area without actually drawing
- Add function getClientRect to IGUIWindow for getting the draw-able area
- Fix bug that menus on IGUIWindows with titlebar got drawn too high (id: 2714400)
- Renamed OctTree to Octree
- Allow getting a ConstIterator from a non-const core:list
- Add swap functions to irrMath and to the core classes.
- Deprecate map::isEmpty() and replace it with map::empty() to make it similar to other base classes.
- Allow to set the logging level already in SIrrlichtCreationParameters.
- Add clearSystemMessages to devices (implemented only for Linux and Win32 so far).
- Support changing the render window from beginScene also with OpenGL driver.
- Add getMaterial2D which allows to alter the 2d render state settings, such as filtering, anti-aliasing, thickness, etc.
- Fix incorrect cursorpos for resizable windows on Windows Vista (found and patched by buffer)
- Change the beginScene window parameter from void* to SExposedVideoData&. This will allow to manage contexts for OpenGL at some point.
- Add bzip2 and LZMA decompression modes for zip loader.
- Add OBJ_TEXTURE_PATH and B3D_TEXTURE_PATH to SceneParameters to allow setting texture-paths for obj and b3d.
- Irrlicht keeps now filenames additionally to the internally used names, thereby fixing some problems with uppercase-filenames on Linux.
- Bugfix: Mousewheel no longer sends EMIE_MOUSE_WHEEL messages twice on Linux.
- Use latest jpeglib
- refactoring: E_ATTRIBUTE_TYPE and IAttribute have now own headers
- CStringWArrayAttribute speedup
- SceneNodeAnimatorFollowSpline can now loop and pingpong
- Meshviewer.example got some fast-scale buttons.
- Support AES-encrypted zip files. Should work with 128, 196, and 256 bit AES. This addition also adds a new PRNG, SHA, and other algorithms to the engine, though no interface is yet added for them. The implementation of the encryption algorithms is provided by Dr Brian Gladman.
- flattenFilename and getAbsolutePath fixed and properly added at several places.
- Added geometry shaders for OpenGL. A first version of the code was submitted by Matthew Kielan (devsh).
- Bugfix: irrArray should no longer crash when using other allocators.
- Add MaterialViewer example.
- Texture activation now back in setMaterial, which simplifies writing external material renderers (OpenGL only).
- Checkbox uses now disabled text color when disabled.
- Changed colors for window-title caption to keep them readable when not active.
- Draw sub-menus to left side if they would be outside main-window otherwise.
- Give ListBox better defaults for the ScrollBar stepsizes.
- Double and triple click events now for each mouse-button. Old events for that got removed.
- Fix adding archives twice, which caused multiple archives of the same name and type covering each other. This one required a texture name change from using backslashes to slashes under Windows.
- Give access to texture mipmaps. You can provide custom mipmap textures upon generation, regeneration, and locking.
Make sure the provided data is large enough and covers all miplevels. Also the returned pointer (from lock) will only cover the smaller data of the mipmap level dimension chosen (level 0 is the original texture).
- Separate TextureWrap mode into U and V fields
- Add mirror texture wrap modes
- windows show now active/inactive state
- remove unneeded drop/grab calls found by manik_sheeri
- fix rounding problem in IGUIElements which have EGUIA_SCALE alignments.
- MessageBox supports now automatic resizing and images.
Deprecated EGDS_MESSAGE_BOX_WIDTH and EGDS_MESSAGE_BOX_HEIGHT
- Let maya-cam animator react on a setTarget call to the camera which happened outside it's own control
- New contextmenue features:
automatic checking for checked flag.
close handling now customizable
serialization can handle incomplete xml's
setEventParent now in public interface
New function findItemWithCommandId
New function insertItem
- new vector3d::getSphericalCoordinateAngles method.
- new triangle3d::isTotalOutsideBox method.
- Newly introduced VertexManipulator interface. This allows for very easy creation of vertex manipulation algorithms. Several manipulators, e.g. vertex color changer and transformation algorithms are already available.
- createMeshWith1TCoords avoids vertex duplication
- getRotation now handles matrices with scaling as well
- Ogre format animations now supported.
- irrArray: Fixed issues with push_front and reallocation
Changed behavior for set_pointer and clear, when free_when_destroyed is false
- NPK (Nebula device archive) reader added, it's an uncompressed PAK-like format
- SSkinMeshBuffer::MoveTo* methods renamed to convertTo*
- Multiple Render Target (MRT) support added, including some enhanced blend features where supported
- Directory changing fixed for virtual file systems (Archives etc)
- Fix texture matrix init in scene manager and driver
- More draw2dimage support in software drivers
- Sphere node now properly chooses a good tesselation based on the parameters
- Active camera not registered twice anymore
- Parallax/normal map shader rotation bug under OpenGL fixed
- bump map handling for obj files fixed
- Fog serialization added
- New context menu features added
- Bounding Box updates for skinned meshes fixed
- The current FPS for an animated scene node can be queried now, added some variables to serialization
- Scrollbars fixed
- Fixed 2d vertex primitive method to correctly handle transparency
- Fullscreen handling has been enhanced for Windows, now proper resolution is restored on Alt-Tab etc.
- Cameras can now be added to the scene node without automatically activating them
Clone method added
- New video driver method getMaxTextureSize
- PAK archive reader fixed
- TRANSPARENT_ALPHA_CHANNEL_REF uses modulate to enable lighting
- LIGHTMAP_ADD now always uses add operator
- Some Unicode file system fixes
- destructor of irrString not virtual anymore, please don't derive from irrString
Some new methods added, for searching and splitting
Assignment operator optimized
- new lightness method for SColor
- draw3DTriangle now renders filled polygons, old behavior can be achieved by setting EMT_WIREFRAME
-----------------------------
Changes in 1.6.1 (13.01.2010)
- Fix pingpong for CSceneNodeAnimatorFlyStraight (found by gbox)
- Fix bug with IGUIEditBox where the cursor position is reset on text change.
- Make sure the window top-left corner on Windows is not negative on start so that Windows sytem-menu is always visible.
- Fix problem that the window did sometimes not get the keyboard focus in X11 in fullscreen. Add more debug output in case focus grabbing goes wrong.
- Fix screensize in videodriver when we didn't get the requested window size. This also prevents that gui-clicks are no longer synchronized with gui-drawing and elements can't be hit anymore.
- Bugfix: Prevent a crash when getTypeName was called for the guienvironment. EGUIET_ELEMENT got changed for this.
- Bugfix: Horizontal centered font with linebreaks draw now all lines. For example multiline TextSceneNodes work again.
- Bugfix: spinbox can no longer get in an endless loop due to floating point rounding error (found by slavik262)
- !!API change!! Disabled AntiAliasing of Lines in material default
Please enable this manually per material when sure that it won't lead to SW rendering.
- IGUIComboBox: clicking on the statictext displaying the active selection does now close and open listbox correctly. (Bug found by Reiko)
- Scrollbuttons in IGUITabControl adapt now to tab-height.
- Fix texturing of cylinder mesh
- Fix modal dialog position (found by LoneBoco: http://sourceforge.net/tracker/?func=detail&aid=2900266&group_id=74339&atid=540676)
- Fix DMF loading
- Fixing left+right special keys (ctrl, shift, alt) on Win32 (thanks to pc0de for good patch-ideas).
- Make stringarrays for enums in IGUISkin a little safer
- Add support for keys KEY_PRINT, KEY_HOME (on numpad) and KEY_NUMLOCK on Linux.
- Fix material handling in createMeshWith1TCoords
- Fix another (OldValue == NewValue) before drop()/grap(), this time in CTextureAttribute::setTexture.
- Fix LIGHTMAP_LIGHTING for D3D drivers.
- AntiAliasing disabled for debug render elements.
- Bugfix: CGUIToolBar::addButton does no longer mess up when no image is set and does now actually work with the text.
- Fix ninja animation range which got messed up a little when b3d animations got fixed (thx gbox for finding)
---------------------------
Changes in 1.6 (23.09.2009)
- Added IFileSystem::createEmptyFileList, exposed IFileList::sort, addItem and added getID
- Fix MAKE_IRR_ID so it can be used from outside the irr namespace (Micha's patch)
- Renamed some methods in ISkinnedMesh to match the official Irrlicht naming scheme according to createXXX()
- Change debug data to draw using lines instead of arrows, which is much faster. Patch by pc0de
- Fix a bug with FPS camera animator causing stutters. Patch by FuzzYspo0N
- Fix scrolling controls in CGUITabControl
- Fix a bug when getting optimal texture size in D3D drivers, by Jetro Lauha (tonic)
- Added EGDS_TITLEBARTEXT_DISTANCE_X and EGDS_TITLEBARTEXT_DISTANCE_Y to GUI, submitted by FuzzYspo0N
- Fix for UFT8 filenames displayed in file dialog, patch by MadHyde.
- Added const method for array::binary_search, potentially slow as it doesn't sort the list!
- Add support for scaling button images.
- Irrlicht can now come with multiple device types compiled in, the device to use is selected by SIrrlichtCreationParameters.DeviceType. This defaults to EIDT_BEST which automatically select the best device available starting with native, then X11, SDL and finally the console.
- Added support for EXP2 fog distribution. This required a change in the setFog parameters where now an enum value instead of the bool linear is given.
- IFileSystem changes:
- Renamed the following functions-
IFileArchive::getArchiveType to getType
IFileSystem::registerFileArchive to addFileArchive
IFileSystem::unregisterFileArchive to removeFileArchive
IFileArchive::openFile to createAndOpenFile
- New enum, E_FILE_ARCHIVE_TYPE. getType on IArchiveLoader and IFileArchive now both return this.
- IFileSystem::addFileArchive takes a parameter to specify the archive type rather always using the file extension. IFileSystem::addZipFileArchive, addFolderFileArchive and addPakFileArchive now use this but these functions are now marked as deprecated. Users should now use addFileArchive instead.
- Added TAR archive loader.
- The ZIP archive loader can now load gzip files, combined with the TAR loader this means Irrlicht now has native support for .tar.gz
Currently this must be done in two calls, for example:
fileSystem->addFileArchive("path/to/myArchive.tar.gz");
fileSystem->addFileArchive("myArchive.tar");
- Fix highlighting in IGUIEditBox where kerning pairs are used in the font. For example in future italic, OS or other custom fonts.
- IOSOperator::getTextFromClipboard returns now const c8* instead of c8*
- Support for copy&paste on linux (X11) added (fixing bug 2804014 found by Pan)
- bugfix for 2795321 found by egrath: Don't rely anymore on broken XkbSetDetectableAutoRepeat.
- bugfix: CMountPointReader::openFile no longer returns true for empty files. Corresponding test added.
- Direct3D now also uses screen coordinates in 2d mode, just like OpenGL. This means that screen coords are going from 0..ScreenWidth and 0..ScreenHeight instead of -1..1.
- ALT+F4 keypress now closes Windows SDL device
- Allow Direct3D drivers in SDL, patch by Halifax
- Added compiler error when attempting to compile with VC6.
- Use setWindowTextA in Windows device for WIN64 platform, posted by veegun
- ELL_ERROR log events are now created when shaders fail to compile or link, reported by Halan
- irrList now uses irrAllocator, fixed by Nox
- Added IGUIWindow::setDraggable and IGUIWindow::isDraggable, by Nox
- Added SGI RGB file reader by Gary Conway, for loading Silicon Graphics .rgb, .rgba, .sgi, .int and .inta textures
- Renamed setResizeAble to setResizable
- Added new device method minimizeWindow which minimizes the window (just as if the minimize button has been clicked).
- SkyDome is now serialized correctly
- Added PLY mesh reader and writer
- Ensure ListBox on combo box doesn't hang off the bottom of the GUI root, by Matthias Specht
- Made IGUIElements recalculate clipping rectangle after setNotClipped, reported by Aelis440
- Bug fix for the combo box where it showed white text instead of skin colour before being focused, fix posted by drewbacca
- EGDS_MESSAGE_BOX_HEIGHT is now honoured, bug reported by Spkka
- Fixed a bug in the edit box where events are sometimes sent to a null parent, reported by Sudi.
- Coordinate system fix for OpenGL in SDL device
- Added generic console device. You can now use Irrlicht to create and manipuate graphics on a shell where no graphics hardware
or windowing system is available. To enable it uncomment #define _IRR_USE_CONSOLE_DEVICE_ in IrrCompileConfig.h
- The console device can now present images from the software drivers and display them as ASCII art in the console
- By default it replaces the default font in the skin, to prevent fonts from being huge.
- Fixed problems with changing cursor visibility while mouse is pressed on windows
- Allow control of background drawing in listbox
- Allow control of drawing background and titlebar in windows
- Improved window serialization
- Add mouse events EMIE_MOUSE_DOUBLE_CLICK and EMIE_MOUSE_TRIPLE_CLICK (thx to Ulf for patch proposal)
- Set "ButtonStates" for mouse events also on Linux (was only for Windows formerly)
- Add Shift+Control states to mouse event
- bugfix (2003238): serialize modal screens
- allow stacking modal screens
- allowing hiding modals
- replace many IsVisible checks with virtual isVisible() checks in IGUIElement
- bugfix: reset selected row when clearing CGUITable
- adding events EGET_EDITBOX_CHANGED and EGET_EDITBOX_MARKING_CHANGED
- prevent editbox from recalculating its textbreaking each frame
- let spinbox react on each textchange without waiting for enter to prevent getting value changes without corresponding EGET_SPINBOX_CHANGED events.
- new test for zipreader
- prevent dropping objects accidentally in many set functions
- Reversed change in vector3d::normalize.
Works now again as documented and a corresponding test has been added.
Does fix bug 2770709 (https://sourceforge.net/tracker/?func=detail&aid=2770709&group_id=74339&atid=540676)
- Animations can now be paused by setting the fps to 0.
- Avoid fp-precision problem in getPickedNodeBB (see also http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=33838&highlight=).
This change might also fix the problem with picking nodes found by aanderse (http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=32890&highlight=)
- implemented isALoadableFileFormat ( File *file ) for the Archive Loader
- PixelBlend16 and PixelBlend16_simd are working for the new rules.
- bugfix. CLightSceneNode didn't correctly update it's attributes
- vector template and equals tests
also set the equal test for s32 to behave like the f32 routine.
The function equals always implements a weak test.
that means a tolerance MUST always be used if you use the equal function. default is 1.
- VideoDriver drawPixel
The HW renderes are using the alpha components for blending.
The Software Renderes and image loaders are using CImage::setPixel copy.
so setPixel is engaged to either blends or copy the pixel
default: false
- Burningvideo
added RenderMaterial EMT_SPHERE_MAP
pushed burningsvideo to 0.43
added RenderMaterial EMT_REFLECTION_2_LAYER
pushed burningsvideo to 0.44
set EMT_TRANSPARENT_ALPHA_CHANNEL_REF
to use AlphaRef 0.5 like Direct3D
One Note: in OpenGL there is know difference between sphere_map and reflection layer
both using GL_TEXTURE_GEN_MODE GL_SPHERE_MAP, whereas in d3d one time using camera_normal
on sphere and reflection on refletcion_layer.
The visual difference is that on sphere map the "image is not moving" when you rotate the
viewer. For Burning i took the opengl visual. always moving
- rename quake3 SEntity to IEntity to be confom with IShader
- fixed createMeshWith2TCoords, normals were missing during copy.
- added
//! Creates a copy of the mesh, which will only consist of S3DVertex vertices.
IMesh* CMeshManipulator::createMeshWith1TCoords(IMesh* mesh) const
- added io::IFileSystem* CSceneManager::getFileSystem()
- added virtual const c8* ISceneManager::getAnimatorTypeName(ESCENE_NODE_ANIMATOR_TYPE type);
- added CSceneNodeAnimatorFlyCircle::radiusEllipsoid.
if radiusEllipsoid == 0 the default circle animation is done
else radiusEllipsoid forms the b-axe of the ellipsoid.
-> gummiball bouncing
- added ISceneManager::createFlyStraightAnimator variable bool ping-pong
used in loop mode to device if start from beginning ( default ) or make ping-pong
-> straight bouncing
- changed IFileSystem::registerFileArchive
remove the index of the hierarchy and added a new interface method
//! move the hirarchy of the filesystem. moves sourceIndex relative up or down
virtual bool moveFileArchive( u32 sourceIndex, s32 relative ) = 0;
- bugfix and changes in SViewFrustum::SViewFrustum
wrong size of Matrices copy.
renamed E_TRANSFORMATION_STATE_2 to E_TRANSFORMATION_STATE_FRUSTUM
therefore also changed SViewFrustum::setTransformState to not tap
in the pitfall again of wrong memory...
- moved
//! EMT_ONETEXTURE_BLEND: has BlendFactor Alphablending
inline bool textureBlendFunc_hasAlpha ( E_BLEND_FACTOR factor ) const
from the material renderes ( 3x declared ) to SMaterial.h
- updated managed light example to use standard driver selection
- BurningsVideo
- LightModel reworked.
Point Light & Direction Light works for Diffuse Color as expected
Specular and Fog still have problems ( needs new pixel shader )
pushed burningsvideo to 0.42 for this major step
- removed obsolete matrix transformations
renamed E_TRANSFORMATION_STATE_2 to E_TRANSFORMATION_STATE_BURNING
- cleaned line3d.h vector3d.h template behavior.
many mixed f32/f64 implementations are here. i'm not sure if this should be
the default behavior to use f64 for example for 1.0/x value, because they
benefit from more precisions, but in my point of view the user is responsible
of choosing a vector3d<f32> or vector3d<f64>.
- added core::squareroot to irrmath.h
-> for having candidates for faster math in the same file
- added AllowZWriteOnTransparent from SceneManager to burningsvideo
-added hasAlpha() to ITexture
This info can be used for e.q to downgrade a transparent alpha channel blit
to add if the texture has no alpha channel.
- FileSystem 2.0 SUPER MASTER MAJOR API CHANGE !!!
The FileSystem is now build internally like for e.g. the image- and meshloaders.
There exists a known list of ArchiveLoaders, which know how to produce a Archive.
The Loaders and the Archives can be attached/detached on runtime.
The FileNames are now stored as core::string<c16>. where c16 is toggled between char/wchar
with the #define flag _IRR_WCHAR_FILESYSTEM, to supported unicode backends (default:off)
Replaced most (const c8* filename) to string references.
Basically the FileSystem is divided into two regions. Native and Virtual.
Native means using the backend OS.
Virtual means only use currently attached IArchives.
diff --git a/source/Irrlicht/CAnimatedMeshSceneNode.cpp b/source/Irrlicht/CAnimatedMeshSceneNode.cpp
index 18ce8aa..61d4fd7 100644
--- a/source/Irrlicht/CAnimatedMeshSceneNode.cpp
+++ b/source/Irrlicht/CAnimatedMeshSceneNode.cpp
@@ -551,548 +551,553 @@ video::SMaterial& CAnimatedMeshSceneNode::getMaterial(u32 i)
}
//! returns amount of materials used by this scene node.
u32 CAnimatedMeshSceneNode::getMaterialCount() const
{
return Materials.size();
}
//! Creates shadow volume scene node as child of this node
//! and returns a pointer to it.
IShadowVolumeSceneNode* CAnimatedMeshSceneNode::addShadowVolumeSceneNode(const IMesh* shadowMesh,
s32 id, bool zfailmethod, f32 infinity)
{
if (!SceneManager->getVideoDriver()->queryFeature(video::EVDF_STENCIL_BUFFER))
return 0;
if (Shadow)
return Shadow;
if (!shadowMesh)
shadowMesh = Mesh; // if null is given, use the mesh of node
Shadow = new CShadowVolumeSceneNode(shadowMesh, this, SceneManager, id, zfailmethod, infinity);
return Shadow;
}
//! Returns a pointer to a child node, which has the same transformation as
//! the corresponding joint, if the mesh in this scene node is a skinned mesh.
IBoneSceneNode* CAnimatedMeshSceneNode::getJointNode(const c8* jointName)
{
if (!Mesh || Mesh->getMeshType() != EAMT_SKINNED)
{
os::Printer::log("No mesh, or mesh not of skinned mesh type", ELL_WARNING);
return 0;
}
checkJoints();
ISkinnedMesh *skinnedMesh=(ISkinnedMesh*)Mesh;
const s32 number = skinnedMesh->getJointNumber(jointName);
if (number == -1)
{
os::Printer::log("Joint with specified name not found in skinned mesh.", jointName, ELL_WARNING);
return 0;
}
if ((s32)JointChildSceneNodes.size() <= number)
{
os::Printer::log("Joint was found in mesh, but is not loaded into node", jointName, ELL_WARNING);
return 0;
}
return getJointNode((u32)number);
}
//! Returns a pointer to a child node, which has the same transformation as
//! the corresponding joint, if the mesh in this scene node is a skinned mesh.
IBoneSceneNode* CAnimatedMeshSceneNode::getJointNode(u32 jointID)
{
if (!Mesh || Mesh->getMeshType() != EAMT_SKINNED)
{
os::Printer::log("No mesh, or mesh not of skinned mesh type", ELL_WARNING);
return 0;
}
checkJoints();
if (JointChildSceneNodes.size() <= jointID)
{
os::Printer::log("Joint not loaded into node", ELL_WARNING);
return 0;
}
return JointChildSceneNodes[jointID];
}
//! Gets joint count.
u32 CAnimatedMeshSceneNode::getJointCount() const
{
if (!Mesh || Mesh->getMeshType() != EAMT_SKINNED)
return 0;
ISkinnedMesh *skinnedMesh=(ISkinnedMesh*)Mesh;
return skinnedMesh->getJointCount();
}
//! Returns a pointer to a child node, which has the same transformation as
//! the corresponding joint, if the mesh in this scene node is a ms3d mesh.
ISceneNode* CAnimatedMeshSceneNode::getMS3DJointNode(const c8* jointName)
{
return getJointNode(jointName);
}
//! Returns a pointer to a child node, which has the same transformation as
//! the corresponding joint, if the mesh in this scene node is a .x mesh.
ISceneNode* CAnimatedMeshSceneNode::getXJointNode(const c8* jointName)
{
return getJointNode(jointName);
}
//! Removes a child from this scene node.
//! Implemented here, to be able to remove the shadow properly, if there is one,
//! or to remove attached childs.
bool CAnimatedMeshSceneNode::removeChild(ISceneNode* child)
{
if (child && Shadow == child)
{
Shadow->drop();
Shadow = 0;
}
if (ISceneNode::removeChild(child))
{
if (JointsUsed) //stop weird bugs caused while changing parents as the joints are being created
{
for (u32 i=0; i<JointChildSceneNodes.size(); ++i)
if (JointChildSceneNodes[i] == child)
{
JointChildSceneNodes[i] = 0; //remove link to child
return true;
}
}
return true;
}
return false;
}
//! Starts a MD2 animation.
bool CAnimatedMeshSceneNode::setMD2Animation(EMD2_ANIMATION_TYPE anim)
{
if (!Mesh || Mesh->getMeshType() != EAMT_MD2)
return false;
IAnimatedMeshMD2* md = (IAnimatedMeshMD2*)Mesh;
s32 begin, end, speed;
md->getFrameLoop(anim, begin, end, speed);
setAnimationSpeed( f32(speed) );
setFrameLoop(begin, end);
return true;
}
//! Starts a special MD2 animation.
bool CAnimatedMeshSceneNode::setMD2Animation(const c8* animationName)
{
if (!Mesh || Mesh->getMeshType() != EAMT_MD2)
return false;
IAnimatedMeshMD2* md = (IAnimatedMeshMD2*)Mesh;
s32 begin, end, speed;
if (!md->getFrameLoop(animationName, begin, end, speed))
return false;
setAnimationSpeed( (f32)speed );
setFrameLoop(begin, end);
return true;
}
//! Sets looping mode which is on by default. If set to false,
//! animations will not be looped.
void CAnimatedMeshSceneNode::setLoopMode(bool playAnimationLooped)
{
Looping = playAnimationLooped;
}
//! Sets a callback interface which will be called if an animation
//! playback has ended. Set this to 0 to disable the callback again.
void CAnimatedMeshSceneNode::setAnimationEndCallback(IAnimationEndCallBack* callback)
{
if (callback == LoopCallBack)
return;
if (LoopCallBack)
LoopCallBack->drop();
LoopCallBack = callback;
if (LoopCallBack)
LoopCallBack->grab();
}
//! Sets if the scene node should not copy the materials of the mesh but use them in a read only style.
void CAnimatedMeshSceneNode::setReadOnlyMaterials(bool readonly)
{
ReadOnlyMaterials = readonly;
}
//! Returns if the scene node should not copy the materials of the mesh but use them in a read only style
bool CAnimatedMeshSceneNode::isReadOnlyMaterials() const
{
return ReadOnlyMaterials;
}
//! Writes attributes of the scene node.
void CAnimatedMeshSceneNode::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const
{
IAnimatedMeshSceneNode::serializeAttributes(out, options);
out->addString("Mesh", SceneManager->getMeshCache()->getMeshName(Mesh).getPath().c_str());
out->addBool("Looping", Looping);
out->addBool("ReadOnlyMaterials", ReadOnlyMaterials);
out->addFloat("FramesPerSecond", FramesPerSecond);
out->addInt("StartFrame", StartFrame);
out->addInt("EndFrame", EndFrame);
}
//! Reads attributes of the scene node.
void CAnimatedMeshSceneNode::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
IAnimatedMeshSceneNode::deserializeAttributes(in, options);
io::path oldMeshStr = SceneManager->getMeshCache()->getMeshName(Mesh);
io::path newMeshStr = in->getAttributeAsString("Mesh");
Looping = in->getAttributeAsBool("Looping");
ReadOnlyMaterials = in->getAttributeAsBool("ReadOnlyMaterials");
FramesPerSecond = in->getAttributeAsFloat("FramesPerSecond");
StartFrame = in->getAttributeAsInt("StartFrame");
EndFrame = in->getAttributeAsInt("EndFrame");
if (newMeshStr != "" && oldMeshStr != newMeshStr)
{
IAnimatedMesh* newAnimatedMesh = SceneManager->getMesh(newMeshStr.c_str());
if (newAnimatedMesh)
setMesh(newAnimatedMesh);
}
// TODO: read animation names instead of frame begin and ends
}
//! Sets a new mesh
void CAnimatedMeshSceneNode::setMesh(IAnimatedMesh* mesh)
{
if (!mesh)
return; // won't set null mesh
if (Mesh != mesh)
{
if (Mesh)
Mesh->drop();
Mesh = mesh;
// grab the mesh (it's non-null!)
Mesh->grab();
}
// get materials and bounding box
Box = Mesh->getBoundingBox();
IMesh* m = Mesh->getMesh(0,0);
if (m)
{
Materials.clear();
Materials.reallocate(m->getMeshBufferCount());
for (u32 i=0; i<m->getMeshBufferCount(); ++i)
{
IMeshBuffer* mb = m->getMeshBuffer(i);
if (mb)
Materials.push_back(mb->getMaterial());
else
Materials.push_back(video::SMaterial());
}
}
// get start and begin time
setFrameLoop ( 0, Mesh->getFrameCount() );
}
// returns the absolute transformation for a special MD3 Tag if the mesh is a md3 mesh,
// or the absolutetransformation if it's a normal scenenode
const SMD3QuaternionTag* CAnimatedMeshSceneNode::getMD3TagTransformation( const core::stringc & tagname)
{
return MD3Special ? MD3Special->AbsoluteTagList.get ( tagname ) : 0;
}
//! updates the absolute position based on the relative and the parents position
void CAnimatedMeshSceneNode::updateAbsolutePosition()
{
IAnimatedMeshSceneNode::updateAbsolutePosition();
if (!Mesh || Mesh->getMeshType() != EAMT_MD3)
return;
SMD3QuaternionTagList *taglist;
taglist = ( (IAnimatedMeshMD3*) Mesh )->getTagList ( (s32)getFrameNr(),255,getStartFrame (),getEndFrame () );
if (taglist)
{
if (!MD3Special)
{
MD3Special = new SMD3Special();
}
SMD3QuaternionTag parent ( MD3Special->Tagname );
if (Parent && Parent->getType() == ESNT_ANIMATED_MESH)
{
const SMD3QuaternionTag * p = ((IAnimatedMeshSceneNode*) Parent)->getMD3TagTransformation
( MD3Special->Tagname );
if (p)
parent = *p;
}
SMD3QuaternionTag relative( RelativeTranslation, RelativeRotation );
MD3Special->AbsoluteTagList.set_used ( taglist->size () );
for ( u32 i=0; i!= taglist->size (); ++i )
{
MD3Special->AbsoluteTagList[i].position = parent.position + (*taglist)[i].position + relative.position;
MD3Special->AbsoluteTagList[i].rotation = parent.rotation * (*taglist)[i].rotation * relative.rotation;
}
}
}
//! Set the joint update mode (0-unused, 1-get joints only, 2-set joints only, 3-move and set)
void CAnimatedMeshSceneNode::setJointMode(E_JOINT_UPDATE_ON_RENDER mode)
{
checkJoints();
//if (mode<0) mode=0;
//if (mode>3) mode=3;
JointMode=mode;
}
//! Sets the transition time in seconds (note: This needs to enable joints, and setJointmode maybe set to 2)
//! you must call animateJoints(), or the mesh will not animate
void CAnimatedMeshSceneNode::setTransitionTime(f32 time)
{
if (time != 0.0f)
{
checkJoints();
setJointMode(EJUOR_CONTROL);
TransitionTime = (u32)core::floor32(time*1000.0f);
}
}
//! render mesh ignoring its transformation. Used with ragdolls. (culling is unaffected)
void CAnimatedMeshSceneNode::setRenderFromIdentity( bool On )
{
RenderFromIdentity=On;
}
//! updates the joint positions of this mesh
void CAnimatedMeshSceneNode::animateJoints(bool CalculateAbsolutePositions)
{
checkJoints();
if (Mesh && Mesh->getMeshType() == EAMT_SKINNED )
{
if (JointsUsed)
{
f32 frame = getFrameNr(); //old?
CSkinnedMesh* skinnedMesh=reinterpret_cast<CSkinnedMesh*>(Mesh);
skinnedMesh->transferOnlyJointsHintsToMesh( JointChildSceneNodes );
skinnedMesh->animateMesh(frame, 1.0f);
skinnedMesh->recoverJointsFromMesh( JointChildSceneNodes);
//-----------------------------------------
// Transition
//-----------------------------------------
if (Transiting != 0.f)
{
//Check the array is big enough (not really needed)
if (PretransitingSave.size()<JointChildSceneNodes.size())
{
for(u32 n=PretransitingSave.size(); n<JointChildSceneNodes.size(); ++n)
PretransitingSave.push_back(core::matrix4());
}
for (u32 n=0; n<JointChildSceneNodes.size(); ++n)
{
//------Position------
JointChildSceneNodes[n]->setPosition(
core::lerp(
PretransitingSave[n].getTranslation(),
JointChildSceneNodes[n]->getPosition(),
TransitingBlend));
//------Rotation------
//Code is slow, needs to be fixed up
const core::quaternion RotationStart(PretransitingSave[n].getRotationDegrees()*core::DEGTORAD);
const core::quaternion RotationEnd(JointChildSceneNodes[n]->getRotation()*core::DEGTORAD);
core::quaternion QRotation;
QRotation.slerp(RotationStart, RotationEnd, TransitingBlend);
core::vector3df tmpVector;
QRotation.toEuler(tmpVector);
tmpVector*=core::RADTODEG; //convert from radians back to degrees
JointChildSceneNodes[n]->setRotation( tmpVector );
//------Scale------
//JointChildSceneNodes[n]->setScale(
// core::lerp(
// PretransitingSave[n].getScale(),
// JointChildSceneNodes[n]->getScale(),
// TransitingBlend));
}
}
if (CalculateAbsolutePositions)
{
//---slow---
for (u32 n=0;n<JointChildSceneNodes.size();++n)
{
if (JointChildSceneNodes[n]->getParent()==this)
{
JointChildSceneNodes[n]->updateAbsolutePositionOfAllChildren(); //temp, should be an option
}
}
}
}
}
}
/*!
*/
void CAnimatedMeshSceneNode::checkJoints()
{
if (!Mesh || Mesh->getMeshType() != EAMT_SKINNED)
return;
if (!JointsUsed)
{
//Create joints for SkinnedMesh
((CSkinnedMesh*)Mesh)->createJoints(JointChildSceneNodes, this, SceneManager);
((CSkinnedMesh*)Mesh)->recoverJointsFromMesh(JointChildSceneNodes);
JointsUsed=true;
JointMode=EJUOR_READ;
}
}
/*!
*/
void CAnimatedMeshSceneNode::beginTransition()
{
if (!JointsUsed)
return;
if (TransitionTime != 0)
{
//Check the array is big enough
if (PretransitingSave.size()<JointChildSceneNodes.size())
{
for(u32 n=PretransitingSave.size(); n<JointChildSceneNodes.size(); ++n)
PretransitingSave.push_back(core::matrix4());
}
//Copy the position of joints
for (u32 n=0;n<JointChildSceneNodes.size();++n)
PretransitingSave[n]=JointChildSceneNodes[n]->getRelativeTransformation();
Transiting = core::reciprocal((f32)TransitionTime);
}
TransitingBlend = 0.f;
}
/*!
*/
ISceneNode* CAnimatedMeshSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager)
{
if (!newParent) newParent = Parent;
if (!newManager) newManager = SceneManager;
CAnimatedMeshSceneNode * newNode =
- new CAnimatedMeshSceneNode(Mesh, newParent, newManager, ID, RelativeTranslation,
+ new CAnimatedMeshSceneNode(Mesh, NULL, newManager, ID, RelativeTranslation,
RelativeRotation, RelativeScale);
+ if ( newParent )
+ {
+ newNode->setParent(newParent); // not in constructor because virtual overload for updateAbsolutePosition won't be called
+ newNode->drop();
+ }
+
newNode->cloneMembers(this, newManager);
newNode->Materials = Materials;
newNode->Box = Box;
newNode->Mesh = Mesh;
newNode->BeginFrameTime = BeginFrameTime;
newNode->StartFrame = StartFrame;
newNode->EndFrame = EndFrame;
newNode->FramesPerSecond = FramesPerSecond;
newNode->CurrentFrameNr = CurrentFrameNr;
newNode->JointMode = JointMode;
newNode->JointsUsed = JointsUsed;
newNode->TransitionTime = TransitionTime;
newNode->Transiting = Transiting;
newNode->TransitingBlend = TransitingBlend;
newNode->Looping = Looping;
newNode->ReadOnlyMaterials = ReadOnlyMaterials;
newNode->LoopCallBack = LoopCallBack;
newNode->PassCount = PassCount;
newNode->Shadow = Shadow;
newNode->JointChildSceneNodes = JointChildSceneNodes;
newNode->PretransitingSave = PretransitingSave;
newNode->RenderFromIdentity = RenderFromIdentity;
newNode->MD3Special = MD3Special;
- (void)newNode->drop();
return newNode;
}
} // end namespace scene
} // end namespace irr
diff --git a/source/Irrlicht/CBillboardSceneNode.cpp b/source/Irrlicht/CBillboardSceneNode.cpp
index 2e07989..2980834 100644
--- a/source/Irrlicht/CBillboardSceneNode.cpp
+++ b/source/Irrlicht/CBillboardSceneNode.cpp
@@ -1,241 +1,242 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CBillboardSceneNode.h"
#include "IVideoDriver.h"
#include "ISceneManager.h"
#include "ICameraSceneNode.h"
#include "os.h"
namespace irr
{
namespace scene
{
//! constructor
CBillboardSceneNode::CBillboardSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id,
const core::vector3df& position, const core::dimension2d<f32>& size,
video::SColor colorTop, video::SColor colorBottom)
: IBillboardSceneNode(parent, mgr, id, position)
{
#ifdef _DEBUG
setDebugName("CBillboardSceneNode");
#endif
setSize(size);
indices[0] = 0;
indices[1] = 2;
indices[2] = 1;
indices[3] = 0;
indices[4] = 3;
indices[5] = 2;
vertices[0].TCoords.set(1.0f, 1.0f);
vertices[0].Color = colorBottom;
vertices[1].TCoords.set(1.0f, 0.0f);
vertices[1].Color = colorTop;
vertices[2].TCoords.set(0.0f, 0.0f);
vertices[2].Color = colorTop;
vertices[3].TCoords.set(0.0f, 1.0f);
vertices[3].Color = colorBottom;
}
//! pre render event
void CBillboardSceneNode::OnRegisterSceneNode()
{
if (IsVisible)
SceneManager->registerNodeForRendering(this);
ISceneNode::OnRegisterSceneNode();
}
//! render
void CBillboardSceneNode::render()
{
video::IVideoDriver* driver = SceneManager->getVideoDriver();
ICameraSceneNode* camera = SceneManager->getActiveCamera();
if (!camera || !driver)
return;
// make billboard look to camera
core::vector3df pos = getAbsolutePosition();
core::vector3df campos = camera->getAbsolutePosition();
core::vector3df target = camera->getTarget();
core::vector3df up = camera->getUpVector();
core::vector3df view = target - campos;
view.normalize();
core::vector3df horizontal = up.crossProduct(view);
if ( horizontal.getLength() == 0 )
{
horizontal.set(up.Y,up.X,up.Z);
}
horizontal.normalize();
horizontal *= 0.5f * Size.Width;
core::vector3df vertical = horizontal.crossProduct(view);
vertical.normalize();
vertical *= 0.5f * Size.Height;
view *= -1.0f;
for (s32 i=0; i<4; ++i)
vertices[i].Normal = view;
vertices[0].Pos = pos + horizontal + vertical;
vertices[1].Pos = pos + horizontal - vertical;
vertices[2].Pos = pos - horizontal - vertical;
vertices[3].Pos = pos - horizontal + vertical;
// draw
if ( DebugDataVisible & scene::EDS_BBOX )
{
driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
video::SMaterial m;
m.Lighting = false;
driver->setMaterial(m);
driver->draw3DBox(BBox, video::SColor(0,208,195,152));
}
driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
driver->setMaterial(Material);
driver->drawIndexedTriangleList(vertices, 4, indices, 2);
}
//! returns the axis aligned bounding box of this node
const core::aabbox3d<f32>& CBillboardSceneNode::getBoundingBox() const
{
return BBox;
}
//! sets the size of the billboard
void CBillboardSceneNode::setSize(const core::dimension2d<f32>& size)
{
Size = size;
if (Size.Width == 0.0f)
Size.Width = 1.0f;
if (Size.Height == 0.0f )
Size.Height = 1.0f;
f32 avg = (size.Width + size.Height)/6;
BBox.MinEdge.set(-avg,-avg,-avg);
BBox.MaxEdge.set(avg,avg,avg);
}
video::SMaterial& CBillboardSceneNode::getMaterial(u32 i)
{
return Material;
}
//! returns amount of materials used by this scene node.
u32 CBillboardSceneNode::getMaterialCount() const
{
return 1;
}
//! gets the size of the billboard
const core::dimension2d<f32>& CBillboardSceneNode::getSize() const
{
return Size;
}
//! Writes attributes of the scene node.
void CBillboardSceneNode::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const
{
IBillboardSceneNode::serializeAttributes(out, options);
out->addFloat("Width", Size.Width);
out->addFloat("Height", Size.Height);
out->addColor ("Shade_Top", vertices[1].Color );
out->addColor ("Shade_Down", vertices[0].Color );
}
//! Reads attributes of the scene node.
void CBillboardSceneNode::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
IBillboardSceneNode::deserializeAttributes(in, options);
Size.Width = in->getAttributeAsFloat("Width");
Size.Height = in->getAttributeAsFloat("Height");
vertices[1].Color = in->getAttributeAsColor ( "Shade_Top" );
vertices[0].Color = in->getAttributeAsColor ( "Shade_Down" );
setSize(Size);
}
//! Set the color of all vertices of the billboard
//! \param overallColor: the color to set
void CBillboardSceneNode::setColor(const video::SColor & overallColor)
{
for(u32 vertex = 0; vertex < 4; ++vertex)
vertices[vertex].Color = overallColor;
}
//! Set the color of the top and bottom vertices of the billboard
//! \param topColor: the color to set the top vertices
//! \param bottomColor: the color to set the bottom vertices
void CBillboardSceneNode::setColor(const video::SColor & topColor, const video::SColor & bottomColor)
{
vertices[0].Color = bottomColor;
vertices[1].Color = topColor;
vertices[2].Color = topColor;
vertices[3].Color = bottomColor;
}
//! Gets the color of the top and bottom vertices of the billboard
//! \param[out] topColor: stores the color of the top vertices
//! \param[out] bottomColor: stores the color of the bottom vertices
void CBillboardSceneNode::getColor(video::SColor & topColor, video::SColor & bottomColor) const
{
bottomColor = vertices[0].Color;
topColor = vertices[1].Color;
}
//! Creates a clone of this scene node and its children.
ISceneNode* CBillboardSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager)
{
if (!newParent)
newParent = Parent;
if (!newManager)
newManager = SceneManager;
- CBillboardSceneNode* nb = new CBillboardSceneNode(newParent,
+ CBillboardSceneNode* nb = new CBillboardSceneNode(newParent,
newManager, ID, RelativeTranslation, Size);
nb->cloneMembers(this, newManager);
nb->Material = Material;
- nb->drop();
+ if ( newParent )
+ nb->drop();
return nb;
}
} // end namespace scene
} // end namespace irr
diff --git a/source/Irrlicht/CCameraSceneNode.cpp b/source/Irrlicht/CCameraSceneNode.cpp
index 529aab9..00259ed 100644
--- a/source/Irrlicht/CCameraSceneNode.cpp
+++ b/source/Irrlicht/CCameraSceneNode.cpp
@@ -1,368 +1,369 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CCameraSceneNode.h"
#include "ISceneManager.h"
#include "IVideoDriver.h"
#include "os.h"
namespace irr
{
namespace scene
{
//! constructor
-CCameraSceneNode::CCameraSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id,
+CCameraSceneNode::CCameraSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id,
const core::vector3df& position, const core::vector3df& lookat)
: ICameraSceneNode(parent, mgr, id, position),
Target(lookat), UpVector(0.0f, 1.0f, 0.0f), ZNear(1.0f), ZFar(3000.0f),
InputReceiverEnabled(true), TargetAndRotationAreBound(false)
{
#ifdef _DEBUG
setDebugName("CCameraSceneNode");
#endif
// set default projection
- Fovy = core::PI / 2.5f; // Field of view, in radians.
+ Fovy = core::PI / 2.5f; // Field of view, in radians.
const video::IVideoDriver* const d = mgr?mgr->getVideoDriver():0;
if (d)
Aspect = (f32)d->getCurrentRenderTargetSize().Width /
(f32)d->getCurrentRenderTargetSize().Height;
else
- Aspect = 4.0f / 3.0f; // Aspect ratio.
+ Aspect = 4.0f / 3.0f; // Aspect ratio.
recalculateProjectionMatrix();
recalculateViewArea();
}
//! Disables or enables the camera to get key or mouse inputs.
void CCameraSceneNode::setInputReceiverEnabled(bool enabled)
{
InputReceiverEnabled = enabled;
}
//! Returns if the input receiver of the camera is currently enabled.
bool CCameraSceneNode::isInputReceiverEnabled() const
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return InputReceiverEnabled;
}
//! Sets the projection matrix of the camera.
/** The core::matrix4 class has some methods
to build a projection matrix. e.g: core::matrix4::buildProjectionMatrixPerspectiveFovLH
\param projection: The new projection matrix of the camera. */
void CCameraSceneNode::setProjectionMatrix(const core::matrix4& projection, bool isOrthogonal)
{
IsOrthogonal = isOrthogonal;
ViewArea.getTransform ( video::ETS_PROJECTION ) = projection;
}
//! Gets the current projection matrix of the camera
//! \return Returns the current projection matrix of the camera.
const core::matrix4& CCameraSceneNode::getProjectionMatrix() const
{
return ViewArea.getTransform ( video::ETS_PROJECTION );
}
//! Gets the current view matrix of the camera
//! \return Returns the current view matrix of the camera.
const core::matrix4& CCameraSceneNode::getViewMatrix() const
{
return ViewArea.getTransform ( video::ETS_VIEW );
}
//! Sets a custom view matrix affector. The matrix passed here, will be
//! multiplied with the view matrix when it gets updated.
//! This allows for custom camera setups like, for example, a reflection camera.
/** \param affector: The affector matrix. */
void CCameraSceneNode::setViewMatrixAffector(const core::matrix4& affector)
{
Affector = affector;
}
//! Gets the custom view matrix affector.
const core::matrix4& CCameraSceneNode::getViewMatrixAffector() const
{
return Affector;
}
//! It is possible to send mouse and key events to the camera. Most cameras
-//! may ignore this input, but camera scene nodes which are created for
+//! may ignore this input, but camera scene nodes which are created for
//! example with scene::ISceneManager::addMayaCameraSceneNode or
//! scene::ISceneManager::addFPSCameraSceneNode, may want to get this input
-//! for changing their position, look at target or whatever.
+//! for changing their position, look at target or whatever.
bool CCameraSceneNode::OnEvent(const SEvent& event)
{
if (!InputReceiverEnabled)
return false;
// send events to event receiving animators
ISceneNodeAnimatorList::Iterator ait = Animators.begin();
-
+
for (; ait != Animators.end(); ++ait)
if ((*ait)->isEventReceiverEnabled() && (*ait)->OnEvent(event))
return true;
// if nobody processed the event, return false
return false;
}
//! sets the look at target of the camera
//! \param pos: Look at target of the camera.
void CCameraSceneNode::setTarget(const core::vector3df& pos)
{
Target = pos;
if(TargetAndRotationAreBound)
{
const core::vector3df toTarget = Target - getAbsolutePosition();
ISceneNode::setRotation(toTarget.getHorizontalAngle());
}
}
//! Sets the rotation of the node.
/** This only modifies the relative rotation of the node.
If the camera's target and rotation are bound ( @see bindTargetAndRotation() )
then calling this will also change the camera's target to match the rotation.
\param rotation New rotation of the node in degrees. */
void CCameraSceneNode::setRotation(const core::vector3df& rotation)
{
if(TargetAndRotationAreBound)
Target = getAbsolutePosition() + rotation.rotationToDirection();
ISceneNode::setRotation(rotation);
}
//! Gets the current look at target of the camera
//! \return Returns the current look at target of the camera
const core::vector3df& CCameraSceneNode::getTarget() const
{
return Target;
}
//! sets the up vector of the camera
//! \param pos: New upvector of the camera.
void CCameraSceneNode::setUpVector(const core::vector3df& pos)
{
UpVector = pos;
}
//! Gets the up vector of the camera.
//! \return Returns the up vector of the camera.
const core::vector3df& CCameraSceneNode::getUpVector() const
{
return UpVector;
}
-f32 CCameraSceneNode::getNearValue() const
+f32 CCameraSceneNode::getNearValue() const
{
return ZNear;
}
-f32 CCameraSceneNode::getFarValue() const
+f32 CCameraSceneNode::getFarValue() const
{
return ZFar;
}
-f32 CCameraSceneNode::getAspectRatio() const
+f32 CCameraSceneNode::getAspectRatio() const
{
return Aspect;
}
-f32 CCameraSceneNode::getFOV() const
+f32 CCameraSceneNode::getFOV() const
{
return Fovy;
}
void CCameraSceneNode::setNearValue(f32 f)
{
ZNear = f;
recalculateProjectionMatrix();
}
void CCameraSceneNode::setFarValue(f32 f)
{
ZFar = f;
recalculateProjectionMatrix();
}
void CCameraSceneNode::setAspectRatio(f32 f)
{
Aspect = f;
recalculateProjectionMatrix();
}
void CCameraSceneNode::setFOV(f32 f)
{
Fovy = f;
recalculateProjectionMatrix();
}
void CCameraSceneNode::recalculateProjectionMatrix()
{
ViewArea.getTransform ( video::ETS_PROJECTION ).buildProjectionMatrixPerspectiveFovLH(Fovy, Aspect, ZNear, ZFar);
}
//! prerender
void CCameraSceneNode::OnRegisterSceneNode()
{
if ( SceneManager->getActiveCamera () == this )
SceneManager->registerNodeForRendering(this, ESNRP_CAMERA);
ISceneNode::OnRegisterSceneNode();
}
//! render
void CCameraSceneNode::render()
-{
+{
core::vector3df pos = getAbsolutePosition();
core::vector3df tgtv = Target - pos;
tgtv.normalize();
// if upvector and vector to the target are the same, we have a
// problem. so solve this problem:
core::vector3df up = UpVector;
up.normalize();
f32 dp = tgtv.dotProduct(up);
if ( core::equals(core::abs_<f32>(dp), 1.f) )
{
up.X += 0.5f;
}
ViewArea.getTransform(video::ETS_VIEW).buildCameraLookAtMatrixLH(pos, Target, up);
ViewArea.getTransform(video::ETS_VIEW) *= Affector;
recalculateViewArea();
video::IVideoDriver* driver = SceneManager->getVideoDriver();
if ( driver)
{
driver->setTransform(video::ETS_PROJECTION, ViewArea.getTransform ( video::ETS_PROJECTION) );
driver->setTransform(video::ETS_VIEW, ViewArea.getTransform ( video::ETS_VIEW) );
}
}
//! returns the axis aligned bounding box of this node
const core::aabbox3d<f32>& CCameraSceneNode::getBoundingBox() const
{
return ViewArea.getBoundingBox();
}
//! returns the view frustum. needed sometimes by bsp or lod render nodes.
const SViewFrustum* CCameraSceneNode::getViewFrustum() const
{
return &ViewArea;
}
void CCameraSceneNode::recalculateViewArea()
{
ViewArea.cameraPosition = getAbsolutePosition();
core::matrix4 m(core::matrix4::EM4CONST_NOTHING);
m.setbyproduct_nocheck(ViewArea.getTransform(video::ETS_PROJECTION),
ViewArea.getTransform(video::ETS_VIEW));
ViewArea.setFrom(m);
}
//! Writes attributes of the scene node.
void CCameraSceneNode::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const
{
ISceneNode::serializeAttributes(out, options);
out->addVector3d("Target", Target);
out->addVector3d("UpVector", UpVector);
out->addFloat("Fovy", Fovy);
out->addFloat("Aspect", Aspect);
out->addFloat("ZNear", ZNear);
out->addFloat("ZFar", ZFar);
out->addBool("Binding", TargetAndRotationAreBound);
}
//! Reads attributes of the scene node.
void CCameraSceneNode::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
ISceneNode::deserializeAttributes(in, options);
Target = in->getAttributeAsVector3d("Target");
UpVector = in->getAttributeAsVector3d("UpVector");
Fovy = in->getAttributeAsFloat("Fovy");
Aspect = in->getAttributeAsFloat("Aspect");
ZNear = in->getAttributeAsFloat("ZNear");
ZFar = in->getAttributeAsFloat("ZFar");
TargetAndRotationAreBound = in->getAttributeAsBool("Binding");
recalculateProjectionMatrix();
- recalculateViewArea();
+ recalculateViewArea();
}
//! Set the binding between the camera's rotation adn target.
void CCameraSceneNode::bindTargetAndRotation(bool bound)
{
TargetAndRotationAreBound = bound;
}
//! Gets the binding between the camera's rotation and target.
bool CCameraSceneNode::getTargetAndRotationBinding(void) const
{
return TargetAndRotationAreBound;
}
//! Creates a clone of this scene node and its children.
ISceneNode* CCameraSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager)
{
if (!newParent)
newParent = Parent;
if (!newManager)
newManager = SceneManager;
- CCameraSceneNode* nb = new CCameraSceneNode(newParent,
+ CCameraSceneNode* nb = new CCameraSceneNode(newParent,
newManager, ID, RelativeTranslation, Target);
nb->cloneMembers(this, newManager);
- nb->drop();
+ if ( newParent )
+ nb->drop();
return nb;
}
} // end namespace
} // end namespace
diff --git a/source/Irrlicht/CCubeSceneNode.cpp b/source/Irrlicht/CCubeSceneNode.cpp
index dfd6c00..614a2b8 100644
--- a/source/Irrlicht/CCubeSceneNode.cpp
+++ b/source/Irrlicht/CCubeSceneNode.cpp
@@ -1,206 +1,207 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CCubeSceneNode.h"
#include "IVideoDriver.h"
#include "ISceneManager.h"
#include "S3DVertex.h"
#include "SMeshBuffer.h"
#include "os.h"
namespace irr
{
namespace scene
{
/*
011 111
/6,8------/5 y
/ | / | ^ z
/ | / | | /
010 3,9-------2 | |/
| 7- - -10,4 101 *---->x
| / | /
|/ | /
0------11,1/
- 000 100
+ 000 100
*/
//! constructor
CCubeSceneNode::CCubeSceneNode(f32 size, ISceneNode* parent, ISceneManager* mgr,
s32 id, const core::vector3df& position,
const core::vector3df& rotation, const core::vector3df& scale)
: IMeshSceneNode(parent, mgr, id, position, rotation, scale),
Mesh(0), Size(size)
{
#ifdef _DEBUG
setDebugName("CCubeSceneNode");
#endif
setSize();
}
CCubeSceneNode::~CCubeSceneNode()
{
if (Mesh)
Mesh->drop();
}
void CCubeSceneNode::setSize()
{
if (Mesh)
Mesh->drop();
Mesh = SceneManager->getGeometryCreator()->createCubeMesh(core::vector3df(Size));
}
//! renders the node.
void CCubeSceneNode::render()
{
video::IVideoDriver* driver = SceneManager->getVideoDriver();
driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
// for debug purposes only:
bool renderMeshes = true;
video::SMaterial mat = Mesh->getMeshBuffer(0)->getMaterial();
// overwrite half transparency
if (DebugDataVisible & scene::EDS_HALF_TRANSPARENCY)
mat.MaterialType = video::EMT_TRANSPARENT_ADD_COLOR;
else
driver->setMaterial(Mesh->getMeshBuffer(0)->getMaterial());
driver->setMaterial(mat);
driver->drawMeshBuffer(Mesh->getMeshBuffer(0));
// for debug purposes only:
if (DebugDataVisible)
{
video::SMaterial m;
m.Lighting = false;
m.AntiAliasing=0;
driver->setMaterial(m);
if (DebugDataVisible & scene::EDS_BBOX)
{
driver->draw3DBox(Mesh->getMeshBuffer(0)->getBoundingBox(), video::SColor(255,255,255,255));
}
if (DebugDataVisible & scene::EDS_BBOX_BUFFERS)
{
driver->draw3DBox(Mesh->getMeshBuffer(0)->getBoundingBox(),
video::SColor(255,190,128,128));
}
if (DebugDataVisible & scene::EDS_NORMALS)
{
// draw normals
core::vector3df normalizedNormal;
const f32 DebugNormalLength = SceneManager->getParameters()->getAttributeAsFloat(DEBUG_NORMAL_LENGTH);
const video::SColor DebugNormalColor = SceneManager->getParameters()->getAttributeAsColor(DEBUG_NORMAL_COLOR);
const scene::IMeshBuffer* mb = Mesh->getMeshBuffer(0);
const u32 vSize = video::getVertexPitchFromType(mb->getVertexType());
const video::S3DVertex* v = ( const video::S3DVertex*)mb->getVertices();
const bool normalize = mb->getMaterial().NormalizeNormals;
for (u32 i=0; i != mb->getVertexCount(); ++i)
{
normalizedNormal = v->Normal;
if (normalize)
normalizedNormal.normalize();
driver->draw3DLine(v->Pos, v->Pos + (normalizedNormal * DebugNormalLength), DebugNormalColor);
v = (const video::S3DVertex*) ( (u8*) v+vSize );
}
driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
}
// show mesh
if (DebugDataVisible & scene::EDS_MESH_WIRE_OVERLAY)
{
m.Wireframe = true;
driver->setMaterial(m);
driver->drawMeshBuffer( Mesh->getMeshBuffer(0) );
}
}
}
//! returns the axis aligned bounding box of this node
const core::aabbox3d<f32>& CCubeSceneNode::getBoundingBox() const
{
return Mesh->getMeshBuffer(0)->getBoundingBox();
}
void CCubeSceneNode::OnRegisterSceneNode()
{
if (IsVisible)
SceneManager->registerNodeForRendering(this);
ISceneNode::OnRegisterSceneNode();
}
//! returns the material based on the zero based index i.
video::SMaterial& CCubeSceneNode::getMaterial(u32 i)
{
return Mesh->getMeshBuffer(0)->getMaterial();
}
//! returns amount of materials used by this scene node.
u32 CCubeSceneNode::getMaterialCount() const
{
return 1;
}
//! Writes attributes of the scene node.
void CCubeSceneNode::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const
{
ISceneNode::serializeAttributes(out, options);
out->addFloat("Size", Size);
}
//! Reads attributes of the scene node.
void CCubeSceneNode::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
f32 newSize = in->getAttributeAsFloat("Size");
newSize = core::max_(newSize, 0.0001f);
if (newSize != Size)
{
Size = newSize;
setSize();
}
ISceneNode::deserializeAttributes(in, options);
}
//! Creates a clone of this scene node and its children.
ISceneNode* CCubeSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager)
{
if (!newParent)
newParent = Parent;
if (!newManager)
newManager = SceneManager;
- CCubeSceneNode* nb = new CCubeSceneNode(Size, newParent,
+ CCubeSceneNode* nb = new CCubeSceneNode(Size, newParent,
newManager, ID, RelativeTranslation);
nb->cloneMembers(this, newManager);
nb->getMaterial(0) = getMaterial(0);
- nb->drop();
+ if ( newParent )
+ nb->drop();
return nb;
}
} // end namespace scene
} // end namespace irr
diff --git a/source/Irrlicht/CEmptySceneNode.cpp b/source/Irrlicht/CEmptySceneNode.cpp
index 40f44dc..eb583e3 100644
--- a/source/Irrlicht/CEmptySceneNode.cpp
+++ b/source/Irrlicht/CEmptySceneNode.cpp
@@ -1,69 +1,70 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CEmptySceneNode.h"
#include "ISceneManager.h"
namespace irr
{
namespace scene
{
//! constructor
CEmptySceneNode::CEmptySceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id)
: ISceneNode(parent, mgr, id)
{
#ifdef _DEBUG
setDebugName("CEmptySceneNode");
#endif
setAutomaticCulling(scene::EAC_OFF);
}
//! pre render event
void CEmptySceneNode::OnRegisterSceneNode()
{
if (IsVisible)
SceneManager->registerNodeForRendering(this);
ISceneNode::OnRegisterSceneNode();
}
//! render
void CEmptySceneNode::render()
{
// do nothing
}
//! returns the axis aligned bounding box of this node
const core::aabbox3d<f32>& CEmptySceneNode::getBoundingBox() const
{
return Box;
}
//! Creates a clone of this scene node and its children.
ISceneNode* CEmptySceneNode::clone(ISceneNode* newParent, ISceneManager* newManager)
{
if (!newParent)
newParent = Parent;
if (!newManager)
newManager = SceneManager;
- CEmptySceneNode* nb = new CEmptySceneNode(newParent,
+ CEmptySceneNode* nb = new CEmptySceneNode(newParent,
newManager, ID);
nb->cloneMembers(this, newManager);
nb->Box = Box;
- nb->drop();
+ if ( newParent )
+ nb->drop();
return nb;
}
} // end namespace scene
} // end namespace irr
diff --git a/source/Irrlicht/CLightSceneNode.cpp b/source/Irrlicht/CLightSceneNode.cpp
index abb5650..a1ecc1c 100644
--- a/source/Irrlicht/CLightSceneNode.cpp
+++ b/source/Irrlicht/CLightSceneNode.cpp
@@ -1,271 +1,272 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CLightSceneNode.h"
#include "IVideoDriver.h"
#include "ISceneManager.h"
#include "ICameraSceneNode.h"
#include "os.h"
namespace irr
{
namespace scene
{
//! constructor
CLightSceneNode::CLightSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id,
const core::vector3df& position, video::SColorf color, f32 radius)
: ILightSceneNode(parent, mgr, id, position), DriverLightIndex(-1), LightIsOn(true)
{
#ifdef _DEBUG
setDebugName("CLightSceneNode");
#endif
LightData.DiffuseColor = color;
// set some useful specular color
LightData.SpecularColor = color.getInterpolated(video::SColor(255,255,255,255),0.7f);
setRadius(radius);
}
//! pre render event
void CLightSceneNode::OnRegisterSceneNode()
{
doLightRecalc();
if (IsVisible)
SceneManager->registerNodeForRendering(this, ESNRP_LIGHT);
ISceneNode::OnRegisterSceneNode();
}
//! render
void CLightSceneNode::render()
{
video::IVideoDriver* driver = SceneManager->getVideoDriver();
if (!driver)
return;
if ( DebugDataVisible & scene::EDS_BBOX )
{
driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
video::SMaterial m;
m.Lighting = false;
driver->setMaterial(m);
switch ( LightData.Type )
{
case video::ELT_POINT:
case video::ELT_SPOT:
driver->draw3DBox(BBox, LightData.DiffuseColor.toSColor());
break;
case video::ELT_DIRECTIONAL:
driver->draw3DLine(core::vector3df(0.f, 0.f, 0.f),
LightData.Direction * LightData.Radius,
LightData.DiffuseColor.toSColor());
break;
}
}
DriverLightIndex = driver->addDynamicLight(LightData);
setVisible(LightIsOn);
}
//! sets the light data
void CLightSceneNode::setLightData(const video::SLight& light)
{
LightData = light;
}
//! \return Returns the light data.
const video::SLight& CLightSceneNode::getLightData() const
{
return LightData;
}
//! \return Returns the light data.
video::SLight& CLightSceneNode::getLightData()
{
return LightData;
}
void CLightSceneNode::setVisible(bool isVisible)
{
ISceneNode::setVisible(isVisible);
if(DriverLightIndex < 0)
return;
video::IVideoDriver* driver = SceneManager->getVideoDriver();
if (!driver)
return;
LightIsOn = isVisible;
driver->turnLightOn((u32)DriverLightIndex, LightIsOn);
}
//! returns the axis aligned bounding box of this node
const core::aabbox3d<f32>& CLightSceneNode::getBoundingBox() const
{
return BBox;
}
//! Sets the light's radius of influence.
/** Outside this radius the light won't lighten geometry and cast no
shadows. Setting the radius will also influence the attenuation, setting
it to (0,1/radius,0). If you want to override this behavior, set the
attenuation after the radius.
\param radius The new radius. */
void CLightSceneNode::setRadius(f32 radius)
{
LightData.Radius=radius;
LightData.Attenuation.set(0.f, 1.f/radius, 0.f);
doLightRecalc();
}
//! Gets the light's radius of influence.
/** \return The current radius. */
f32 CLightSceneNode::getRadius() const
{
return LightData.Radius;
}
//! Sets the light type.
/** \param type The new type. */
void CLightSceneNode::setLightType(video::E_LIGHT_TYPE type)
{
LightData.Type=type;
}
//! Gets the light type.
/** \return The current light type. */
video::E_LIGHT_TYPE CLightSceneNode::getLightType() const
{
return LightData.Type;
}
//! Sets whether this light casts shadows.
/** Enabling this flag won't automatically cast shadows, the meshes
will still need shadow scene nodes attached. But one can enable or
disable distinct lights for shadow casting for performance reasons.
\param shadow True if this light shall cast shadows. */
void CLightSceneNode::enableCastShadow(bool shadow)
{
LightData.CastShadows=shadow;
}
//! Check whether this light casts shadows.
/** \return True if light would cast shadows, else false. */
bool CLightSceneNode::getCastShadow() const
{
return LightData.CastShadows;
}
void CLightSceneNode::doLightRecalc()
{
if ((LightData.Type == video::ELT_SPOT) || (LightData.Type == video::ELT_DIRECTIONAL))
{
LightData.Direction = core::vector3df(.0f,.0f,1.0f);
getAbsoluteTransformation().rotateVect(LightData.Direction);
LightData.Direction.normalize();
}
if ((LightData.Type == video::ELT_SPOT) || (LightData.Type == video::ELT_POINT))
{
const f32 r = LightData.Radius * LightData.Radius * 0.5f;
BBox.MaxEdge.set( r, r, r );
BBox.MinEdge.set( -r, -r, -r );
setAutomaticCulling( scene::EAC_BOX );
LightData.Position = getAbsolutePosition();
}
if (LightData.Type == video::ELT_DIRECTIONAL)
{
BBox.reset( 0, 0, 0 );
setAutomaticCulling( scene::EAC_OFF );
}
}
//! Writes attributes of the scene node.
void CLightSceneNode::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const
{
ILightSceneNode::serializeAttributes(out, options);
out->addColorf ("AmbientColor", LightData.AmbientColor);
out->addColorf ("DiffuseColor", LightData.DiffuseColor);
out->addColorf ("SpecularColor", LightData.SpecularColor);
out->addVector3d("Attenuation", LightData.Attenuation);
out->addFloat ("Radius", LightData.Radius);
out->addFloat ("OuterCone", LightData.OuterCone);
out->addFloat ("InnerCone", LightData.InnerCone);
out->addFloat ("Falloff", LightData.Falloff);
out->addBool ("CastShadows", LightData.CastShadows);
out->addEnum ("LightType", LightData.Type, video::LightTypeNames);
}
//! Reads attributes of the scene node.
void CLightSceneNode::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
LightData.AmbientColor = in->getAttributeAsColorf("AmbientColor");
LightData.DiffuseColor = in->getAttributeAsColorf("DiffuseColor");
LightData.SpecularColor = in->getAttributeAsColorf("SpecularColor");
//TODO: clearify Radius and Linear Attenuation
#if 0
setRadius ( in->getAttributeAsFloat("Radius") );
#else
LightData.Radius = in->getAttributeAsFloat("Radius");
#endif
if (in->existsAttribute("Attenuation")) // might not exist in older files
LightData.Attenuation = in->getAttributeAsVector3d("Attenuation");
if (in->existsAttribute("OuterCone")) // might not exist in older files
LightData.OuterCone = in->getAttributeAsFloat("OuterCone");
if (in->existsAttribute("InnerCone")) // might not exist in older files
LightData.InnerCone = in->getAttributeAsFloat("InnerCone");
if (in->existsAttribute("Falloff")) // might not exist in older files
LightData.Falloff = in->getAttributeAsFloat("Falloff");
LightData.CastShadows = in->getAttributeAsBool("CastShadows");
LightData.Type = (video::E_LIGHT_TYPE)in->getAttributeAsEnumeration("LightType", video::LightTypeNames);
doLightRecalc ();
ILightSceneNode::deserializeAttributes(in, options);
}
//! Creates a clone of this scene node and its children.
ISceneNode* CLightSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager)
{
if (!newParent)
newParent = Parent;
if (!newManager)
newManager = SceneManager;
CLightSceneNode* nb = new CLightSceneNode(newParent,
newManager, ID, RelativeTranslation, LightData.DiffuseColor, LightData.Radius);
nb->cloneMembers(this, newManager);
nb->LightData = LightData;
nb->BBox = BBox;
- nb->drop();
+ if ( newParent )
+ nb->drop();
return nb;
}
} // end namespace scene
} // end namespace irr
diff --git a/source/Irrlicht/CMeshSceneNode.cpp b/source/Irrlicht/CMeshSceneNode.cpp
index 559e1c9..207666a 100644
--- a/source/Irrlicht/CMeshSceneNode.cpp
+++ b/source/Irrlicht/CMeshSceneNode.cpp
@@ -1,383 +1,384 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CMeshSceneNode.h"
#include "IVideoDriver.h"
#include "ISceneManager.h"
#include "S3DVertex.h"
#include "ICameraSceneNode.h"
#include "IMeshCache.h"
#include "IAnimatedMesh.h"
#include "IMaterialRenderer.h"
namespace irr
{
namespace scene
{
//! constructor
CMeshSceneNode::CMeshSceneNode(IMesh* mesh, ISceneNode* parent, ISceneManager* mgr, s32 id,
const core::vector3df& position, const core::vector3df& rotation,
const core::vector3df& scale)
: IMeshSceneNode(parent, mgr, id, position, rotation, scale), Mesh(0), PassCount(0),
ReadOnlyMaterials(false)
{
#ifdef _DEBUG
setDebugName("CMeshSceneNode");
#endif
setMesh(mesh);
}
//! destructor
CMeshSceneNode::~CMeshSceneNode()
{
if (Mesh)
Mesh->drop();
}
//! frame
void CMeshSceneNode::OnRegisterSceneNode()
{
if (IsVisible)
{
// because this node supports rendering of mixed mode meshes consisting of
// transparent and solid material at the same time, we need to go through all
// materials, check of what type they are and register this node for the right
// render pass according to that.
video::IVideoDriver* driver = SceneManager->getVideoDriver();
PassCount = 0;
int transparentCount = 0;
int solidCount = 0;
// count transparent and solid materials in this scene node
if (ReadOnlyMaterials && Mesh)
{
// count mesh materials
for (u32 i=0; i<Mesh->getMeshBufferCount(); ++i)
{
scene::IMeshBuffer* mb = Mesh->getMeshBuffer(i);
video::IMaterialRenderer* rnd = mb ? driver->getMaterialRenderer(mb->getMaterial().MaterialType) : 0;
if (rnd && rnd->isTransparent())
++transparentCount;
else
++solidCount;
if (solidCount && transparentCount)
break;
}
}
else
{
// count copied materials
for (u32 i=0; i<Materials.size(); ++i)
{
video::IMaterialRenderer* rnd =
driver->getMaterialRenderer(Materials[i].MaterialType);
if (rnd && rnd->isTransparent())
++transparentCount;
else
++solidCount;
if (solidCount && transparentCount)
break;
}
}
// register according to material types counted
if (solidCount)
SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
if (transparentCount)
SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
ISceneNode::OnRegisterSceneNode();
}
}
//! renders the node.
void CMeshSceneNode::render()
{
video::IVideoDriver* driver = SceneManager->getVideoDriver();
if (!Mesh || !driver)
return;
bool isTransparentPass =
SceneManager->getSceneNodeRenderPass() == scene::ESNRP_TRANSPARENT;
++PassCount;
driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
Box = Mesh->getBoundingBox();
// for debug purposes only:
bool renderMeshes = true;
video::SMaterial mat;
if (DebugDataVisible && PassCount==1)
{
// overwrite half transparency
if (DebugDataVisible & scene::EDS_HALF_TRANSPARENCY)
{
for (u32 g=0; g<Mesh->getMeshBufferCount(); ++g)
{
mat = Materials[g];
mat.MaterialType = video::EMT_TRANSPARENT_ADD_COLOR;
driver->setMaterial(mat);
driver->drawMeshBuffer(Mesh->getMeshBuffer(g));
}
renderMeshes = false;
}
}
// render original meshes
if (renderMeshes)
{
for (u32 i=0; i<Mesh->getMeshBufferCount(); ++i)
{
scene::IMeshBuffer* mb = Mesh->getMeshBuffer(i);
if (mb)
{
const video::SMaterial& material = ReadOnlyMaterials ? mb->getMaterial() : Materials[i];
video::IMaterialRenderer* rnd = driver->getMaterialRenderer(material.MaterialType);
bool transparent = (rnd && rnd->isTransparent());
// only render transparent buffer if this is the transparent render pass
// and solid only in solid pass
if (transparent == isTransparentPass)
{
driver->setMaterial(material);
driver->drawMeshBuffer(mb);
}
}
}
}
driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
// for debug purposes only:
if (DebugDataVisible && PassCount==1)
{
video::SMaterial m;
m.Lighting = false;
m.AntiAliasing=0;
driver->setMaterial(m);
if (DebugDataVisible & scene::EDS_BBOX)
{
driver->draw3DBox(Box, video::SColor(255,255,255,255));
}
if (DebugDataVisible & scene::EDS_BBOX_BUFFERS)
{
for (u32 g=0; g<Mesh->getMeshBufferCount(); ++g)
{
driver->draw3DBox(
Mesh->getMeshBuffer(g)->getBoundingBox(),
video::SColor(255,190,128,128));
}
}
if (DebugDataVisible & scene::EDS_NORMALS)
{
// draw normals
core::vector3df normalizedNormal;
const f32 DebugNormalLength = SceneManager->getParameters()->getAttributeAsFloat(DEBUG_NORMAL_LENGTH);
const video::SColor DebugNormalColor = SceneManager->getParameters()->getAttributeAsColor(DEBUG_NORMAL_COLOR);
for (u32 g=0; g<Mesh->getMeshBufferCount(); ++g)
{
const scene::IMeshBuffer* mb = Mesh->getMeshBuffer(g);
const u32 vSize = video::getVertexPitchFromType(mb->getVertexType());
const video::S3DVertex* v = ( const video::S3DVertex*)mb->getVertices();
const bool normalize = mb->getMaterial().NormalizeNormals;
for (u32 i=0; i != mb->getVertexCount(); ++i)
{
normalizedNormal = v->Normal;
if (normalize)
normalizedNormal.normalize();
driver->draw3DLine(v->Pos, v->Pos + (normalizedNormal * DebugNormalLength), DebugNormalColor);
v = (const video::S3DVertex*) ( (u8*) v+vSize );
}
}
driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
}
// show mesh
if (DebugDataVisible & scene::EDS_MESH_WIRE_OVERLAY)
{
m.Wireframe = true;
driver->setMaterial(m);
for (u32 g=0; g<Mesh->getMeshBufferCount(); ++g)
{
driver->drawMeshBuffer( Mesh->getMeshBuffer(g) );
}
}
}
}
//! returns the axis aligned bounding box of this node
const core::aabbox3d<f32>& CMeshSceneNode::getBoundingBox() const
{
return Mesh ? Mesh->getBoundingBox() : Box;
}
//! returns the material based on the zero based index i. To get the amount
//! of materials used by this scene node, use getMaterialCount().
//! This function is needed for inserting the node into the scene hierarchy on a
//! optimal position for minimizing renderstate changes, but can also be used
//! to directly modify the material of a scene node.
video::SMaterial& CMeshSceneNode::getMaterial(u32 i)
{
if (Mesh && ReadOnlyMaterials && i<Mesh->getMeshBufferCount())
{
tmpReadOnlyMaterial = Mesh->getMeshBuffer(i)->getMaterial();
return tmpReadOnlyMaterial;
}
if (i >= Materials.size())
return ISceneNode::getMaterial(i);
return Materials[i];
}
//! returns amount of materials used by this scene node.
u32 CMeshSceneNode::getMaterialCount() const
{
if (Mesh && ReadOnlyMaterials)
return Mesh->getMeshBufferCount();
return Materials.size();
}
//! Sets a new mesh
void CMeshSceneNode::setMesh(IMesh* mesh)
{
if (!mesh)
return; // won't set null mesh
mesh->grab();
if (Mesh)
Mesh->drop();
Mesh = mesh;
copyMaterials();
}
void CMeshSceneNode::copyMaterials()
{
Materials.clear();
if (Mesh)
{
video::SMaterial mat;
for (u32 i=0; i<Mesh->getMeshBufferCount(); ++i)
{
IMeshBuffer* mb = Mesh->getMeshBuffer(i);
if (mb)
mat = mb->getMaterial();
Materials.push_back(mat);
}
}
}
//! Writes attributes of the scene node.
void CMeshSceneNode::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const
{
IMeshSceneNode::serializeAttributes(out, options);
out->addString("Mesh", SceneManager->getMeshCache()->getMeshName(Mesh).getPath().c_str());
out->addBool("ReadOnlyMaterials", ReadOnlyMaterials);
}
//! Reads attributes of the scene node.
void CMeshSceneNode::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
io::path oldMeshStr = SceneManager->getMeshCache()->getMeshName(Mesh);
io::path newMeshStr = in->getAttributeAsString("Mesh");
ReadOnlyMaterials = in->getAttributeAsBool("ReadOnlyMaterials");
if (newMeshStr != "" && oldMeshStr != newMeshStr)
{
IMesh* newMesh = 0;
IAnimatedMesh* newAnimatedMesh = SceneManager->getMesh(newMeshStr.c_str());
if (newAnimatedMesh)
newMesh = newAnimatedMesh->getMesh(0);
if (newMesh)
setMesh(newMesh);
}
IMeshSceneNode::deserializeAttributes(in, options);
}
//! Sets if the scene node should not copy the materials of the mesh but use them in a read only style.
/* In this way it is possible to change the materials a mesh causing all mesh scene nodes
referencing this mesh to change too. */
void CMeshSceneNode::setReadOnlyMaterials(bool readonly)
{
ReadOnlyMaterials = readonly;
}
//! Returns if the scene node should not copy the materials of the mesh but use them in a read only style
bool CMeshSceneNode::isReadOnlyMaterials() const
{
return ReadOnlyMaterials;
}
//! Creates a clone of this scene node and its children.
ISceneNode* CMeshSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager)
{
if (!newParent) newParent = Parent;
if (!newManager) newManager = SceneManager;
CMeshSceneNode* nb = new CMeshSceneNode(Mesh, newParent,
newManager, ID, RelativeTranslation, RelativeRotation, RelativeScale);
nb->cloneMembers(this, newManager);
nb->ReadOnlyMaterials = ReadOnlyMaterials;
nb->Materials = Materials;
- nb->drop();
+ if ( newParent )
+ nb->drop();
return nb;
}
} // end namespace scene
} // end namespace irr
diff --git a/source/Irrlicht/CSkyBoxSceneNode.cpp b/source/Irrlicht/CSkyBoxSceneNode.cpp
index 038a9f3..6be4027 100644
--- a/source/Irrlicht/CSkyBoxSceneNode.cpp
+++ b/source/Irrlicht/CSkyBoxSceneNode.cpp
@@ -1,262 +1,263 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CSkyBoxSceneNode.h"
#include "IVideoDriver.h"
#include "ISceneManager.h"
#include "ICameraSceneNode.h"
#include "S3DVertex.h"
#include "os.h"
namespace irr
{
namespace scene
{
//! constructor
CSkyBoxSceneNode::CSkyBoxSceneNode(video::ITexture* top, video::ITexture* bottom, video::ITexture* left,
video::ITexture* right, video::ITexture* front, video::ITexture* back, ISceneNode* parent, ISceneManager* mgr, s32 id)
: ISceneNode(parent, mgr, id)
{
#ifdef _DEBUG
setDebugName("CSkyBoxSceneNode");
#endif
setAutomaticCulling(scene::EAC_OFF);
Box.MaxEdge.set(0,0,0);
Box.MinEdge.set(0,0,0);
// create indices
Indices[0] = 0;
Indices[1] = 1;
Indices[2] = 2;
Indices[3] = 3;
// create material
video::SMaterial mat;
mat.Lighting = false;
mat.ZBuffer = video::ECFN_NEVER;
mat.ZWriteEnable = false;
mat.AntiAliasing=0;
mat.TextureLayer[0].TextureWrapU = video::ETC_CLAMP_TO_EDGE;
mat.TextureLayer[0].TextureWrapV = video::ETC_CLAMP_TO_EDGE;
/* Hey, I am no artist, but look at that
cool ASCII art I made! ;)
-111 111
/6--------/5 y
/ | / | ^ z
/ | 11-1 | | /
-11-1 3---------2 | |/
| 7- - -| -4 1-11 *---->x
| -1-11 | / 3-------|2
|/ | / | //|
0---------1/ | // |
-1-1-1 1-1-1 |// |
0--------1
*/
video::ITexture* tex = front;
if (!tex) tex = left;
if (!tex) tex = back;
if (!tex) tex = right;
if (!tex) tex = top;
if (!tex) tex = bottom;
const f32 onepixel = tex?(1.0f / (tex->getSize().Width * 1.5f)) : 0.0f;
const f32 t = 1.0f - onepixel;
const f32 o = 0.0f + onepixel;
// create front side
Material[0] = mat;
Material[0].setTexture(0, front);
Vertices[0] = video::S3DVertex(-1,-1,-1, 0,0,1, video::SColor(255,255,255,255), t, t);
Vertices[1] = video::S3DVertex( 1,-1,-1, 0,0,1, video::SColor(255,255,255,255), o, t);
Vertices[2] = video::S3DVertex( 1, 1,-1, 0,0,1, video::SColor(255,255,255,255), o, o);
Vertices[3] = video::S3DVertex(-1, 1,-1, 0,0,1, video::SColor(255,255,255,255), t, o);
// create left side
Material[1] = mat;
Material[1].setTexture(0, left);
Vertices[4] = video::S3DVertex( 1,-1,-1, -1,0,0, video::SColor(255,255,255,255), t, t);
Vertices[5] = video::S3DVertex( 1,-1, 1, -1,0,0, video::SColor(255,255,255,255), o, t);
Vertices[6] = video::S3DVertex( 1, 1, 1, -1,0,0, video::SColor(255,255,255,255), o, o);
Vertices[7] = video::S3DVertex( 1, 1,-1, -1,0,0, video::SColor(255,255,255,255), t, o);
// create back side
Material[2] = mat;
Material[2].setTexture(0, back);
Vertices[8] = video::S3DVertex( 1,-1, 1, 0,0,-1, video::SColor(255,255,255,255), t, t);
Vertices[9] = video::S3DVertex(-1,-1, 1, 0,0,-1, video::SColor(255,255,255,255), o, t);
Vertices[10] = video::S3DVertex(-1, 1, 1, 0,0,-1, video::SColor(255,255,255,255), o, o);
Vertices[11] = video::S3DVertex( 1, 1, 1, 0,0,-1, video::SColor(255,255,255,255), t, o);
// create right side
Material[3] = mat;
Material[3].setTexture(0, right);
Vertices[12] = video::S3DVertex(-1,-1, 1, 1,0,0, video::SColor(255,255,255,255), t, t);
Vertices[13] = video::S3DVertex(-1,-1,-1, 1,0,0, video::SColor(255,255,255,255), o, t);
Vertices[14] = video::S3DVertex(-1, 1,-1, 1,0,0, video::SColor(255,255,255,255), o, o);
Vertices[15] = video::S3DVertex(-1, 1, 1, 1,0,0, video::SColor(255,255,255,255), t, o);
// create top side
Material[4] = mat;
Material[4].setTexture(0, top);
Vertices[16] = video::S3DVertex( 1, 1,-1, 0,-1,0, video::SColor(255,255,255,255), t, t);
Vertices[17] = video::S3DVertex( 1, 1, 1, 0,-1,0, video::SColor(255,255,255,255), o, t);
Vertices[18] = video::S3DVertex(-1, 1, 1, 0,-1,0, video::SColor(255,255,255,255), o, o);
Vertices[19] = video::S3DVertex(-1, 1,-1, 0,-1,0, video::SColor(255,255,255,255), t, o);
// create bottom side
Material[5] = mat;
Material[5].setTexture(0, bottom);
Vertices[20] = video::S3DVertex( 1,-1, 1, 0,1,0, video::SColor(255,255,255,255), o, o);
Vertices[21] = video::S3DVertex( 1,-1,-1, 0,1,0, video::SColor(255,255,255,255), t, o);
Vertices[22] = video::S3DVertex(-1,-1,-1, 0,1,0, video::SColor(255,255,255,255), t, t);
Vertices[23] = video::S3DVertex(-1,-1, 1, 0,1,0, video::SColor(255,255,255,255), o, t);
}
//! renders the node.
void CSkyBoxSceneNode::render()
{
video::IVideoDriver* driver = SceneManager->getVideoDriver();
scene::ICameraSceneNode* camera = SceneManager->getActiveCamera();
if (!camera || !driver)
return;
if ( !camera->isOrthogonal() )
{
// draw perspective skybox
core::matrix4 translate(AbsoluteTransformation);
translate.setTranslation(camera->getAbsolutePosition());
// Draw the sky box between the near and far clip plane
const f32 viewDistance = (camera->getNearValue() + camera->getFarValue()) * 0.5f;
core::matrix4 scale;
scale.setScale(core::vector3df(viewDistance, viewDistance, viewDistance));
driver->setTransform(video::ETS_WORLD, translate * scale);
for (s32 i=0; i<6; ++i)
{
driver->setMaterial(Material[i]);
driver->drawIndexedTriangleFan(&Vertices[i*4], 4, Indices, 2);
}
}
else
{
// draw orthogonal skybox,
// simply choose one texture and draw it as 2d picture.
// there could be better ways to do this, but currently I think this is ok.
core::vector3df lookVect = camera->getTarget() - camera->getAbsolutePosition();
lookVect.normalize();
core::vector3df absVect( core::abs_(lookVect.X),
core::abs_(lookVect.Y),
core::abs_(lookVect.Z));
int idx = 0;
if ( absVect.X >= absVect.Y && absVect.X >= absVect.Z )
{
// x direction
idx = lookVect.X > 0 ? 0 : 2;
}
else
if ( absVect.Y >= absVect.X && absVect.Y >= absVect.Z )
{
// y direction
idx = lookVect.Y > 0 ? 4 : 5;
}
else
if ( absVect.Z >= absVect.X && absVect.Z >= absVect.Y )
{
// z direction
idx = lookVect.Z > 0 ? 1 : 3;
}
video::ITexture* tex = Material[idx].getTexture(0);
if ( tex )
{
core::rect<s32> rctDest(core::position2d<s32>(-1,0),
core::dimension2di(driver->getCurrentRenderTargetSize()));
core::rect<s32> rctSrc(core::position2d<s32>(0,0),
core::dimension2di(tex->getSize()));
driver->draw2DImage(tex, rctDest, rctSrc);
}
}
}
//! returns the axis aligned bounding box of this node
const core::aabbox3d<f32>& CSkyBoxSceneNode::getBoundingBox() const
{
return Box;
}
void CSkyBoxSceneNode::OnRegisterSceneNode()
{
if (IsVisible)
SceneManager->registerNodeForRendering(this, ESNRP_SKY_BOX);
ISceneNode::OnRegisterSceneNode();
}
//! returns the material based on the zero based index i. To get the amount
//! of materials used by this scene node, use getMaterialCount().
//! This function is needed for inserting the node into the scene hirachy on a
//! optimal position for minimizing renderstate changes, but can also be used
//! to directly modify the material of a scene node.
video::SMaterial& CSkyBoxSceneNode::getMaterial(u32 i)
{
return Material[i];
}
//! returns amount of materials used by this scene node.
u32 CSkyBoxSceneNode::getMaterialCount() const
{
return 6;
}
//! Creates a clone of this scene node and its children.
ISceneNode* CSkyBoxSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager)
{
if (!newParent) newParent = Parent;
if (!newManager) newManager = SceneManager;
CSkyBoxSceneNode* nb = new CSkyBoxSceneNode(0,0,0,0,0,0, newParent,
newManager, ID);
nb->cloneMembers(this, newManager);
for (u32 i=0; i<6; ++i)
nb->Material[i] = Material[i];
- nb->drop();
+ if ( newParent )
+ nb->drop();
return nb;
}
} // end namespace scene
} // end namespace irr
diff --git a/source/Irrlicht/CSkyDomeSceneNode.cpp b/source/Irrlicht/CSkyDomeSceneNode.cpp
index 82b1f83..d5590b4 100644
--- a/source/Irrlicht/CSkyDomeSceneNode.cpp
+++ b/source/Irrlicht/CSkyDomeSceneNode.cpp
@@ -1,291 +1,292 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
// Code for this scene node has been contributed by Anders la Cour-Harbo (alc)
#include "CSkyDomeSceneNode.h"
#include "IVideoDriver.h"
#include "ISceneManager.h"
#include "ICameraSceneNode.h"
#include "IAnimatedMesh.h"
#include "os.h"
namespace irr
{
namespace scene
{
/* horiRes and vertRes:
Controls the number of faces along the horizontal axis (30 is a good value)
and the number of faces along the vertical axis (8 is a good value).
texturePercentage:
Only the top texturePercentage of the image is used, e.g. 0.8 uses the top 80% of the image,
1.0 uses the entire image. This is useful as some landscape images have a small banner
at the bottom that you don't want.
spherePercentage:
This controls how far around the sphere the sky dome goes. For value 1.0 you get exactly the upper
hemisphere, for 1.1 you get slightly more, and for 2.0 you get a full sphere. It is sometimes useful
to use a value slightly bigger than 1 to avoid a gap between some ground place and the sky. This
parameters stretches the image to fit the chosen "sphere-size". */
CSkyDomeSceneNode::CSkyDomeSceneNode(video::ITexture* sky, u32 horiRes, u32 vertRes,
f32 texturePercentage, f32 spherePercentage, f32 radius,
ISceneNode* parent, ISceneManager* mgr, s32 id)
- : ISceneNode(parent, mgr, id), Buffer(0),
+ : ISceneNode(parent, mgr, id), Buffer(0),
HorizontalResolution(horiRes), VerticalResolution(vertRes),
TexturePercentage(texturePercentage),
SpherePercentage(spherePercentage), Radius(radius)
{
#ifdef _DEBUG
setDebugName("CSkyDomeSceneNode");
#endif
setAutomaticCulling(scene::EAC_OFF);
Buffer = new SMeshBuffer();
Buffer->Material.Lighting = false;
Buffer->Material.ZBuffer = video::ECFN_NEVER;
Buffer->Material.ZWriteEnable = false;
Buffer->Material.AntiAliasing = video::EAAM_OFF;
Buffer->Material.setTexture(0, sky);
Buffer->BoundingBox.MaxEdge.set(0,0,0);
Buffer->BoundingBox.MinEdge.set(0,0,0);
Buffer->Vertices.clear();
Buffer->Indices.clear();
// regenerate the mesh
generateMesh();
}
CSkyDomeSceneNode::~CSkyDomeSceneNode()
{
if (Buffer)
Buffer->drop();
}
void CSkyDomeSceneNode::generateMesh()
{
f32 azimuth;
u32 k;
const f32 azimuth_step = (core::PI * 2.f) / HorizontalResolution;
if (SpherePercentage < 0.f)
SpherePercentage = -SpherePercentage;
if (SpherePercentage > 2.f)
SpherePercentage = 2.f;
const f32 elevation_step = SpherePercentage * core::HALF_PI / (f32)VerticalResolution;
Buffer->Vertices.reallocate( (HorizontalResolution + 1) * (VerticalResolution + 1) );
Buffer->Indices.reallocate(3 * (2*VerticalResolution - 1) * HorizontalResolution);
video::S3DVertex vtx;
vtx.Color.set(255,255,255,255);
vtx.Normal.set(0.0f,-1.f,0.0f);
const f32 tcV = TexturePercentage / VerticalResolution;
for (k = 0, azimuth = 0; k <= HorizontalResolution; ++k)
{
f32 elevation = core::HALF_PI;
const f32 tcU = (f32)k / (f32)HorizontalResolution;
const f32 sinA = sinf(azimuth);
const f32 cosA = cosf(azimuth);
for (u32 j = 0; j <= VerticalResolution; ++j)
{
const f32 cosEr = Radius * cosf(elevation);
vtx.Pos.set(cosEr*sinA, Radius*sinf(elevation), cosEr*cosA);
vtx.TCoords.set(tcU, j*tcV);
vtx.Normal = -vtx.Pos;
vtx.Normal.normalize();
Buffer->Vertices.push_back(vtx);
elevation -= elevation_step;
}
azimuth += azimuth_step;
}
for (k = 0; k < HorizontalResolution; ++k)
{
Buffer->Indices.push_back(VerticalResolution + 2 + (VerticalResolution + 1)*k);
Buffer->Indices.push_back(1 + (VerticalResolution + 1)*k);
Buffer->Indices.push_back(0 + (VerticalResolution + 1)*k);
for (u32 j = 1; j < VerticalResolution; ++j)
{
Buffer->Indices.push_back(VerticalResolution + 2 + (VerticalResolution + 1)*k + j);
Buffer->Indices.push_back(1 + (VerticalResolution + 1)*k + j);
Buffer->Indices.push_back(0 + (VerticalResolution + 1)*k + j);
Buffer->Indices.push_back(VerticalResolution + 1 + (VerticalResolution + 1)*k + j);
Buffer->Indices.push_back(VerticalResolution + 2 + (VerticalResolution + 1)*k + j);
Buffer->Indices.push_back(0 + (VerticalResolution + 1)*k + j);
}
}
Buffer->setHardwareMappingHint(scene::EHM_STATIC);
}
//! renders the node.
void CSkyDomeSceneNode::render()
{
video::IVideoDriver* driver = SceneManager->getVideoDriver();
scene::ICameraSceneNode* camera = SceneManager->getActiveCamera();
if (!camera || !driver)
return;
if ( !camera->isOrthogonal() )
{
core::matrix4 mat(AbsoluteTransformation);
mat.setTranslation(camera->getAbsolutePosition());
driver->setTransform(video::ETS_WORLD, mat);
driver->setMaterial(Buffer->Material);
driver->drawMeshBuffer(Buffer);
}
// for debug purposes only:
if ( DebugDataVisible )
{
video::SMaterial m;
m.Lighting = false;
driver->setMaterial(m);
if ( DebugDataVisible & scene::EDS_NORMALS )
{
IAnimatedMesh * arrow = SceneManager->addArrowMesh (
"__debugnormal2", 0xFFECEC00,
0xFF999900, 4, 8, 1.f * 40.f, 0.6f * 40.f, 0.05f * 40.f, 0.3f * 40.f);
if ( 0 == arrow )
{
arrow = SceneManager->getMesh ( "__debugnormal2" );
}
IMesh *mesh = arrow->getMesh(0);
// find a good scaling factor
core::matrix4 m2;
// draw normals
const scene::IMeshBuffer* mb = Buffer;
const u32 vSize = video::getVertexPitchFromType(mb->getVertexType());
const video::S3DVertex* v = ( const video::S3DVertex*)mb->getVertices();
for ( u32 i=0; i != mb->getVertexCount(); ++i )
{
// align to v->Normal
core::quaternion quatRot(v->Normal.X, 0.f, -v->Normal.X, 1+v->Normal.Y);
quatRot.normalize();
quatRot.getMatrix(m2, v->Pos);
m2 = AbsoluteTransformation * m2;
driver->setTransform(video::ETS_WORLD, m2);
for (u32 a = 0; a != mesh->getMeshBufferCount(); ++a)
driver->drawMeshBuffer(mesh->getMeshBuffer(a));
v = (const video::S3DVertex*) ( (u8*) v + vSize );
}
driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
}
// show mesh
if ( DebugDataVisible & scene::EDS_MESH_WIRE_OVERLAY )
{
m.Wireframe = true;
driver->setMaterial(m);
driver->drawMeshBuffer(Buffer);
}
}
}
//! returns the axis aligned bounding box of this node
const core::aabbox3d<f32>& CSkyDomeSceneNode::getBoundingBox() const
{
return Buffer->BoundingBox;
}
void CSkyDomeSceneNode::OnRegisterSceneNode()
{
if (IsVisible)
{
SceneManager->registerNodeForRendering(this, ESNRP_SKY_BOX );
}
ISceneNode::OnRegisterSceneNode();
}
//! returns the material based on the zero based index i. To get the amount
//! of materials used by this scene node, use getMaterialCount().
//! This function is needed for inserting the node into the scene hirachy on a
//! optimal position for minimizing renderstate changes, but can also be used
//! to directly modify the material of a scene node.
video::SMaterial& CSkyDomeSceneNode::getMaterial(u32 i)
{
return Buffer->Material;
}
//! returns amount of materials used by this scene node.
u32 CSkyDomeSceneNode::getMaterialCount() const
{
return 1;
}
//! Writes attributes of the scene node.
void CSkyDomeSceneNode::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const
{
ISceneNode::serializeAttributes(out, options);
out->addInt ("HorizontalResolution", HorizontalResolution);
out->addInt ("VerticalResolution", VerticalResolution);
out->addFloat("TexturePercentage", TexturePercentage);
out->addFloat("SpherePercentage", SpherePercentage);
out->addFloat("Radius", Radius);
}
//! Reads attributes of the scene node.
void CSkyDomeSceneNode::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
HorizontalResolution = in->getAttributeAsInt ("HorizontalResolution");
VerticalResolution = in->getAttributeAsInt ("VerticalResolution");
TexturePercentage = in->getAttributeAsFloat("TexturePercentage");
SpherePercentage = in->getAttributeAsFloat("SpherePercentage");
Radius = in->getAttributeAsFloat("Radius");
ISceneNode::deserializeAttributes(in, options);
-
+
// regenerate the mesh
generateMesh();
}
//! Creates a clone of this scene node and its children.
ISceneNode* CSkyDomeSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager)
{
- if (!newParent)
+ if (!newParent)
newParent = Parent;
- if (!newManager)
+ if (!newManager)
newManager = SceneManager;
- CSkyDomeSceneNode* nb = new CSkyDomeSceneNode(Buffer->Material.TextureLayer[0].Texture, HorizontalResolution, VerticalResolution, TexturePercentage,
+ CSkyDomeSceneNode* nb = new CSkyDomeSceneNode(Buffer->Material.TextureLayer[0].Texture, HorizontalResolution, VerticalResolution, TexturePercentage,
SpherePercentage, Radius, newParent, newManager, ID);
nb->cloneMembers(this, newManager);
-
- nb->drop();
+
+ if ( newParent )
+ nb->drop();
return nb;
}
} // namespace scene
} // namespace irr
diff --git a/source/Irrlicht/CSphereSceneNode.cpp b/source/Irrlicht/CSphereSceneNode.cpp
index c106368..eaceffd 100644
--- a/source/Irrlicht/CSphereSceneNode.cpp
+++ b/source/Irrlicht/CSphereSceneNode.cpp
@@ -1,156 +1,157 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CSphereSceneNode.h"
#include "IVideoDriver.h"
#include "ISceneManager.h"
#include "S3DVertex.h"
#include "os.h"
namespace irr
{
namespace scene
{
//! constructor
CSphereSceneNode::CSphereSceneNode(f32 radius, u32 polyCountX, u32 polyCountY, ISceneNode* parent, ISceneManager* mgr, s32 id,
const core::vector3df& position, const core::vector3df& rotation, const core::vector3df& scale)
: IMeshSceneNode(parent, mgr, id, position, rotation, scale), Mesh(0),
Radius(radius), PolyCountX(polyCountX), PolyCountY(polyCountY)
{
#ifdef _DEBUG
setDebugName("CSphereSceneNode");
#endif
Mesh = SceneManager->getGeometryCreator()->createSphereMesh(radius, polyCountX, polyCountY);
}
//! destructor
CSphereSceneNode::~CSphereSceneNode()
{
if (Mesh)
Mesh->drop();
}
//! renders the node.
void CSphereSceneNode::render()
{
video::IVideoDriver* driver = SceneManager->getVideoDriver();
if (Mesh && driver)
{
driver->setMaterial(Mesh->getMeshBuffer(0)->getMaterial());
driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
driver->drawMeshBuffer(Mesh->getMeshBuffer(0));
if ( DebugDataVisible & scene::EDS_BBOX )
{
video::SMaterial m;
m.Lighting = false;
driver->setMaterial(m);
driver->draw3DBox(Mesh->getMeshBuffer(0)->getBoundingBox(), video::SColor(255,255,255,255));
}
}
}
//! returns the axis aligned bounding box of this node
const core::aabbox3d<f32>& CSphereSceneNode::getBoundingBox() const
{
return Mesh ? Mesh->getBoundingBox() : Box;
}
void CSphereSceneNode::OnRegisterSceneNode()
{
if (IsVisible)
SceneManager->registerNodeForRendering(this);
ISceneNode::OnRegisterSceneNode();
}
//! returns the material based on the zero based index i. To get the amount
//! of materials used by this scene node, use getMaterialCount().
//! This function is needed for inserting the node into the scene hirachy on a
//! optimal position for minimizing renderstate changes, but can also be used
//! to directly modify the material of a scene node.
video::SMaterial& CSphereSceneNode::getMaterial(u32 i)
{
if (i>0 || !Mesh)
return ISceneNode::getMaterial(i);
else
return Mesh->getMeshBuffer(i)->getMaterial();
}
//! returns amount of materials used by this scene node.
u32 CSphereSceneNode::getMaterialCount() const
{
return 1;
}
//! Writes attributes of the scene node.
void CSphereSceneNode::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const
{
ISceneNode::serializeAttributes(out, options);
out->addFloat("Radius", Radius);
out->addInt("PolyCountX", PolyCountX);
out->addInt("PolyCountY", PolyCountY);
}
//! Reads attributes of the scene node.
void CSphereSceneNode::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
f32 oldRadius = Radius;
u32 oldPolyCountX = PolyCountX;
u32 oldPolyCountY = PolyCountY;
Radius = in->getAttributeAsFloat("Radius");
PolyCountX = in->getAttributeAsInt("PolyCountX");
PolyCountY = in->getAttributeAsInt("PolyCountY");
// legacy values read for compatibility with older versions
u32 polyCount = in->getAttributeAsInt("PolyCount");
if (PolyCountX ==0 && PolyCountY == 0)
PolyCountX = PolyCountY = polyCount;
Radius = core::max_(Radius, 0.0001f);
if ( !core::equals(Radius, oldRadius) || PolyCountX != oldPolyCountX || PolyCountY != oldPolyCountY)
{
if (Mesh)
Mesh->drop();
Mesh = SceneManager->getGeometryCreator()->createSphereMesh(Radius, PolyCountX, PolyCountY);
}
ISceneNode::deserializeAttributes(in, options);
}
//! Creates a clone of this scene node and its children.
ISceneNode* CSphereSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager)
{
if (!newParent)
newParent = Parent;
if (!newManager)
newManager = SceneManager;
- CSphereSceneNode* nb = new CSphereSceneNode(Radius, PolyCountX, PolyCountY, newParent,
+ CSphereSceneNode* nb = new CSphereSceneNode(Radius, PolyCountX, PolyCountY, newParent,
newManager, ID, RelativeTranslation);
nb->cloneMembers(this, newManager);
nb->getMaterial(0) = Mesh->getMeshBuffer(0)->getMaterial();
- nb->drop();
+ if ( newParent )
+ nb->drop();
return nb;
}
} // end namespace scene
} // end namespace irr
diff --git a/source/Irrlicht/CTerrainSceneNode.cpp b/source/Irrlicht/CTerrainSceneNode.cpp
index 11c1ef6..3109ada 100644
--- a/source/Irrlicht/CTerrainSceneNode.cpp
+++ b/source/Irrlicht/CTerrainSceneNode.cpp
@@ -1006,520 +1006,521 @@ namespace scene
return true;
}
//! Creates a planar texture mapping on the terrain
//! \param resolution: resolution of the planar mapping. This is the value
//! specifying the relation between world space and texture coordinate space.
void CTerrainSceneNode::scaleTexture(f32 resolution, f32 resolution2)
{
TCoordScale1 = resolution;
TCoordScale2 = resolution2;
const f32 resBySize = resolution / (f32)(TerrainData.Size-1);
const f32 res2BySize = resolution2 / (f32)(TerrainData.Size-1);
u32 index = 0;
f32 xval = 0.f;
f32 x2val = 0.f;
for (s32 x=0; x<TerrainData.Size; ++x)
{
f32 zval=0.f;
f32 z2val=0.f;
for (s32 z=0; z<TerrainData.Size; ++z)
{
RenderBuffer->getVertexBuffer()[index].TCoords.X = 1.f-xval;
RenderBuffer->getVertexBuffer()[index].TCoords.Y = zval;
if (RenderBuffer->getVertexType()==video::EVT_2TCOORDS)
{
if (resolution2 == 0)
{
((video::S3DVertex2TCoords&)RenderBuffer->getVertexBuffer()[index]).TCoords2 = RenderBuffer->getVertexBuffer()[index].TCoords;
}
else
{
((video::S3DVertex2TCoords&)RenderBuffer->getVertexBuffer()[index]).TCoords2.X = 1.f-x2val;
((video::S3DVertex2TCoords&)RenderBuffer->getVertexBuffer()[index]).TCoords2.Y = z2val;
}
}
++index;
zval += resBySize;
z2val += res2BySize;
}
xval += resBySize;
x2val += res2BySize;
}
RenderBuffer->setDirty(EBT_VERTEX);
}
//! used to get the indices when generating index data for patches at varying levels of detail.
u32 CTerrainSceneNode::getIndex(const s32 PatchX, const s32 PatchZ,
const s32 PatchIndex, u32 vX, u32 vZ) const
{
// top border
if (vZ == 0)
{
if (TerrainData.Patches[PatchIndex].Top &&
TerrainData.Patches[PatchIndex].CurrentLOD < TerrainData.Patches[PatchIndex].Top->CurrentLOD &&
(vX % (1 << TerrainData.Patches[PatchIndex].Top->CurrentLOD)) != 0 )
{
vX -= vX % (1 << TerrainData.Patches[PatchIndex].Top->CurrentLOD);
}
}
else
if (vZ == (u32)TerrainData.CalcPatchSize) // bottom border
{
if (TerrainData.Patches[PatchIndex].Bottom &&
TerrainData.Patches[PatchIndex].CurrentLOD < TerrainData.Patches[PatchIndex].Bottom->CurrentLOD &&
(vX % (1 << TerrainData.Patches[PatchIndex].Bottom->CurrentLOD)) != 0)
{
vX -= vX % (1 << TerrainData.Patches[PatchIndex].Bottom->CurrentLOD);
}
}
// left border
if (vX == 0)
{
if (TerrainData.Patches[PatchIndex].Left &&
TerrainData.Patches[PatchIndex].CurrentLOD < TerrainData.Patches[PatchIndex].Left->CurrentLOD &&
(vZ % (1 << TerrainData.Patches[PatchIndex].Left->CurrentLOD)) != 0)
{
vZ -= vZ % (1 << TerrainData.Patches[PatchIndex].Left->CurrentLOD);
}
}
else
if (vX == (u32)TerrainData.CalcPatchSize) // right border
{
if (TerrainData.Patches[PatchIndex].Right &&
TerrainData.Patches[PatchIndex].CurrentLOD < TerrainData.Patches[PatchIndex].Right->CurrentLOD &&
(vZ % (1 << TerrainData.Patches[PatchIndex].Right->CurrentLOD)) != 0)
{
vZ -= vZ % (1 << TerrainData.Patches[PatchIndex].Right->CurrentLOD);
}
}
if (vZ >= (u32)TerrainData.PatchSize)
vZ = TerrainData.CalcPatchSize;
if (vX >= (u32)TerrainData.PatchSize)
vX = TerrainData.CalcPatchSize;
return (vZ + ((TerrainData.CalcPatchSize) * PatchZ)) * TerrainData.Size +
(vX + ((TerrainData.CalcPatchSize) * PatchX));
}
//! smooth the terrain
void CTerrainSceneNode::smoothTerrain(IDynamicMeshBuffer* mb, s32 smoothFactor)
{
for (s32 run = 0; run < smoothFactor; ++run)
{
s32 yd = TerrainData.Size;
for (s32 y = 1; y < TerrainData.Size - 1; ++y)
{
for (s32 x = 1; x < TerrainData.Size - 1; ++x)
{
mb->getVertexBuffer()[x + yd].Pos.Y =
(mb->getVertexBuffer()[x-1 + yd].Pos.Y + //left
mb->getVertexBuffer()[x+1 + yd].Pos.Y + //right
mb->getVertexBuffer()[x + yd - TerrainData.Size].Pos.Y + //above
mb->getVertexBuffer()[x + yd + TerrainData.Size].Pos.Y) * 0.25f; //below
}
yd += TerrainData.Size;
}
}
}
//! calculate smooth normals
void CTerrainSceneNode::calculateNormals(IDynamicMeshBuffer* mb)
{
s32 count;
core::vector3df a, b, c, t;
for (s32 x=0; x<TerrainData.Size; ++x)
{
for (s32 z=0; z<TerrainData.Size; ++z)
{
count = 0;
core::vector3df normal;
// top left
if (x>0 && z>0)
{
a = mb->getVertexBuffer()[(x-1)*TerrainData.Size+z-1].Pos;
b = mb->getVertexBuffer()[(x-1)*TerrainData.Size+z].Pos;
c = mb->getVertexBuffer()[x*TerrainData.Size+z].Pos;
b -= a;
c -= a;
t = b.crossProduct(c);
t.normalize();
normal += t;
a = mb->getVertexBuffer()[(x-1)*TerrainData.Size+z-1].Pos;
b = mb->getVertexBuffer()[x*TerrainData.Size+z-1].Pos;
c = mb->getVertexBuffer()[x*TerrainData.Size+z].Pos;
b -= a;
c -= a;
t = b.crossProduct(c);
t.normalize();
normal += t;
count += 2;
}
// top right
if (x>0 && z<TerrainData.Size-1)
{
a = mb->getVertexBuffer()[(x-1)*TerrainData.Size+z].Pos;
b = mb->getVertexBuffer()[(x-1)*TerrainData.Size+z+1].Pos;
c = mb->getVertexBuffer()[x*TerrainData.Size+z+1].Pos;
b -= a;
c -= a;
t = b.crossProduct(c);
t.normalize();
normal += t;
a = mb->getVertexBuffer()[(x-1)*TerrainData.Size+z].Pos;
b = mb->getVertexBuffer()[x*TerrainData.Size+z+1].Pos;
c = mb->getVertexBuffer()[x*TerrainData.Size+z].Pos;
b -= a;
c -= a;
t = b.crossProduct(c);
t.normalize();
normal += t;
count += 2;
}
// bottom right
if (x<TerrainData.Size-1 && z<TerrainData.Size-1)
{
a = mb->getVertexBuffer()[x*TerrainData.Size+z+1].Pos;
b = mb->getVertexBuffer()[x*TerrainData.Size+z].Pos;
c = mb->getVertexBuffer()[(x+1)*TerrainData.Size+z+1].Pos;
b -= a;
c -= a;
t = b.crossProduct(c);
t.normalize();
normal += t;
a = mb->getVertexBuffer()[x*TerrainData.Size+z+1].Pos;
b = mb->getVertexBuffer()[(x+1)*TerrainData.Size+z+1].Pos;
c = mb->getVertexBuffer()[(x+1)*TerrainData.Size+z].Pos;
b -= a;
c -= a;
t = b.crossProduct(c);
t.normalize();
normal += t;
count += 2;
}
// bottom left
if (x<TerrainData.Size-1 && z>0)
{
a = mb->getVertexBuffer()[x*TerrainData.Size+z-1].Pos;
b = mb->getVertexBuffer()[x*TerrainData.Size+z].Pos;
c = mb->getVertexBuffer()[(x+1)*TerrainData.Size+z].Pos;
b -= a;
c -= a;
t = b.crossProduct(c);
t.normalize();
normal += t;
a = mb->getVertexBuffer()[x*TerrainData.Size+z-1].Pos;
b = mb->getVertexBuffer()[(x+1)*TerrainData.Size+z].Pos;
c = mb->getVertexBuffer()[(x+1)*TerrainData.Size+z-1].Pos;
b -= a;
c -= a;
t = b.crossProduct(c);
t.normalize();
normal += t;
count += 2;
}
if (count != 0)
{
normal.normalize();
}
else
{
normal.set(0.0f, 1.0f, 0.0f);
}
mb->getVertexBuffer()[x * TerrainData.Size + z].Normal = normal;
}
}
}
//! create patches, stuff that needs to be done only once for patches goes here.
void CTerrainSceneNode::createPatches()
{
TerrainData.PatchCount = (TerrainData.Size - 1) / (TerrainData.CalcPatchSize);
if (TerrainData.Patches)
delete [] TerrainData.Patches;
TerrainData.Patches = new SPatch[TerrainData.PatchCount * TerrainData.PatchCount];
}
//! used to calculate the internal STerrainData structure both at creation and after scaling/position calls.
void CTerrainSceneNode::calculatePatchData()
{
// Reset the Terrains Bounding Box for re-calculation
TerrainData.BoundingBox = core::aabbox3df(999999.9f, 999999.9f, 999999.9f, -999999.9f, -999999.9f, -999999.9f);
for (s32 x = 0; x < TerrainData.PatchCount; ++x)
{
for (s32 z = 0; z < TerrainData.PatchCount; ++z)
{
const s32 index = x * TerrainData.PatchCount + z;
TerrainData.Patches[index].CurrentLOD = 0;
// For each patch, calculate the bounding box (mins and maxes)
TerrainData.Patches[index].BoundingBox = core::aabbox3df(999999.9f, 999999.9f, 999999.9f,
-999999.9f, -999999.9f, -999999.9f);
for (s32 xx = x*(TerrainData.CalcPatchSize); xx <= (x + 1) * TerrainData.CalcPatchSize; ++xx)
for (s32 zz = z*(TerrainData.CalcPatchSize); zz <= (z + 1) * TerrainData.CalcPatchSize; ++zz)
TerrainData.Patches[index].BoundingBox.addInternalPoint(RenderBuffer->getVertexBuffer()[xx * TerrainData.Size + zz].Pos);
// Reconfigure the bounding box of the terrain as a whole
TerrainData.BoundingBox.addInternalBox(TerrainData.Patches[index].BoundingBox);
// get center of Patch
TerrainData.Patches[index].Center = TerrainData.Patches[index].BoundingBox.getCenter();
// Assign Neighbours
// Top
if (x > 0)
TerrainData.Patches[index].Top = &TerrainData.Patches[(x-1) * TerrainData.PatchCount + z];
else
TerrainData.Patches[index].Top = 0;
// Bottom
if (x < TerrainData.PatchCount - 1)
TerrainData.Patches[index].Bottom = &TerrainData.Patches[(x+1) * TerrainData.PatchCount + z];
else
TerrainData.Patches[index].Bottom = 0;
// Left
if (z > 0)
TerrainData.Patches[index].Left = &TerrainData.Patches[x * TerrainData.PatchCount + z - 1];
else
TerrainData.Patches[index].Left = 0;
// Right
if (z < TerrainData.PatchCount - 1)
TerrainData.Patches[index].Right = &TerrainData.Patches[x * TerrainData.PatchCount + z + 1];
else
TerrainData.Patches[index].Right = 0;
}
}
// get center of Terrain
TerrainData.Center = TerrainData.BoundingBox.getCenter();
// if the default rotation pivot is still being used, update it.
if (UseDefaultRotationPivot)
{
TerrainData.RotationPivot = TerrainData.Center;
}
}
//! used to calculate or recalculate the distance thresholds
void CTerrainSceneNode::calculateDistanceThresholds(bool scalechanged)
{
// Only update the LODDistanceThreshold if it's not manually changed
if (!OverrideDistanceThreshold)
{
TerrainData.LODDistanceThreshold.set_used(0);
// Determine new distance threshold for determining what LOD to draw patches at
TerrainData.LODDistanceThreshold.reallocate(TerrainData.MaxLOD);
const f64 size = TerrainData.PatchSize * TerrainData.PatchSize *
TerrainData.Scale.X * TerrainData.Scale.Z;
for (s32 i=0; i<TerrainData.MaxLOD; ++i)
{
TerrainData.LODDistanceThreshold.push_back(size * ((i+1+ i / 2) * (i+1+ i / 2)));
}
}
}
void CTerrainSceneNode::setCurrentLODOfPatches(s32 lod)
{
const s32 count = TerrainData.PatchCount * TerrainData.PatchCount;
for (s32 i=0; i< count; ++i)
TerrainData.Patches[i].CurrentLOD = lod;
}
void CTerrainSceneNode::setCurrentLODOfPatches(const core::array<s32>& lodarray)
{
const s32 count = TerrainData.PatchCount * TerrainData.PatchCount;
for (s32 i=0; i<count; ++i)
TerrainData.Patches[i].CurrentLOD = lodarray[i];
}
//! Gets the height
f32 CTerrainSceneNode::getHeight(f32 x, f32 z) const
{
if (!Mesh->getMeshBufferCount())
return 0;
f32 height = -999999.9f;
core::matrix4 rotMatrix;
rotMatrix.setRotationDegrees(TerrainData.Rotation);
core::vector3df pos(x, 0.0f, z);
rotMatrix.rotateVect(pos);
pos -= TerrainData.Position;
pos /= TerrainData.Scale;
s32 X(core::floor32(pos.X));
s32 Z(core::floor32(pos.Z));
if (X >= 0 && X < TerrainData.Size-1 &&
Z >= 0 && Z < TerrainData.Size-1)
{
const video::S3DVertex2TCoords* Vertices = (const video::S3DVertex2TCoords*)Mesh->getMeshBuffer(0)->getVertices();
const core::vector3df& a = Vertices[X * TerrainData.Size + Z].Pos;
const core::vector3df& b = Vertices[(X + 1) * TerrainData.Size + Z].Pos;
const core::vector3df& c = Vertices[X * TerrainData.Size + (Z + 1)].Pos;
const core::vector3df& d = Vertices[(X + 1) * TerrainData.Size + (Z + 1)].Pos;
// offset from integer position
const f32 dx = pos.X - X;
const f32 dz = pos.Z - Z;
if (dx > dz)
height = a.Y + (d.Y - b.Y)*dz + (b.Y - a.Y)*dx;
else
height = a.Y + (d.Y - c.Y)*dx + (c.Y - a.Y)*dz;
height *= TerrainData.Scale.Y;
height += TerrainData.Position.Y;
}
return height;
}
//! Writes attributes of the scene node.
void CTerrainSceneNode::serializeAttributes(io::IAttributes* out,
io::SAttributeReadWriteOptions* options) const
{
ISceneNode::serializeAttributes(out, options);
out->addString("Heightmap", HeightmapFile.c_str());
out->addFloat("TextureScale1", TCoordScale1);
out->addFloat("TextureScale2", TCoordScale2);
}
//! Reads attributes of the scene node.
void CTerrainSceneNode::deserializeAttributes(io::IAttributes* in,
io::SAttributeReadWriteOptions* options)
{
io::path newHeightmap = in->getAttributeAsString("Heightmap");
f32 tcoordScale1 = in->getAttributeAsFloat("TextureScale1");
f32 tcoordScale2 = in->getAttributeAsFloat("TextureScale2");
// set possible new heightmap
if (newHeightmap.size() != 0 && newHeightmap != HeightmapFile)
{
io::IReadFile* file = FileSystem->createAndOpenFile(newHeightmap.c_str());
if (file)
{
loadHeightMap(file, video::SColor(255,255,255,255), 0);
file->drop();
}
else
os::Printer::log("could not open heightmap", newHeightmap.c_str());
}
// set possible new scale
if (core::equals(tcoordScale1, 0.f))
tcoordScale1 = 1.0f;
if (core::equals(tcoordScale2, 0.f))
tcoordScale2 = 1.0f;
if (!core::equals(tcoordScale1, TCoordScale1) ||
!core::equals(tcoordScale2, TCoordScale2))
{
scaleTexture(tcoordScale1, tcoordScale2);
}
ISceneNode::deserializeAttributes(in, options);
}
//! Creates a clone of this scene node and its children.
ISceneNode* CTerrainSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager)
{
if (!newParent)
newParent = Parent;
if (!newManager)
newManager = SceneManager;
CTerrainSceneNode* nb = new CTerrainSceneNode(
newParent, newManager, FileSystem, ID,
4, ETPS_17, getPosition(), getRotation(), getScale());
nb->cloneMembers(this, newManager);
// instead of cloning the data structures, recreate the terrain.
// (temporary solution)
// load file
io::IReadFile* file = FileSystem->createAndOpenFile(HeightmapFile.c_str());
if (file)
{
nb->loadHeightMap(file, video::SColor(255,255,255,255), 0);
file->drop();
}
// scale textures
nb->scaleTexture(TCoordScale1, TCoordScale2);
// copy materials
for (unsigned int m = 0; m<Mesh->getMeshBufferCount(); ++m)
{
if (nb->Mesh->getMeshBufferCount()>m &&
nb->Mesh->getMeshBuffer(m) &&
Mesh->getMeshBuffer(m))
{
nb->Mesh->getMeshBuffer(m)->getMaterial() =
Mesh->getMeshBuffer(m)->getMaterial();
}
}
nb->RenderBuffer->getMaterial() = RenderBuffer->getMaterial();
// finish
- nb->drop();
+ if ( newParent )
+ nb->drop();
return nb;
}
} // end namespace scene
} // end namespace irr
diff --git a/source/Irrlicht/CVolumeLightSceneNode.cpp b/source/Irrlicht/CVolumeLightSceneNode.cpp
index 423d86b..f18cfa0 100644
--- a/source/Irrlicht/CVolumeLightSceneNode.cpp
+++ b/source/Irrlicht/CVolumeLightSceneNode.cpp
@@ -1,201 +1,202 @@
// Copyright (C) 2007-2009 Dean Wadsworth
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CVolumeLightSceneNode.h"
#include "IVideoDriver.h"
#include "ISceneManager.h"
#include "S3DVertex.h"
#include "os.h"
namespace irr
{
namespace scene
{
//! constructor
CVolumeLightSceneNode::CVolumeLightSceneNode(ISceneNode* parent, ISceneManager* mgr,
s32 id, const u32 subdivU, const u32 subdivV,
const video::SColor foot,
const video::SColor tail,
const core::vector3df& position,
const core::vector3df& rotation, const core::vector3df& scale)
: IVolumeLightSceneNode(parent, mgr, id, position, rotation, scale),
Mesh(0), LPDistance(8.0f),
SubdivideU(subdivU), SubdivideV(subdivV),
FootColor(foot), TailColor(tail),
LightDimensions(core::vector3df(1.0f, 1.2f, 1.0f))
{
#ifdef _DEBUG
setDebugName("CVolumeLightSceneNode");
#endif
constructLight();
}
CVolumeLightSceneNode::~CVolumeLightSceneNode()
{
if (Mesh)
Mesh->drop();
}
void CVolumeLightSceneNode::constructLight()
{
if (Mesh)
Mesh->drop();
Mesh = SceneManager->getGeometryCreator()->createVolumeLightMesh(SubdivideU, SubdivideV, FootColor, TailColor, LPDistance, LightDimensions);
}
//! renders the node.
void CVolumeLightSceneNode::render()
{
if (!Mesh)
return;
video::IVideoDriver* driver = SceneManager->getVideoDriver();
driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
driver->setMaterial(Mesh->getMeshBuffer(0)->getMaterial());
driver->drawMeshBuffer(Mesh->getMeshBuffer(0));
}
//! returns the axis aligned bounding box of this node
const core::aabbox3d<f32>& CVolumeLightSceneNode::getBoundingBox() const
{
return Mesh->getBoundingBox();
}
void CVolumeLightSceneNode::OnRegisterSceneNode()
{
if (IsVisible)
{
SceneManager->registerNodeForRendering(this, ESNRP_TRANSPARENT);
}
ISceneNode::OnRegisterSceneNode();
}
//! returns the material based on the zero based index i. To get the amount
//! of materials used by this scene node, use getMaterialCount().
//! This function is needed for inserting the node into the scene hirachy on a
//! optimal position for minimizing renderstate changes, but can also be used
//! to directly modify the material of a scene node.
video::SMaterial& CVolumeLightSceneNode::getMaterial(u32 i)
{
return Mesh->getMeshBuffer(i)->getMaterial();
}
//! returns amount of materials used by this scene node.
u32 CVolumeLightSceneNode::getMaterialCount() const
{
return 1;
}
void CVolumeLightSceneNode::setSubDivideU (const u32 inU)
{
if (inU != SubdivideU)
{
SubdivideU = inU;
constructLight();
}
}
void CVolumeLightSceneNode::setSubDivideV (const u32 inV)
{
if (inV != SubdivideV)
{
SubdivideV = inV;
constructLight();
}
}
void CVolumeLightSceneNode::setFootColor(const video::SColor inColor)
{
if (inColor != FootColor)
{
FootColor = inColor;
constructLight();
}
}
void CVolumeLightSceneNode::setTailColor(const video::SColor inColor)
{
if (inColor != TailColor)
{
TailColor = inColor;
constructLight();
}
}
//! Writes attributes of the scene node.
void CVolumeLightSceneNode::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const
{
ISceneNode::serializeAttributes(out, options);
out->addFloat("lpDistance", LPDistance);
out->addInt("subDivideU", SubdivideU);
out->addInt("subDivideV", SubdivideV);
out->addColor("footColor", FootColor);
out->addColor("tailColor", TailColor);
out->addVector3d("lightDimension", LightDimensions);
}
//! Reads attributes of the scene node.
void CVolumeLightSceneNode::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
LPDistance = in->getAttributeAsFloat("lpDistance");
LPDistance = core::max_(LPDistance, 8.0f);
SubdivideU = in->getAttributeAsInt("subDivideU");
SubdivideU = core::max_(SubdivideU, 1u);
SubdivideV = in->getAttributeAsInt("subDivideV");
SubdivideV = core::max_(SubdivideV, 1u);
FootColor = in->getAttributeAsColor("footColor");
TailColor = in->getAttributeAsColor("tailColor");
LightDimensions = in->getAttributeAsVector3d("lightDimension");
constructLight();
ISceneNode::deserializeAttributes(in, options);
}
//! Creates a clone of this scene node and its children.
ISceneNode* CVolumeLightSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager)
{
if (!newParent)
newParent = Parent;
if (!newManager)
newManager = SceneManager;
CVolumeLightSceneNode* nb = new CVolumeLightSceneNode(newParent,
newManager, ID, SubdivideU, SubdivideV, FootColor, TailColor, RelativeTranslation);
nb->cloneMembers(this, newManager);
nb->getMaterial(0) = Mesh->getMeshBuffer(0)->getMaterial();
- nb->drop();
+ if ( newParent )
+ nb->drop();
return nb;
}
} // end namespace scene
} // end namespace irr
diff --git a/tests/tests-last-passed-at.txt b/tests/tests-last-passed-at.txt
index 8d480e7..242ffd4 100644
--- a/tests/tests-last-passed-at.txt
+++ b/tests/tests-last-passed-at.txt
@@ -1,4 +1,4 @@
Tests finished. 51 tests of 51 passed.
Compiled as DEBUG
-Test suite pass at GMT Fri Feb 12 21:54:42 2010
+Test suite pass at GMT Sat Mar 6 17:06:39 2010
|
paupawsan/Irrlicht
|
8000a89d01607729ca5765317f73489f89a0a111
|
Make sure TAB is still recognized on X11 when shift+tab is pressed. This also does fix going backwards with tabstops on X11.
|
diff --git a/source/Irrlicht/CIrrDeviceLinux.cpp b/source/Irrlicht/CIrrDeviceLinux.cpp
index dff1a29..b465222 100644
--- a/source/Irrlicht/CIrrDeviceLinux.cpp
+++ b/source/Irrlicht/CIrrDeviceLinux.cpp
@@ -489,1401 +489,1403 @@ bool CIrrDeviceLinux::createWindow()
visualAttrBuffer[19] -= 1;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
}
if (!configList)
{
visualAttrBuffer[17] = 0;
visualAttrBuffer[19] = 0;
configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems);
if (configList)
{
os::Printer::log("No FSAA available.", ELL_WARNING);
CreationParams.AntiAlias=0;
}
else
{
//reenable multisampling
visualAttrBuffer[17] = 1;
visualAttrBuffer[19] = CreationParams.AntiAlias;
}
}
}
}
if (configList)
{
glxFBConfig=configList[0];
XFree(configList);
UseGLXWindow=true;
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
typedef XVisualInfo * ( * PFNGLXGETVISUALFROMFBCONFIGPROC) (Display *dpy, GLXFBConfig config);
PFNGLXGETVISUALFROMFBCONFIGPROC glxGetVisualFromFBConfig= (PFNGLXGETVISUALFROMFBCONFIGPROC)glXGetProcAddress(reinterpret_cast<const GLubyte*>("glXGetVisualFromFBConfig"));
if (glxGetVisualFromFBConfig)
visual = glxGetVisualFromFBConfig(display,glxFBConfig);
#else
visual = glXGetVisualFromFBConfig(display,glxFBConfig);
#endif
}
}
else
#endif
{
// attribute array for the draw buffer
int visualAttrBuffer[] =
{
GLX_RGBA, GL_TRUE,
GLX_RED_SIZE, 4,
GLX_GREEN_SIZE, 4,
GLX_BLUE_SIZE, 4,
GLX_ALPHA_SIZE, CreationParams.WithAlphaChannel?1:0,
GLX_DEPTH_SIZE, CreationParams.ZBufferBits,
GLX_STENCIL_SIZE, CreationParams.Stencilbuffer?1:0, // 12,13
// The following attributes have no flags, but are
// either present or not. As a no-op we use
// GLX_USE_GL, which is silently ignored by glXChooseVisual
CreationParams.Doublebuffer?GLX_DOUBLEBUFFER:GLX_USE_GL, // 14
CreationParams.Stereobuffer?GLX_STEREO:GLX_USE_GL, // 15
None
};
visual=glXChooseVisual(display, screennr, visualAttrBuffer);
if (!visual)
{
if (CreationParams.Stencilbuffer)
os::Printer::log("No stencilbuffer available, disabling.", ELL_WARNING);
CreationParams.Stencilbuffer = !CreationParams.Stencilbuffer;
visualAttrBuffer[13]=CreationParams.Stencilbuffer?1:0;
visual=glXChooseVisual(display, screennr, visualAttrBuffer);
if (!visual && CreationParams.Doublebuffer)
{
os::Printer::log("No doublebuffering available.", ELL_WARNING);
CreationParams.Doublebuffer=false;
visualAttrBuffer[14] = GLX_USE_GL;
visual=glXChooseVisual(display, screennr, visualAttrBuffer);
}
}
}
}
else
os::Printer::log("No GLX support available. OpenGL driver will not work.", ELL_WARNING);
}
// don't use the XVisual with OpenGL, because it ignores all requested
// properties of the CreationParams
else if (!visual)
#endif // _IRR_COMPILE_WITH_OPENGL_
// create visual with standard X methods
{
os::Printer::log("Using plain X visual");
XVisualInfo visTempl; //Template to hold requested values
int visNumber; // Return value of available visuals
visTempl.screen = screennr;
// ARGB visuals should be avoided for usual applications
visTempl.depth = CreationParams.WithAlphaChannel?32:24;
while ((!visual) && (visTempl.depth>=16))
{
visual = XGetVisualInfo(display, VisualScreenMask|VisualDepthMask,
&visTempl, &visNumber);
visTempl.depth -= 8;
}
}
if (!visual)
{
os::Printer::log("Fatal error, could not get visual.", ELL_ERROR);
XCloseDisplay(display);
display=0;
return false;
}
#ifdef _DEBUG
else
os::Printer::log("Visual chosen: ", core::stringc(static_cast<u32>(visual->visualid)).c_str(), ELL_INFORMATION);
#endif
// create color map
Colormap colormap;
colormap = XCreateColormap(display,
RootWindow(display, visual->screen),
visual->visual, AllocNone);
attributes.colormap = colormap;
attributes.border_pixel = 0;
attributes.event_mask = StructureNotifyMask | FocusChangeMask | ExposureMask;
if (!CreationParams.IgnoreInput)
attributes.event_mask |= PointerMotionMask |
ButtonPressMask | KeyPressMask |
ButtonReleaseMask | KeyReleaseMask;
if (!CreationParams.WindowId)
{
// create new Window
// Remove window manager decoration in fullscreen
attributes.override_redirect = CreationParams.Fullscreen;
window = XCreateWindow(display,
RootWindow(display, visual->screen),
0, 0, Width, Height, 0, visual->depth,
InputOutput, visual->visual,
CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect,
&attributes);
XMapRaised(display, window);
CreationParams.WindowId = (void*)window;
Atom wmDelete;
wmDelete = XInternAtom(display, wmDeleteWindow, True);
XSetWMProtocols(display, window, &wmDelete, 1);
if (CreationParams.Fullscreen)
{
XSetInputFocus(display, window, RevertToParent, CurrentTime);
int grabKb = XGrabKeyboard(display, window, True, GrabModeAsync,
GrabModeAsync, CurrentTime);
IrrPrintXGrabError(grabKb, "XGrabKeyboard");
int grabPointer = XGrabPointer(display, window, True, ButtonPressMask,
GrabModeAsync, GrabModeAsync, window, None, CurrentTime);
IrrPrintXGrabError(grabPointer, "XGrabPointer");
XWarpPointer(display, None, window, 0, 0, 0, 0, 0, 0);
}
}
else
{
// attach external window
window = (Window)CreationParams.WindowId;
if (!CreationParams.IgnoreInput)
{
XCreateWindow(display,
window,
0, 0, Width, Height, 0, visual->depth,
InputOutput, visual->visual,
CWBorderPixel | CWColormap | CWEventMask,
&attributes);
}
XWindowAttributes wa;
XGetWindowAttributes(display, window, &wa);
CreationParams.WindowSize.Width = wa.width;
CreationParams.WindowSize.Height = wa.height;
CreationParams.Fullscreen = false;
ExternalWindow = true;
}
WindowMinimized=false;
// Currently broken in X, see Bug ID 2795321
// XkbSetDetectableAutoRepeat(display, True, &AutorepeatSupport);
#ifdef _IRR_COMPILE_WITH_OPENGL_
// connect glx context to window
Context=0;
if (isAvailableGLX && CreationParams.DriverType==video::EDT_OPENGL)
{
if (UseGLXWindow)
{
glxWin=glXCreateWindow(display,glxFBConfig,window,NULL);
if (glxWin)
{
// create glx context
Context = glXCreateNewContext(display, glxFBConfig, GLX_RGBA_TYPE, NULL, True);
if (Context)
{
if (!glXMakeContextCurrent(display, glxWin, glxWin, Context))
{
os::Printer::log("Could not make context current.", ELL_WARNING);
glXDestroyContext(display, Context);
}
}
else
{
os::Printer::log("Could not create GLX rendering context.", ELL_WARNING);
}
}
else
{
os::Printer::log("Could not create GLX window.", ELL_WARNING);
}
}
else
{
Context = glXCreateContext(display, visual, NULL, True);
if (Context)
{
if (!glXMakeCurrent(display, window, Context))
{
os::Printer::log("Could not make context current.", ELL_WARNING);
glXDestroyContext(display, Context);
}
}
else
{
os::Printer::log("Could not create GLX rendering context.", ELL_WARNING);
}
}
}
#endif // _IRR_COMPILE_WITH_OPENGL_
Window tmp;
u32 borderWidth;
int x,y;
unsigned int bits;
XGetGeometry(display, window, &tmp, &x, &y, &Width, &Height, &borderWidth, &bits);
CreationParams.Bits = bits;
CreationParams.WindowSize.Width = Width;
CreationParams.WindowSize.Height = Height;
StdHints = XAllocSizeHints();
long num;
XGetWMNormalHints(display, window, StdHints, &num);
// create an XImage for the software renderer
//(thx to Nadav for some clues on how to do that!)
if (CreationParams.DriverType == video::EDT_SOFTWARE || CreationParams.DriverType == video::EDT_BURNINGSVIDEO)
{
SoftwareImage = XCreateImage(display,
visual->visual, visual->depth,
ZPixmap, 0, 0, Width, Height,
BitmapPad(display), 0);
// use malloc because X will free it later on
if (SoftwareImage)
SoftwareImage->data = (char*) malloc(SoftwareImage->bytes_per_line * SoftwareImage->height * sizeof(char));
}
initXAtoms();
#endif // #ifdef _IRR_COMPILE_WITH_X11_
return true;
}
//! create the driver
void CIrrDeviceLinux::createDriver()
{
switch(CreationParams.DriverType)
{
#ifdef _IRR_COMPILE_WITH_X11_
case video::EDT_SOFTWARE:
#ifdef _IRR_COMPILE_WITH_SOFTWARE_
VideoDriver = video::createSoftwareDriver(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this);
#else
os::Printer::log("No Software driver support compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_BURNINGSVIDEO:
#ifdef _IRR_COMPILE_WITH_BURNINGSVIDEO_
VideoDriver = video::createSoftwareDriver2(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this);
#else
os::Printer::log("Burning's video driver was not compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_OPENGL:
#ifdef _IRR_COMPILE_WITH_OPENGL_
if (Context)
VideoDriver = video::createOpenGLDriver(CreationParams, FileSystem, this);
#else
os::Printer::log("No OpenGL support compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_DIRECT3D8:
case video::EDT_DIRECT3D9:
os::Printer::log("This driver is not available in Linux. Try OpenGL or Software renderer.",
ELL_ERROR);
break;
case video::EDT_NULL:
VideoDriver = video::createNullDriver(FileSystem, CreationParams.WindowSize);
break;
default:
os::Printer::log("Unable to create video driver of unknown type.", ELL_ERROR);
break;
#else
case video::EDT_NULL:
VideoDriver = video::createNullDriver(FileSystem, CreationParams.WindowSize);
break;
default:
os::Printer::log("No X11 support compiled in. Only Null driver available.", ELL_ERROR);
break;
#endif
}
}
//! runs the device. Returns false if device wants to be deleted
bool CIrrDeviceLinux::run()
{
os::Timer::tick();
#ifdef _IRR_COMPILE_WITH_X11_
if ((CreationParams.DriverType != video::EDT_NULL) && display)
{
SEvent irrevent;
irrevent.MouseInput.ButtonStates = 0xffffffff;
while (XPending(display) > 0 && !Close)
{
XEvent event;
XNextEvent(display, &event);
switch (event.type)
{
case ConfigureNotify:
// check for changed window size
if ((event.xconfigure.width != (int) Width) ||
(event.xconfigure.height != (int) Height))
{
Width = event.xconfigure.width;
Height = event.xconfigure.height;
// resize image data
if (SoftwareImage)
{
XDestroyImage(SoftwareImage);
SoftwareImage = XCreateImage(display,
visual->visual, visual->depth,
ZPixmap, 0, 0, Width, Height,
BitmapPad(display), 0);
// use malloc because X will free it later on
if (SoftwareImage)
SoftwareImage->data = (char*) malloc(SoftwareImage->bytes_per_line * SoftwareImage->height * sizeof(char));
}
if (VideoDriver)
VideoDriver->OnResize(core::dimension2d<u32>(Width, Height));
}
break;
case MapNotify:
WindowMinimized=false;
break;
case UnmapNotify:
WindowMinimized=true;
break;
case FocusIn:
WindowHasFocus=true;
break;
case FocusOut:
WindowHasFocus=false;
break;
case MotionNotify:
irrevent.EventType = irr::EET_MOUSE_INPUT_EVENT;
irrevent.MouseInput.Event = irr::EMIE_MOUSE_MOVED;
irrevent.MouseInput.X = event.xbutton.x;
irrevent.MouseInput.Y = event.xbutton.y;
irrevent.MouseInput.Control = (event.xkey.state & ControlMask) != 0;
irrevent.MouseInput.Shift = (event.xkey.state & ShiftMask) != 0;
// mouse button states
irrevent.MouseInput.ButtonStates = (event.xbutton.state & Button1Mask) ? irr::EMBSM_LEFT : 0;
irrevent.MouseInput.ButtonStates |= (event.xbutton.state & Button3Mask) ? irr::EMBSM_RIGHT : 0;
irrevent.MouseInput.ButtonStates |= (event.xbutton.state & Button2Mask) ? irr::EMBSM_MIDDLE : 0;
postEventFromUser(irrevent);
break;
case ButtonPress:
case ButtonRelease:
irrevent.EventType = irr::EET_MOUSE_INPUT_EVENT;
irrevent.MouseInput.X = event.xbutton.x;
irrevent.MouseInput.Y = event.xbutton.y;
irrevent.MouseInput.Control = (event.xkey.state & ControlMask) != 0;
irrevent.MouseInput.Shift = (event.xkey.state & ShiftMask) != 0;
// mouse button states
// This sets the state which the buttons had _prior_ to the event.
// So unlike on Windows the button which just got changed has still the old state here.
// We handle that below by flipping the corresponding bit later.
irrevent.MouseInput.ButtonStates = (event.xbutton.state & Button1Mask) ? irr::EMBSM_LEFT : 0;
irrevent.MouseInput.ButtonStates |= (event.xbutton.state & Button3Mask) ? irr::EMBSM_RIGHT : 0;
irrevent.MouseInput.ButtonStates |= (event.xbutton.state & Button2Mask) ? irr::EMBSM_MIDDLE : 0;
irrevent.MouseInput.Event = irr::EMIE_COUNT;
switch(event.xbutton.button)
{
case Button1:
irrevent.MouseInput.Event =
(event.type == ButtonPress) ? irr::EMIE_LMOUSE_PRESSED_DOWN : irr::EMIE_LMOUSE_LEFT_UP;
irrevent.MouseInput.ButtonStates ^= irr::EMBSM_LEFT;
break;
case Button3:
irrevent.MouseInput.Event =
(event.type == ButtonPress) ? irr::EMIE_RMOUSE_PRESSED_DOWN : irr::EMIE_RMOUSE_LEFT_UP;
irrevent.MouseInput.ButtonStates ^= irr::EMBSM_RIGHT;
break;
case Button2:
irrevent.MouseInput.Event =
(event.type == ButtonPress) ? irr::EMIE_MMOUSE_PRESSED_DOWN : irr::EMIE_MMOUSE_LEFT_UP;
irrevent.MouseInput.ButtonStates ^= irr::EMBSM_MIDDLE;
break;
case Button4:
if (event.type == ButtonPress)
{
irrevent.MouseInput.Event = EMIE_MOUSE_WHEEL;
irrevent.MouseInput.Wheel = 1.0f;
}
break;
case Button5:
if (event.type == ButtonPress)
{
irrevent.MouseInput.Event = EMIE_MOUSE_WHEEL;
irrevent.MouseInput.Wheel = -1.0f;
}
break;
}
if (irrevent.MouseInput.Event != irr::EMIE_COUNT)
{
postEventFromUser(irrevent);
if ( irrevent.MouseInput.Event >= EMIE_LMOUSE_PRESSED_DOWN && irrevent.MouseInput.Event <= EMIE_MMOUSE_PRESSED_DOWN )
{
u32 clicks = checkSuccessiveClicks(irrevent.MouseInput.X, irrevent.MouseInput.Y, irrevent.MouseInput.Event);
if ( clicks == 2 )
{
irrevent.MouseInput.Event = (EMOUSE_INPUT_EVENT)(EMIE_LMOUSE_DOUBLE_CLICK + irrevent.MouseInput.Event-EMIE_LMOUSE_PRESSED_DOWN);
postEventFromUser(irrevent);
}
else if ( clicks == 3 )
{
irrevent.MouseInput.Event = (EMOUSE_INPUT_EVENT)(EMIE_LMOUSE_TRIPLE_CLICK + irrevent.MouseInput.Event-EMIE_LMOUSE_PRESSED_DOWN);
postEventFromUser(irrevent);
}
}
}
break;
case MappingNotify:
XRefreshKeyboardMapping (&event.xmapping) ;
break;
case KeyRelease:
if (0 == AutorepeatSupport && (XPending( display ) > 0) )
{
// check for Autorepeat manually
// We'll do the same as Windows does: Only send KeyPressed
// So every KeyRelease is a real release
XEvent next_event;
XPeekEvent (event.xkey.display, &next_event);
if ((next_event.type == KeyPress) &&
(next_event.xkey.keycode == event.xkey.keycode) &&
(next_event.xkey.time - event.xkey.time) < 2) // usually same time, but on some systems a difference of 1 is possible
{
/* Ignore the key release event */
break;
}
}
// fall-through in case the release should be handled
case KeyPress:
{
SKeyMap mp;
char buf[8]={0};
XLookupString(&event.xkey, buf, sizeof(buf), &mp.X11Key, NULL);
const s32 idx = KeyMap.binary_search(mp);
if (idx != -1)
irrevent.KeyInput.Key = (EKEY_CODE)KeyMap[idx].Win32Key;
else
{
+ // Usually you will check keysymdef.h and add the corresponding key to createKeyMap.
irrevent.KeyInput.Key = (EKEY_CODE)0;
os::Printer::log("Could not find win32 key for x11 key.", core::stringc((int)mp.X11Key).c_str(), ELL_WARNING);
}
irrevent.EventType = irr::EET_KEY_INPUT_EVENT;
irrevent.KeyInput.PressedDown = (event.type == KeyPress);
// mbtowc(&irrevent.KeyInput.Char, buf, sizeof(buf));
irrevent.KeyInput.Char = ((wchar_t*)(buf))[0];
irrevent.KeyInput.Control = (event.xkey.state & ControlMask) != 0;
irrevent.KeyInput.Shift = (event.xkey.state & ShiftMask) != 0;
postEventFromUser(irrevent);
}
break;
case ClientMessage:
{
char *atom = XGetAtomName(display, event.xclient.message_type);
if (*atom == *wmDeleteWindow)
{
os::Printer::log("Quit message received.", ELL_INFORMATION);
Close = true;
}
else
{
// we assume it's a user message
irrevent.EventType = irr::EET_USER_EVENT;
irrevent.UserEvent.UserData1 = (s32)event.xclient.data.l[0];
irrevent.UserEvent.UserData2 = (s32)event.xclient.data.l[1];
postEventFromUser(irrevent);
}
XFree(atom);
}
break;
case SelectionRequest:
{
XEvent respond;
XSelectionRequestEvent *req = &(event.xselectionrequest);
if ( req->target == XA_STRING)
{
XChangeProperty (display,
req->requestor,
req->property, req->target,
8, // format
PropModeReplace,
(unsigned char*) Clipboard.c_str(),
Clipboard.size());
respond.xselection.property = req->property;
}
else if ( req->target == X_ATOM_TARGETS )
{
long data[2];
data[0] = X_ATOM_TEXT;
data[1] = XA_STRING;
XChangeProperty (display, req->requestor,
req->property, req->target,
8, PropModeReplace,
(unsigned char *) &data,
sizeof (data));
respond.xselection.property = req->property;
}
else
{
respond.xselection.property= None;
}
respond.xselection.type= SelectionNotify;
respond.xselection.display= req->display;
respond.xselection.requestor= req->requestor;
respond.xselection.selection=req->selection;
respond.xselection.target= req->target;
respond.xselection.time = req->time;
XSendEvent (display, req->requestor,0,0,&respond);
XFlush (display);
}
break;
default:
break;
} // end switch
} // end while
}
#endif //_IRR_COMPILE_WITH_X11_
if(!Close)
pollJoysticks();
return !Close;
}
//! Pause the current process for the minimum time allowed only to allow other processes to execute
void CIrrDeviceLinux::yield()
{
struct timespec ts = {0,0};
nanosleep(&ts, NULL);
}
//! Pause execution and let other processes to run for a specified amount of time.
void CIrrDeviceLinux::sleep(u32 timeMs, bool pauseTimer=false)
{
const bool wasStopped = Timer ? Timer->isStopped() : true;
struct timespec ts;
ts.tv_sec = (time_t) (timeMs / 1000);
ts.tv_nsec = (long) (timeMs % 1000) * 1000000;
if (pauseTimer && !wasStopped)
Timer->stop();
nanosleep(&ts, NULL);
if (pauseTimer && !wasStopped)
Timer->start();
}
//! sets the caption of the window
void CIrrDeviceLinux::setWindowCaption(const wchar_t* text)
{
#ifdef _IRR_COMPILE_WITH_X11_
if (CreationParams.DriverType == video::EDT_NULL)
return;
XTextProperty txt;
if (Success==XwcTextListToTextProperty(display, const_cast<wchar_t**>(&text),
1, XStdICCTextStyle, &txt))
{
XSetWMName(display, window, &txt);
XSetWMIconName(display, window, &txt);
XFree(txt.value);
}
#endif
}
//! presents a surface in the client area
bool CIrrDeviceLinux::present(video::IImage* image, void* windowId, core::rect<s32>* srcRect)
{
#ifdef _IRR_COMPILE_WITH_X11_
// this is only necessary for software drivers.
if (!SoftwareImage)
return true;
// thx to Nadav, who send me some clues of how to display the image
// to the X Server.
const u32 destwidth = SoftwareImage->width;
const u32 minWidth = core::min_(image->getDimension().Width, destwidth);
const u32 destPitch = SoftwareImage->bytes_per_line;
video::ECOLOR_FORMAT destColor;
switch (SoftwareImage->bits_per_pixel)
{
case 16:
if (SoftwareImage->depth==16)
destColor = video::ECF_R5G6B5;
else
destColor = video::ECF_A1R5G5B5;
break;
case 24: destColor = video::ECF_R8G8B8; break;
case 32: destColor = video::ECF_A8R8G8B8; break;
default:
os::Printer::log("Unsupported screen depth.");
return false;
}
u8* srcdata = reinterpret_cast<u8*>(image->lock());
u8* destData = reinterpret_cast<u8*>(SoftwareImage->data);
const u32 destheight = SoftwareImage->height;
const u32 srcheight = core::min_(image->getDimension().Height, destheight);
const u32 srcPitch = image->getPitch();
for (u32 y=0; y!=srcheight; ++y)
{
video::CColorConverter::convert_viaFormat(srcdata,image->getColorFormat(), minWidth, destData, destColor);
srcdata+=srcPitch;
destData+=destPitch;
}
image->unlock();
GC gc = DefaultGC(display, DefaultScreen(display));
Window myWindow=window;
if (windowId)
myWindow = reinterpret_cast<Window>(windowId);
XPutImage(display, myWindow, gc, SoftwareImage, 0, 0, 0, 0, destwidth, destheight);
#endif
return true;
}
//! notifies the device that it should close itself
void CIrrDeviceLinux::closeDevice()
{
Close = true;
}
//! returns if window is active. if not, nothing need to be drawn
bool CIrrDeviceLinux::isWindowActive() const
{
return (WindowHasFocus && !WindowMinimized);
}
//! returns if window has focus.
bool CIrrDeviceLinux::isWindowFocused() const
{
return WindowHasFocus;
}
//! returns if window is minimized.
bool CIrrDeviceLinux::isWindowMinimized() const
{
return WindowMinimized;
}
//! returns color format of the window.
video::ECOLOR_FORMAT CIrrDeviceLinux::getColorFormat() const
{
#ifdef _IRR_COMPILE_WITH_X11_
if (visual && (visual->depth != 16))
return video::ECF_R8G8B8;
else
#endif
return video::ECF_R5G6B5;
}
//! Sets if the window should be resizable in windowed mode.
void CIrrDeviceLinux::setResizable(bool resize)
{
#ifdef _IRR_COMPILE_WITH_X11_
if (CreationParams.DriverType == video::EDT_NULL)
return;
XUnmapWindow(display, window);
if ( !resize )
{
// Must be heap memory because data size depends on X Server
XSizeHints *hints = XAllocSizeHints();
hints->flags=PSize|PMinSize|PMaxSize;
hints->min_width=hints->max_width=hints->base_width=Width;
hints->min_height=hints->max_height=hints->base_height=Height;
XSetWMNormalHints(display, window, hints);
XFree(hints);
}
else
{
XSetWMNormalHints(display, window, StdHints);
}
XMapWindow(display, window);
XFlush(display);
#endif // #ifdef _IRR_COMPILE_WITH_X11_
}
//! Return pointer to a list with all video modes supported by the gfx adapter.
video::IVideoModeList* CIrrDeviceLinux::getVideoModeList()
{
#ifdef _IRR_COMPILE_WITH_X11_
if (!VideoModeList.getVideoModeCount())
{
bool temporaryDisplay = false;
if (!display)
{
display = XOpenDisplay(0);
temporaryDisplay=true;
}
if (display)
{
#if defined(_IRR_LINUX_X11_VIDMODE_) || defined(_IRR_LINUX_X11_RANDR_)
s32 eventbase, errorbase;
s32 defaultDepth=DefaultDepth(display,screennr);
#endif
#ifdef _IRR_LINUX_X11_VIDMODE_
if (XF86VidModeQueryExtension(display, &eventbase, &errorbase))
{
// enumerate video modes
int modeCount;
XF86VidModeModeInfo** modes;
XF86VidModeGetAllModeLines(display, screennr, &modeCount, &modes);
// save current video mode
oldVideoMode = *modes[0];
// find fitting mode
VideoModeList.setDesktop(defaultDepth, core::dimension2d<u32>(
modes[0]->hdisplay, modes[0]->vdisplay));
for (int i = 0; i<modeCount; ++i)
{
VideoModeList.addMode(core::dimension2d<u32>(
modes[i]->hdisplay, modes[i]->vdisplay), defaultDepth);
}
XFree(modes);
}
else
#endif
#ifdef _IRR_LINUX_X11_RANDR_
if (XRRQueryExtension(display, &eventbase, &errorbase))
{
int modeCount;
XRRScreenConfiguration *config=XRRGetScreenInfo(display,DefaultRootWindow(display));
oldRandrMode=XRRConfigCurrentConfiguration(config,&oldRandrRotation);
XRRScreenSize *modes=XRRConfigSizes(config,&modeCount);
VideoModeList.setDesktop(defaultDepth, core::dimension2d<u32>(
modes[oldRandrMode].width, modes[oldRandrMode].height));
for (int i = 0; i<modeCount; ++i)
{
VideoModeList.addMode(core::dimension2d<u32>(
modes[i].width, modes[i].height), defaultDepth);
}
XRRFreeScreenConfigInfo(config);
}
else
#endif
{
os::Printer::log("VidMode or RandR X11 extension requireed for VideoModeList." , ELL_WARNING);
}
}
if (display && temporaryDisplay)
{
XCloseDisplay(display);
display=0;
}
}
#endif
return &VideoModeList;
}
//! Minimize window
void CIrrDeviceLinux::minimizeWindow()
{
#ifdef _IRR_COMPILE_WITH_X11_
XIconifyWindow(display, window, screennr);
#endif
}
//! Maximize window
void CIrrDeviceLinux::maximizeWindow()
{
#ifdef _IRR_COMPILE_WITH_X11_
XMapWindow(display, window);
#endif
}
//! Restore original window size
void CIrrDeviceLinux::restoreWindow()
{
#ifdef _IRR_COMPILE_WITH_X11_
XMapWindow(display, window);
#endif
}
void CIrrDeviceLinux::createKeyMap()
{
// I don't know if this is the best method to create
// the lookuptable, but I'll leave it like that until
// I find a better version.
#ifdef _IRR_COMPILE_WITH_X11_
KeyMap.reallocate(84);
KeyMap.push_back(SKeyMap(XK_BackSpace, KEY_BACK));
KeyMap.push_back(SKeyMap(XK_Tab, KEY_TAB));
+ KeyMap.push_back(SKeyMap(XK_ISO_Left_Tab, KEY_TAB));
KeyMap.push_back(SKeyMap(XK_Linefeed, 0)); // ???
KeyMap.push_back(SKeyMap(XK_Clear, KEY_CLEAR));
KeyMap.push_back(SKeyMap(XK_Return, KEY_RETURN));
KeyMap.push_back(SKeyMap(XK_Pause, KEY_PAUSE));
KeyMap.push_back(SKeyMap(XK_Scroll_Lock, KEY_SCROLL));
KeyMap.push_back(SKeyMap(XK_Sys_Req, 0)); // ???
KeyMap.push_back(SKeyMap(XK_Escape, KEY_ESCAPE));
KeyMap.push_back(SKeyMap(XK_Insert, KEY_INSERT));
KeyMap.push_back(SKeyMap(XK_Delete, KEY_DELETE));
KeyMap.push_back(SKeyMap(XK_Home, KEY_HOME));
KeyMap.push_back(SKeyMap(XK_Left, KEY_LEFT));
KeyMap.push_back(SKeyMap(XK_Up, KEY_UP));
KeyMap.push_back(SKeyMap(XK_Right, KEY_RIGHT));
KeyMap.push_back(SKeyMap(XK_Down, KEY_DOWN));
KeyMap.push_back(SKeyMap(XK_Prior, KEY_PRIOR));
KeyMap.push_back(SKeyMap(XK_Page_Up, KEY_PRIOR));
KeyMap.push_back(SKeyMap(XK_Next, KEY_NEXT));
KeyMap.push_back(SKeyMap(XK_Page_Down, KEY_NEXT));
KeyMap.push_back(SKeyMap(XK_End, KEY_END));
KeyMap.push_back(SKeyMap(XK_Begin, KEY_HOME));
KeyMap.push_back(SKeyMap(XK_Num_Lock, KEY_NUMLOCK));
KeyMap.push_back(SKeyMap(XK_KP_Space, KEY_SPACE));
KeyMap.push_back(SKeyMap(XK_KP_Tab, KEY_TAB));
KeyMap.push_back(SKeyMap(XK_KP_Enter, KEY_RETURN));
KeyMap.push_back(SKeyMap(XK_KP_F1, KEY_F1));
KeyMap.push_back(SKeyMap(XK_KP_F2, KEY_F2));
KeyMap.push_back(SKeyMap(XK_KP_F3, KEY_F3));
KeyMap.push_back(SKeyMap(XK_KP_F4, KEY_F4));
KeyMap.push_back(SKeyMap(XK_KP_Home, KEY_HOME));
KeyMap.push_back(SKeyMap(XK_KP_Left, KEY_LEFT));
KeyMap.push_back(SKeyMap(XK_KP_Up, KEY_UP));
KeyMap.push_back(SKeyMap(XK_KP_Right, KEY_RIGHT));
KeyMap.push_back(SKeyMap(XK_KP_Down, KEY_DOWN));
KeyMap.push_back(SKeyMap(XK_Print, KEY_PRINT));
KeyMap.push_back(SKeyMap(XK_KP_Prior, KEY_PRIOR));
KeyMap.push_back(SKeyMap(XK_KP_Page_Up, KEY_PRIOR));
KeyMap.push_back(SKeyMap(XK_KP_Next, KEY_NEXT));
KeyMap.push_back(SKeyMap(XK_KP_Page_Down, KEY_NEXT));
KeyMap.push_back(SKeyMap(XK_KP_End, KEY_END));
KeyMap.push_back(SKeyMap(XK_KP_Begin, KEY_HOME));
KeyMap.push_back(SKeyMap(XK_KP_Insert, KEY_INSERT));
KeyMap.push_back(SKeyMap(XK_KP_Delete, KEY_DELETE));
KeyMap.push_back(SKeyMap(XK_KP_Equal, 0)); // ???
KeyMap.push_back(SKeyMap(XK_KP_Multiply, KEY_MULTIPLY));
KeyMap.push_back(SKeyMap(XK_KP_Add, KEY_ADD));
KeyMap.push_back(SKeyMap(XK_KP_Separator, KEY_SEPARATOR));
KeyMap.push_back(SKeyMap(XK_KP_Subtract, KEY_SUBTRACT));
KeyMap.push_back(SKeyMap(XK_KP_Decimal, KEY_DECIMAL));
KeyMap.push_back(SKeyMap(XK_KP_Divide, KEY_DIVIDE));
KeyMap.push_back(SKeyMap(XK_KP_0, KEY_KEY_0));
KeyMap.push_back(SKeyMap(XK_KP_1, KEY_KEY_1));
KeyMap.push_back(SKeyMap(XK_KP_2, KEY_KEY_2));
KeyMap.push_back(SKeyMap(XK_KP_3, KEY_KEY_3));
KeyMap.push_back(SKeyMap(XK_KP_4, KEY_KEY_4));
KeyMap.push_back(SKeyMap(XK_KP_5, KEY_KEY_5));
KeyMap.push_back(SKeyMap(XK_KP_6, KEY_KEY_6));
KeyMap.push_back(SKeyMap(XK_KP_7, KEY_KEY_7));
KeyMap.push_back(SKeyMap(XK_KP_8, KEY_KEY_8));
KeyMap.push_back(SKeyMap(XK_KP_9, KEY_KEY_9));
KeyMap.push_back(SKeyMap(XK_F1, KEY_F1));
KeyMap.push_back(SKeyMap(XK_F2, KEY_F2));
KeyMap.push_back(SKeyMap(XK_F3, KEY_F3));
KeyMap.push_back(SKeyMap(XK_F4, KEY_F4));
KeyMap.push_back(SKeyMap(XK_F5, KEY_F5));
KeyMap.push_back(SKeyMap(XK_F6, KEY_F6));
KeyMap.push_back(SKeyMap(XK_F7, KEY_F7));
KeyMap.push_back(SKeyMap(XK_F8, KEY_F8));
KeyMap.push_back(SKeyMap(XK_F9, KEY_F9));
KeyMap.push_back(SKeyMap(XK_F10, KEY_F10));
KeyMap.push_back(SKeyMap(XK_F11, KEY_F11));
KeyMap.push_back(SKeyMap(XK_F12, KEY_F12));
KeyMap.push_back(SKeyMap(XK_Shift_L, KEY_LSHIFT));
KeyMap.push_back(SKeyMap(XK_Shift_R, KEY_RSHIFT));
KeyMap.push_back(SKeyMap(XK_Control_L, KEY_LCONTROL));
KeyMap.push_back(SKeyMap(XK_Control_R, KEY_RCONTROL));
KeyMap.push_back(SKeyMap(XK_Caps_Lock, KEY_CAPITAL));
KeyMap.push_back(SKeyMap(XK_Shift_Lock, KEY_CAPITAL));
KeyMap.push_back(SKeyMap(XK_Meta_L, KEY_LWIN));
KeyMap.push_back(SKeyMap(XK_Meta_R, KEY_RWIN));
KeyMap.push_back(SKeyMap(XK_Alt_L, KEY_LMENU));
KeyMap.push_back(SKeyMap(XK_Alt_R, KEY_RMENU));
KeyMap.push_back(SKeyMap(XK_ISO_Level3_Shift, KEY_RMENU));
KeyMap.push_back(SKeyMap(XK_Menu, KEY_MENU));
KeyMap.push_back(SKeyMap(XK_space, KEY_SPACE));
KeyMap.push_back(SKeyMap(XK_exclam, 0)); //?
KeyMap.push_back(SKeyMap(XK_quotedbl, 0)); //?
KeyMap.push_back(SKeyMap(XK_section, 0)); //?
KeyMap.push_back(SKeyMap(XK_numbersign, 0)); //?
KeyMap.push_back(SKeyMap(XK_dollar, 0)); //?
KeyMap.push_back(SKeyMap(XK_percent, 0)); //?
KeyMap.push_back(SKeyMap(XK_ampersand, 0)); //?
KeyMap.push_back(SKeyMap(XK_apostrophe, 0)); //?
KeyMap.push_back(SKeyMap(XK_parenleft, 0)); //?
KeyMap.push_back(SKeyMap(XK_parenright, 0)); //?
KeyMap.push_back(SKeyMap(XK_asterisk, 0)); //?
KeyMap.push_back(SKeyMap(XK_plus, KEY_PLUS)); //?
KeyMap.push_back(SKeyMap(XK_comma, KEY_COMMA)); //?
KeyMap.push_back(SKeyMap(XK_minus, KEY_MINUS)); //?
KeyMap.push_back(SKeyMap(XK_period, KEY_PERIOD)); //?
KeyMap.push_back(SKeyMap(XK_slash, 0)); //?
KeyMap.push_back(SKeyMap(XK_0, KEY_KEY_0));
KeyMap.push_back(SKeyMap(XK_1, KEY_KEY_1));
KeyMap.push_back(SKeyMap(XK_2, KEY_KEY_2));
KeyMap.push_back(SKeyMap(XK_3, KEY_KEY_3));
KeyMap.push_back(SKeyMap(XK_4, KEY_KEY_4));
KeyMap.push_back(SKeyMap(XK_5, KEY_KEY_5));
KeyMap.push_back(SKeyMap(XK_6, KEY_KEY_6));
KeyMap.push_back(SKeyMap(XK_7, KEY_KEY_7));
KeyMap.push_back(SKeyMap(XK_8, KEY_KEY_8));
KeyMap.push_back(SKeyMap(XK_9, KEY_KEY_9));
KeyMap.push_back(SKeyMap(XK_colon, 0)); //?
KeyMap.push_back(SKeyMap(XK_semicolon, 0)); //?
KeyMap.push_back(SKeyMap(XK_less, 0)); //?
KeyMap.push_back(SKeyMap(XK_equal, 0)); //?
KeyMap.push_back(SKeyMap(XK_greater, 0)); //?
KeyMap.push_back(SKeyMap(XK_question, 0)); //?
KeyMap.push_back(SKeyMap(XK_at, 0)); //?
KeyMap.push_back(SKeyMap(XK_mu, 0)); //?
KeyMap.push_back(SKeyMap(XK_EuroSign, 0)); //?
KeyMap.push_back(SKeyMap(XK_A, KEY_KEY_A));
KeyMap.push_back(SKeyMap(XK_B, KEY_KEY_B));
KeyMap.push_back(SKeyMap(XK_C, KEY_KEY_C));
KeyMap.push_back(SKeyMap(XK_D, KEY_KEY_D));
KeyMap.push_back(SKeyMap(XK_E, KEY_KEY_E));
KeyMap.push_back(SKeyMap(XK_F, KEY_KEY_F));
KeyMap.push_back(SKeyMap(XK_G, KEY_KEY_G));
KeyMap.push_back(SKeyMap(XK_H, KEY_KEY_H));
KeyMap.push_back(SKeyMap(XK_I, KEY_KEY_I));
KeyMap.push_back(SKeyMap(XK_J, KEY_KEY_J));
KeyMap.push_back(SKeyMap(XK_K, KEY_KEY_K));
KeyMap.push_back(SKeyMap(XK_L, KEY_KEY_L));
KeyMap.push_back(SKeyMap(XK_M, KEY_KEY_M));
KeyMap.push_back(SKeyMap(XK_N, KEY_KEY_N));
KeyMap.push_back(SKeyMap(XK_O, KEY_KEY_O));
KeyMap.push_back(SKeyMap(XK_P, KEY_KEY_P));
KeyMap.push_back(SKeyMap(XK_Q, KEY_KEY_Q));
KeyMap.push_back(SKeyMap(XK_R, KEY_KEY_R));
KeyMap.push_back(SKeyMap(XK_S, KEY_KEY_S));
KeyMap.push_back(SKeyMap(XK_T, KEY_KEY_T));
KeyMap.push_back(SKeyMap(XK_U, KEY_KEY_U));
KeyMap.push_back(SKeyMap(XK_V, KEY_KEY_V));
KeyMap.push_back(SKeyMap(XK_W, KEY_KEY_W));
KeyMap.push_back(SKeyMap(XK_X, KEY_KEY_X));
KeyMap.push_back(SKeyMap(XK_Y, KEY_KEY_Y));
KeyMap.push_back(SKeyMap(XK_Z, KEY_KEY_Z));
KeyMap.push_back(SKeyMap(XK_Adiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_Odiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_Udiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_bracketleft, 0)); //?
KeyMap.push_back(SKeyMap(XK_backslash, 0)); //?
KeyMap.push_back(SKeyMap(XK_bracketright, 0)); //?
KeyMap.push_back(SKeyMap(XK_asciicircum, 0)); //?
KeyMap.push_back(SKeyMap(XK_degree, 0)); //?
KeyMap.push_back(SKeyMap(XK_underscore, 0)); //?
KeyMap.push_back(SKeyMap(XK_grave, 0)); //?
KeyMap.push_back(SKeyMap(XK_acute, 0)); //?
KeyMap.push_back(SKeyMap(XK_quoteleft, 0)); //?
KeyMap.push_back(SKeyMap(XK_a, KEY_KEY_A));
KeyMap.push_back(SKeyMap(XK_b, KEY_KEY_B));
KeyMap.push_back(SKeyMap(XK_c, KEY_KEY_C));
KeyMap.push_back(SKeyMap(XK_d, KEY_KEY_D));
KeyMap.push_back(SKeyMap(XK_e, KEY_KEY_E));
KeyMap.push_back(SKeyMap(XK_f, KEY_KEY_F));
KeyMap.push_back(SKeyMap(XK_g, KEY_KEY_G));
KeyMap.push_back(SKeyMap(XK_h, KEY_KEY_H));
KeyMap.push_back(SKeyMap(XK_i, KEY_KEY_I));
KeyMap.push_back(SKeyMap(XK_j, KEY_KEY_J));
KeyMap.push_back(SKeyMap(XK_k, KEY_KEY_K));
KeyMap.push_back(SKeyMap(XK_l, KEY_KEY_L));
KeyMap.push_back(SKeyMap(XK_m, KEY_KEY_M));
KeyMap.push_back(SKeyMap(XK_n, KEY_KEY_N));
KeyMap.push_back(SKeyMap(XK_o, KEY_KEY_O));
KeyMap.push_back(SKeyMap(XK_p, KEY_KEY_P));
KeyMap.push_back(SKeyMap(XK_q, KEY_KEY_Q));
KeyMap.push_back(SKeyMap(XK_r, KEY_KEY_R));
KeyMap.push_back(SKeyMap(XK_s, KEY_KEY_S));
KeyMap.push_back(SKeyMap(XK_t, KEY_KEY_T));
KeyMap.push_back(SKeyMap(XK_u, KEY_KEY_U));
KeyMap.push_back(SKeyMap(XK_v, KEY_KEY_V));
KeyMap.push_back(SKeyMap(XK_w, KEY_KEY_W));
KeyMap.push_back(SKeyMap(XK_x, KEY_KEY_X));
KeyMap.push_back(SKeyMap(XK_y, KEY_KEY_Y));
KeyMap.push_back(SKeyMap(XK_z, KEY_KEY_Z));
KeyMap.push_back(SKeyMap(XK_ssharp, 0)); //?
KeyMap.push_back(SKeyMap(XK_adiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_odiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_udiaeresis, 0)); //?
KeyMap.sort();
#endif
}
bool CIrrDeviceLinux::activateJoysticks(core::array<SJoystickInfo> & joystickInfo)
{
#if defined (_IRR_COMPILE_WITH_JOYSTICK_EVENTS_)
joystickInfo.clear();
u32 joystick;
for(joystick = 0; joystick < 32; ++joystick)
{
// The joystick device could be here...
core::stringc devName = "/dev/js";
devName += joystick;
SJoystickInfo returnInfo;
JoystickInfo info;
info.fd = open(devName.c_str(), O_RDONLY);
if(-1 == info.fd)
{
// ...but Ubuntu and possibly other distros
// create the devices in /dev/input
devName = "/dev/input/js";
devName += joystick;
info.fd = open(devName.c_str(), O_RDONLY);
if(-1 == info.fd)
{
// and BSD here
devName = "/dev/joy";
devName += joystick;
info.fd = open(devName.c_str(), O_RDONLY);
}
}
if(-1 == info.fd)
continue;
#ifdef __FREE_BSD_
info.axes=2;
info.buttons=2;
#else
ioctl( info.fd, JSIOCGAXES, &(info.axes) );
ioctl( info.fd, JSIOCGBUTTONS, &(info.buttons) );
fcntl( info.fd, F_SETFL, O_NONBLOCK );
#endif
(void)memset(&info.persistentData, 0, sizeof(info.persistentData));
info.persistentData.EventType = irr::EET_JOYSTICK_INPUT_EVENT;
info.persistentData.JoystickEvent.Joystick = ActiveJoysticks.size();
// There's no obvious way to determine which (if any) axes represent a POV
// hat, so we'll just set it to "not used" and forget about it.
info.persistentData.JoystickEvent.POV = 65535;
ActiveJoysticks.push_back(info);
returnInfo.Joystick = joystick;
returnInfo.PovHat = SJoystickInfo::POV_HAT_UNKNOWN;
returnInfo.Axes = info.axes;
returnInfo.Buttons = info.buttons;
#ifndef __FREE_BSD_
char name[80];
ioctl( info.fd, JSIOCGNAME(80), name);
returnInfo.Name = name;
#endif
joystickInfo.push_back(returnInfo);
}
for(joystick = 0; joystick < joystickInfo.size(); ++joystick)
{
char logString[256];
(void)sprintf(logString, "Found joystick %u, %u axes, %u buttons '%s'",
joystick, joystickInfo[joystick].Axes,
joystickInfo[joystick].Buttons, joystickInfo[joystick].Name.c_str());
os::Printer::log(logString, ELL_INFORMATION);
}
return true;
#else
return false;
#endif // _IRR_COMPILE_WITH_JOYSTICK_EVENTS_
}
void CIrrDeviceLinux::pollJoysticks()
{
#if defined (_IRR_COMPILE_WITH_JOYSTICK_EVENTS_)
if(0 == ActiveJoysticks.size())
return;
u32 j;
for(j= 0; j< ActiveJoysticks.size(); ++j)
{
JoystickInfo & info = ActiveJoysticks[j];
#ifdef __FREE_BSD_
struct joystick js;
if( read( info.fd, &js, JS_RETURN ) == JS_RETURN )
{
info.persistentData.JoystickEvent.ButtonStates = js.buttons; /* should be a two-bit field */
info.persistentData.JoystickEvent.Axis[0] = js.x; /* X axis */
info.persistentData.JoystickEvent.Axis[1] = js.y; /* Y axis */
#else
struct js_event event;
while(sizeof(event) == read(info.fd, &event, sizeof(event)))
{
switch(event.type & ~JS_EVENT_INIT)
{
case JS_EVENT_BUTTON:
if (event.value)
info.persistentData.JoystickEvent.ButtonStates |= (1 << event.number);
else
info.persistentData.JoystickEvent.ButtonStates &= ~(1 << event.number);
break;
case JS_EVENT_AXIS:
info.persistentData.JoystickEvent.Axis[event.number] = event.value;
break;
default:
break;
}
}
#endif
// Send an irrlicht joystick event once per ::run() even if no new data were received.
(void)postEventFromUser(info.persistentData);
}
#endif // _IRR_COMPILE_WITH_JOYSTICK_EVENTS_
}
//! Set the current Gamma Value for the Display
bool CIrrDeviceLinux::setGammaRamp( f32 red, f32 green, f32 blue, f32 brightness, f32 contrast )
{
#if defined(_IRR_LINUX_X11_VIDMODE_) || defined(_IRR_LINUX_X11_RANDR_)
s32 eventbase, errorbase;
#ifdef _IRR_LINUX_X11_VIDMODE_
if (XF86VidModeQueryExtension(display, &eventbase, &errorbase))
{
XF86VidModeGamma gamma;
gamma.red=red;
gamma.green=green;
gamma.blue=blue;
XF86VidModeSetGamma(display, screennr, &gamma);
return true;
}
#endif
#if defined(_IRR_LINUX_X11_VIDMODE_) && defined(_IRR_LINUX_X11_RANDR_)
else
#endif
#ifdef _IRR_LINUX_X11_RANDR_
if (XRRQueryExtension(display, &eventbase, &errorbase))
{
XRRQueryVersion(display, &eventbase, &errorbase); // major, minor
if (eventbase>=1 && errorbase>1)
{
#if (RANDR_MAJOR>1 || RANDR_MINOR>1)
XRRCrtcGamma *gamma = XRRGetCrtcGamma(display, screennr);
if (gamma)
{
*gamma->red=(u16)red;
*gamma->green=(u16)green;
*gamma->blue=(u16)blue;
XRRSetCrtcGamma(display, screennr, gamma);
XRRFreeGamma(gamma);
return true;
}
#endif
}
}
#endif
#endif
return false;
}
//! Get the current Gamma Value for the Display
bool CIrrDeviceLinux::getGammaRamp( f32 &red, f32 &green, f32 &blue, f32 &brightness, f32 &contrast )
{
brightness = 0.f;
contrast = 0.f;
#if defined(_IRR_LINUX_X11_VIDMODE_) || defined(_IRR_LINUX_X11_RANDR_)
s32 eventbase, errorbase;
#ifdef _IRR_LINUX_X11_VIDMODE_
if (XF86VidModeQueryExtension(display, &eventbase, &errorbase))
{
XF86VidModeGamma gamma;
XF86VidModeGetGamma(display, screennr, &gamma);
red = gamma.red;
green = gamma.green;
blue = gamma.blue;
return true;
}
#endif
#if defined(_IRR_LINUX_X11_VIDMODE_) && defined(_IRR_LINUX_X11_RANDR_)
else
#endif
#ifdef _IRR_LINUX_X11_RANDR_
if (XRRQueryExtension(display, &eventbase, &errorbase))
{
XRRQueryVersion(display, &eventbase, &errorbase); // major, minor
if (eventbase>=1 && errorbase>1)
{
#if (RANDR_MAJOR>1 || RANDR_MINOR>1)
XRRCrtcGamma *gamma = XRRGetCrtcGamma(display, screennr);
if (gamma)
{
red = *gamma->red;
green = *gamma->green;
blue= *gamma->blue;
XRRFreeGamma(gamma);
return true;
}
#endif
}
}
#endif
#endif
return false;
}
//! gets text from the clipboard
//! \return Returns 0 if no string is in there.
const c8* CIrrDeviceLinux::getTextFromClipboard() const
{
#if defined(_IRR_COMPILE_WITH_X11_)
Window ownerWindow = XGetSelectionOwner (display, X_ATOM_CLIPBOARD);
if ( ownerWindow == window )
{
return Clipboard.c_str();
}
Clipboard = "";
if (ownerWindow != None )
{
XConvertSelection (display, X_ATOM_CLIPBOARD, XA_STRING, None, ownerWindow, CurrentTime);
XFlush (display);
// check for data
Atom type;
int format;
unsigned long numItems, bytesLeft, dummy;
unsigned char *data;
XGetWindowProperty (display, ownerWindow,
XA_STRING, // property name
0, // offset
0, // length (we only check for data, so 0)
0, // Delete 0==false
AnyPropertyType, // AnyPropertyType or property identifier
&type, // return type
&format, // return format
&numItems, // number items
&bytesLeft, // remaining bytes for partial reads
&data); // data
if ( bytesLeft > 0 )
{
// there is some data to get
int result = XGetWindowProperty (display, ownerWindow, XA_STRING, 0,
bytesLeft, 0, AnyPropertyType, &type, &format,
&numItems, &dummy, &data);
if (result == Success)
Clipboard = (irr::c8*)data;
XFree (data);
}
}
return Clipboard.c_str();
#else
return 0;
#endif
}
//! copies text to the clipboard
void CIrrDeviceLinux::copyToClipboard(const c8* text) const
{
#if defined(_IRR_COMPILE_WITH_X11_)
// Actually there is no clipboard on X but applications just say they own the clipboard and return text when asked.
// Which btw. also means that on X you lose clipboard content when closing applications.
Clipboard = text;
XSetSelectionOwner (display, X_ATOM_CLIPBOARD, window, CurrentTime);
XFlush (display);
#endif
}
#ifdef _IRR_COMPILE_WITH_X11_
// return true if the passed event has the type passed in parameter arg
Bool PredicateIsEventType(Display *display, XEvent *event, XPointer arg)
{
if ( event && event->type == *(int*)arg )
{
// os::Printer::log("remove event:", core::stringc((int)arg).c_str(), ELL_INFORMATION);
return True;
}
return False;
}
#endif //_IRR_COMPILE_WITH_X11_
//! Remove all messages pending in the system message loop
void CIrrDeviceLinux::clearSystemMessages()
{
#ifdef _IRR_COMPILE_WITH_X11_
if (CreationParams.DriverType != video::EDT_NULL)
{
XEvent event;
int usrArg = ButtonPress;
while ( XCheckIfEvent(display, &event, PredicateIsEventType, XPointer(&usrArg)) == True ) {}
usrArg = ButtonRelease;
while ( XCheckIfEvent(display, &event, PredicateIsEventType, XPointer(&usrArg)) == True ) {}
usrArg = MotionNotify;
while ( XCheckIfEvent(display, &event, PredicateIsEventType, XPointer(&usrArg)) == True ) {}
usrArg = KeyRelease;
while ( XCheckIfEvent(display, &event, PredicateIsEventType, XPointer(&usrArg)) == True ) {}
usrArg = KeyPress;
while ( XCheckIfEvent(display, &event, PredicateIsEventType, XPointer(&usrArg)) == True ) {}
}
#endif //_IRR_COMPILE_WITH_X11_
}
|
paupawsan/Irrlicht
|
e2979f4d9eeb9682514eceadec4eca1f80e6e8a5
|
Document IGUIELement::setAlignment (was missing).
|
diff --git a/include/IGUIElement.h b/include/IGUIElement.h
index 44ded59..cfdcf18 100644
--- a/include/IGUIElement.h
+++ b/include/IGUIElement.h
@@ -1,701 +1,702 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __I_GUI_ELEMENT_H_INCLUDED__
#define __I_GUI_ELEMENT_H_INCLUDED__
#include "IAttributeExchangingObject.h"
#include "irrList.h"
#include "rect.h"
#include "irrString.h"
#include "IEventReceiver.h"
#include "EGUIElementTypes.h"
#include "EGUIAlignment.h"
#include "IAttributes.h"
namespace irr
{
namespace gui
{
class IGUIEnvironment;
//! Base class of all GUI elements.
class IGUIElement : public virtual io::IAttributeExchangingObject, public IEventReceiver
{
public:
//! Constructor
IGUIElement(EGUI_ELEMENT_TYPE type, IGUIEnvironment* environment, IGUIElement* parent,
s32 id, const core::rect<s32>& rectangle)
: Parent(0), RelativeRect(rectangle), AbsoluteRect(rectangle),
AbsoluteClippingRect(rectangle), DesiredRect(rectangle),
MaxSize(0,0), MinSize(1,1), IsVisible(true), IsEnabled(true),
IsSubElement(false), NoClip(false), ID(id), IsTabStop(false), TabOrder(-1), IsTabGroup(false),
AlignLeft(EGUIA_UPPERLEFT), AlignRight(EGUIA_UPPERLEFT), AlignTop(EGUIA_UPPERLEFT), AlignBottom(EGUIA_UPPERLEFT),
Environment(environment), Type(type)
{
#ifdef _DEBUG
setDebugName("IGUIElement");
#endif
// if we were given a parent to attach to
if (parent)
{
parent->addChildToEnd(this);
recalculateAbsolutePosition(true);
}
}
//! Destructor
virtual ~IGUIElement()
{
// delete all children
core::list<IGUIElement*>::Iterator it = Children.begin();
for (; it != Children.end(); ++it)
{
(*it)->Parent = 0;
(*it)->drop();
}
}
//! Returns parent of this element.
IGUIElement* getParent() const
{
return Parent;
}
//! Returns the relative rectangle of this element.
core::rect<s32> getRelativePosition() const
{
return RelativeRect;
}
//! Sets the relative rectangle of this element.
/** \param r The absolute position to set */
void setRelativePosition(const core::rect<s32>& r)
{
if (Parent)
{
const core::rect<s32>& r2 = Parent->getAbsolutePosition();
core::dimension2df d((f32)(r2.getSize().Width), (f32)(r2.getSize().Height));
if (AlignLeft == EGUIA_SCALE)
ScaleRect.UpperLeftCorner.X = (f32)r.UpperLeftCorner.X / d.Width;
if (AlignRight == EGUIA_SCALE)
ScaleRect.LowerRightCorner.X = (f32)r.LowerRightCorner.X / d.Width;
if (AlignTop == EGUIA_SCALE)
ScaleRect.UpperLeftCorner.Y = (f32)r.UpperLeftCorner.Y / d.Height;
if (AlignBottom == EGUIA_SCALE)
ScaleRect.LowerRightCorner.Y = (f32)r.LowerRightCorner.Y / d.Height;
}
DesiredRect = r;
updateAbsolutePosition();
}
//! Sets the relative rectangle of this element, maintaining its current width and height
/** \param position The new relative position to set. Width and height will not be changed. */
void setRelativePosition(const core::position2di & position)
{
const core::dimension2di mySize = RelativeRect.getSize();
const core::rect<s32> rectangle(position.X, position.Y,
position.X + mySize.Width, position.Y + mySize.Height);
setRelativePosition(rectangle);
}
//! Sets the relative rectangle of this element as a proportion of its parent's area.
/** \note This method used to be 'void setRelativePosition(const core::rect<f32>& r)'
\param r The rectangle to set, interpreted as a proportion of the parent's area.
Meaningful values are in the range [0...1], unless you intend this element to spill
outside its parent. */
void setRelativePositionProportional(const core::rect<f32>& r)
{
if (!Parent)
return;
const core::dimension2di& d = Parent->getAbsolutePosition().getSize();
DesiredRect = core::rect<s32>(
core::floor32((f32)d.Width * r.UpperLeftCorner.X),
core::floor32((f32)d.Height * r.UpperLeftCorner.Y),
core::floor32((f32)d.Width * r.LowerRightCorner.X),
core::floor32((f32)d.Height * r.LowerRightCorner.Y));
ScaleRect = r;
updateAbsolutePosition();
}
//! Gets the absolute rectangle of this element
core::rect<s32> getAbsolutePosition() const
{
return AbsoluteRect;
}
//! Returns the visible area of the element.
core::rect<s32> getAbsoluteClippingRect() const
{
return AbsoluteClippingRect;
}
//! Sets whether the element will ignore its parent's clipping rectangle
/** \param noClip If true, the element will not be clipped by its parent's clipping rectangle. */
void setNotClipped(bool noClip)
{
NoClip = noClip;
updateAbsolutePosition();
}
//! Gets whether the element will ignore its parent's clipping rectangle
/** \return true if the element is not clipped by its parent's clipping rectangle. */
bool isNotClipped() const
{
return NoClip;
}
//! Sets the maximum size allowed for this element
/** If set to 0,0, there is no maximum size */
void setMaxSize(core::dimension2du size)
{
MaxSize = size;
updateAbsolutePosition();
}
//! Sets the minimum size allowed for this element
void setMinSize(core::dimension2du size)
{
MinSize = size;
if (MinSize.Width < 1)
MinSize.Width = 1;
if (MinSize.Height < 1)
MinSize.Height = 1;
updateAbsolutePosition();
}
+ //! The alignment defines how the borders of this element will be positioned when the parent element is resized.
void setAlignment(EGUI_ALIGNMENT left, EGUI_ALIGNMENT right, EGUI_ALIGNMENT top, EGUI_ALIGNMENT bottom)
{
AlignLeft = left;
AlignRight = right;
AlignTop = top;
AlignBottom = bottom;
if (Parent)
{
core::rect<s32> r(Parent->getAbsolutePosition());
core::dimension2df d((f32)r.getSize().Width, (f32)r.getSize().Height);
if (AlignLeft == EGUIA_SCALE)
ScaleRect.UpperLeftCorner.X = (f32)DesiredRect.UpperLeftCorner.X / d.Width;
if (AlignRight == EGUIA_SCALE)
ScaleRect.LowerRightCorner.X = (f32)DesiredRect.LowerRightCorner.X / d.Width;
if (AlignTop == EGUIA_SCALE)
ScaleRect.UpperLeftCorner.Y = (f32)DesiredRect.UpperLeftCorner.Y / d.Height;
if (AlignBottom == EGUIA_SCALE)
ScaleRect.LowerRightCorner.Y = (f32)DesiredRect.LowerRightCorner.Y / d.Height;
}
}
//! Updates the absolute position.
virtual void updateAbsolutePosition()
{
recalculateAbsolutePosition(false);
// update all children
core::list<IGUIElement*>::Iterator it = Children.begin();
for (; it != Children.end(); ++it)
{
(*it)->updateAbsolutePosition();
}
}
//! Returns the topmost GUI element at the specific position.
/**
This will check this GUI element and all of its descendants, so it
may return this GUI element. To check all GUI elements, call this
function on device->getGUIEnvironment()->getRootGUIElement(). Note
that the root element is the size of the screen, so doing so (with
an on-screen point) will always return the root element if no other
element is above it at that point.
\param point: The point at which to find a GUI element.
\return The topmost GUI element at that point, or 0 if there are
no candidate elements at this point.
*/
IGUIElement* getElementFromPoint(const core::position2d<s32>& point)
{
IGUIElement* target = 0;
// we have to search from back to front, because later children
// might be drawn over the top of earlier ones.
core::list<IGUIElement*>::Iterator it = Children.getLast();
if (isVisible())
{
while(it != Children.end())
{
target = (*it)->getElementFromPoint(point);
if (target)
return target;
--it;
}
}
if (isVisible() && isPointInside(point))
target = this;
return target;
}
//! Returns true if a point is within this element.
/** Elements with a shape other than a rectangle should override this method */
virtual bool isPointInside(const core::position2d<s32>& point) const
{
return AbsoluteClippingRect.isPointInside(point);
}
//! Adds a GUI element as new child of this element.
virtual void addChild(IGUIElement* child)
{
addChildToEnd(child);
if (child)
{
child->updateAbsolutePosition();
}
}
//! Removes a child.
virtual void removeChild(IGUIElement* child)
{
core::list<IGUIElement*>::Iterator it = Children.begin();
for (; it != Children.end(); ++it)
if ((*it) == child)
{
(*it)->Parent = 0;
(*it)->drop();
Children.erase(it);
return;
}
}
//! Removes this element from its parent.
virtual void remove()
{
if (Parent)
Parent->removeChild(this);
}
//! Draws the element and its children.
virtual void draw()
{
if ( isVisible() )
{
core::list<IGUIElement*>::Iterator it = Children.begin();
for (; it != Children.end(); ++it)
(*it)->draw();
}
}
//! animate the element and its children.
virtual void OnPostRender(u32 timeMs)
{
if ( isVisible() )
{
core::list<IGUIElement*>::Iterator it = Children.begin();
for (; it != Children.end(); ++it)
(*it)->OnPostRender( timeMs );
}
}
//! Moves this element.
virtual void move(core::position2d<s32> absoluteMovement)
{
setRelativePosition(DesiredRect + absoluteMovement);
}
//! Returns true if element is visible.
virtual bool isVisible() const
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return IsVisible;
}
//! Sets the visible state of this element.
virtual void setVisible(bool visible)
{
IsVisible = visible;
}
//! Returns true if this element was created as part of its parent control
virtual bool isSubElement() const
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return IsSubElement;
}
//! Sets whether this control was created as part of its parent.
/** For example, it is true when a scrollbar is part of a listbox.
SubElements are not saved to disk when calling guiEnvironment->saveGUI() */
virtual void setSubElement(bool subElement)
{
IsSubElement = subElement;
}
//! If set to true, the focus will visit this element when using the tab key to cycle through elements.
/** If this element is a tab group (see isTabGroup/setTabGroup) then
ctrl+tab will be used instead. */
void setTabStop(bool enable)
{
IsTabStop = enable;
}
//! Returns true if this element can be focused by navigating with the tab key
bool isTabStop() const
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return IsTabStop;
}
//! Sets the priority of focus when using the tab key to navigate between a group of elements.
/** See setTabGroup, isTabGroup and getTabGroup for information on tab groups.
Elements with a lower number are focused first */
void setTabOrder(s32 index)
{
// negative = autonumber
if (index < 0)
{
TabOrder = 0;
IGUIElement *el = getTabGroup();
while (IsTabGroup && el && el->Parent)
el = el->Parent;
IGUIElement *first=0, *closest=0;
if (el)
{
// find the highest element number
el->getNextElement(-1, true, IsTabGroup, first, closest, true);
if (first)
{
TabOrder = first->getTabOrder() + 1;
}
}
}
else
TabOrder = index;
}
//! Returns the number in the tab order sequence
s32 getTabOrder() const
{
return TabOrder;
}
//! Sets whether this element is a container for a group of elements which can be navigated using the tab key.
/** For example, windows are tab groups.
Groups can be navigated using ctrl+tab, providing isTabStop is true. */
void setTabGroup(bool isGroup)
{
IsTabGroup = isGroup;
}
//! Returns true if this element is a tab group.
bool isTabGroup() const
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return IsTabGroup;
}
//! Returns the container element which holds all elements in this element's tab group.
IGUIElement* getTabGroup()
{
IGUIElement *ret=this;
while (ret && !ret->isTabGroup())
ret = ret->getParent();
return ret;
}
//! Returns true if element is enabled.
virtual bool isEnabled() const
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return IsEnabled;
}
//! Sets the enabled state of this element.
virtual void setEnabled(bool enabled)
{
IsEnabled = enabled;
}
//! Sets the new caption of this element.
virtual void setText(const wchar_t* text)
{
Text = text;
}
//! Returns caption of this element.
virtual const wchar_t* getText() const
{
return Text.c_str();
}
//! Sets the new caption of this element.
virtual void setToolTipText(const wchar_t* text)
{
ToolTipText = text;
}
//! Returns caption of this element.
virtual const core::stringw& getToolTipText() const
{
return ToolTipText;
}
//! Returns id. Can be used to identify the element.
virtual s32 getID() const
{
return ID;
}
//! Sets the id of this element
virtual void setID(s32 id)
{
ID = id;
}
//! Called if an event happened.
virtual bool OnEvent(const SEvent& event)
{
return Parent ? Parent->OnEvent(event) : false;
}
//! Brings a child to front
/** \return True if successful, false if not. */
virtual bool bringToFront(IGUIElement* element)
{
core::list<IGUIElement*>::Iterator it = Children.begin();
for (; it != Children.end(); ++it)
{
if (element == (*it))
{
Children.erase(it);
Children.push_back(element);
return true;
}
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
//! Returns list with children of this element
virtual const core::list<IGUIElement*>& getChildren() const
{
return Children;
}
//! Finds the first element with the given id.
/** \param id: Id to search for.
\param searchchildren: Set this to true, if also children of this
element may contain the element with the searched id and they
should be searched too.
\return Returns the first element with the given id. If no element
with this id was found, 0 is returned. */
virtual IGUIElement* getElementFromId(s32 id, bool searchchildren=false) const
{
IGUIElement* e = 0;
core::list<IGUIElement*>::ConstIterator it = Children.begin();
for (; it != Children.end(); ++it)
{
if ((*it)->getID() == id)
return (*it);
if (searchchildren)
e = (*it)->getElementFromId(id, true);
if (e)
return e;
}
return e;
}
//! returns true if the given element is a child of this one.
//! \param child: The child element to check
bool isMyChild(IGUIElement* child) const
{
if (!child)
return false;
do
{
if (child->Parent)
child = child->Parent;
} while (child->Parent && child != this);
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return child == this;
}
//! searches elements to find the closest next element to tab to
/** \param startOrder: The TabOrder of the current element, -1 if none
\param reverse: true if searching for a lower number
\param group: true if searching for a higher one
\param first: element with the highest/lowest known tab order depending on search direction
\param closest: the closest match, depending on tab order and direction
\param includeInvisible: includes invisible elements in the search (default=false)
\return true if successfully found an element, false to continue searching/fail */
bool getNextElement(s32 startOrder, bool reverse, bool group,
IGUIElement*& first, IGUIElement*& closest, bool includeInvisible=false) const
{
// we'll stop searching if we find this number
s32 wanted = startOrder + ( reverse ? -1 : 1 );
if (wanted==-2)
wanted = 1073741824; // maximum s32
core::list<IGUIElement*>::ConstIterator it = Children.begin();
s32 closestOrder, currentOrder;
while(it != Children.end())
{
// ignore invisible elements and their children
if ( ( (*it)->isVisible() || includeInvisible ) &&
(group == true || (*it)->isTabGroup() == false) )
{
// only check tab stops and those with the same group status
if ((*it)->isTabStop() && ((*it)->isTabGroup() == group))
{
currentOrder = (*it)->getTabOrder();
// is this what we're looking for?
if (currentOrder == wanted)
{
closest = *it;
return true;
}
// is it closer than the current closest?
if (closest)
{
closestOrder = closest->getTabOrder();
if ( ( reverse && currentOrder > closestOrder && currentOrder < startOrder)
||(!reverse && currentOrder < closestOrder && currentOrder > startOrder))
{
closest = *it;
}
}
else
if ( (reverse && currentOrder < startOrder) || (!reverse && currentOrder > startOrder) )
{
closest = *it;
}
// is it before the current first?
if (first)
{
closestOrder = first->getTabOrder();
if ( (reverse && closestOrder < currentOrder) || (!reverse && closestOrder > currentOrder) )
{
first = *it;
}
}
else
{
first = *it;
}
}
// search within children
if ((*it)->getNextElement(startOrder, reverse, group, first, closest))
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return true;
}
}
++it;
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
//! Returns the type of the gui element.
/** This is needed for the .NET wrapper but will be used
later for serializing and deserializing.
If you wrote your own GUIElements, you need to set the type for your element as first parameter
in the constructor of IGUIElement. For own (=unknown) elements, simply use EGUIET_ELEMENT as type */
EGUI_ELEMENT_TYPE getType() const
{
return Type;
}
//! Returns true if the gui element supports the given type.
/** This is mostly used to check if you can cast a gui element to the class that goes with the type.
Most gui elements will only support their own type, but if you derive your own classes from interfaces
you can overload this function and add a check for the type of the base-class additionally.
This allows for checks comparable to the dynamic_cast of c++ with enabled rtti.
Note that you can't do that by calling BaseClass::hasType(type), but you have to do an explicit
comparison check, because otherwise the base class usually just checks for the membervariable
Type which contains the type of your derived class.
*/
virtual bool hasType(EGUI_ELEMENT_TYPE type) const
{
return type == Type;
}
//! Returns the type name of the gui element.
|
paupawsan/Irrlicht
|
d094e4ead086b09d80c3211181c5ecedc050a370
|
Fix tooltips: - Make sure they get removed when the element is hidden or removed (thx to seven for finding) - Make (more) sure they don't get confused by gui-subelements - Fix the faster relaunch times (that did sometimes instead hide the tooltip) - Make sure hovered element is never the tooltip Send EGET_ELEMENT_LEFT also when there is no new hovered element Update docs for EGET_ELEMENT_LEFT and EGET_ELEMENT_HOVERED
|
diff --git a/include/IEventReceiver.h b/include/IEventReceiver.h
index 0ca2245..c365c1d 100644
--- a/include/IEventReceiver.h
+++ b/include/IEventReceiver.h
@@ -1,485 +1,487 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __I_EVENT_RECEIVER_H_INCLUDED__
#define __I_EVENT_RECEIVER_H_INCLUDED__
#include "ILogger.h"
#include "position2d.h"
#include "Keycodes.h"
#include "irrString.h"
namespace irr
{
//! Enumeration for all event types there are.
enum EEVENT_TYPE
{
//! An event of the graphical user interface.
/** GUI events are created by the GUI environment or the GUI elements in response
to mouse or keyboard events. When a GUI element receives an event it will either
process it and return true, or pass the event to its parent. If an event is not absorbed
before it reaches the root element then it will then be passed to the user receiver. */
EET_GUI_EVENT = 0,
//! A mouse input event.
/** Mouse events are created by the device and passed to IrrlichtDevice::postEventFromUser
in response to mouse input received from the operating system.
Mouse events are first passed to the user receiver, then to the GUI environment and its elements,
then finally the input receiving scene manager where it is passed to the active camera.
*/
EET_MOUSE_INPUT_EVENT,
//! A key input event.
/** Like mouse events, keyboard events are created by the device and passed to
IrrlichtDevice::postEventFromUser. They take the same path as mouse events. */
EET_KEY_INPUT_EVENT,
//! A joystick (joypad, gamepad) input event.
/** Joystick events are created by polling all connected joysticks once per
device run() and then passing the events to IrrlichtDevice::postEventFromUser.
They take the same path as mouse events.
Windows, SDL: Implemented.
Linux: Implemented, with POV hat issues.
MacOS / Other: Not yet implemented.
*/
EET_JOYSTICK_INPUT_EVENT,
//! A log event
/** Log events are only passed to the user receiver if there is one. If they are absorbed by the
user receiver then no text will be sent to the console. */
EET_LOG_TEXT_EVENT,
//! A user event with user data.
/** This is not used by Irrlicht and can be used to send user
specific data though the system. The Irrlicht 'window handle'
can be obtained from IrrlichtDevice::getExposedVideoData()
The usage and behaviour depends on the operating system:
Windows: send a WM_USER message to the Irrlicht Window; the
wParam and lParam will be used to populate the
UserData1 and UserData2 members of the SUserEvent.
Linux: send a ClientMessage via XSendEvent to the Irrlicht
Window; the data.l[0] and data.l[1] members will be
casted to s32 and used as UserData1 and UserData2.
MacOS: Not yet implemented
*/
EET_USER_EVENT,
//! This enum is never used, it only forces the compiler to
//! compile these enumeration values to 32 bit.
EGUIET_FORCE_32_BIT = 0x7fffffff
};
//! Enumeration for all mouse input events
enum EMOUSE_INPUT_EVENT
{
//! Left mouse button was pressed down.
EMIE_LMOUSE_PRESSED_DOWN = 0,
//! Right mouse button was pressed down.
EMIE_RMOUSE_PRESSED_DOWN,
//! Middle mouse button was pressed down.
EMIE_MMOUSE_PRESSED_DOWN,
//! Left mouse button was left up.
EMIE_LMOUSE_LEFT_UP,
//! Right mouse button was left up.
EMIE_RMOUSE_LEFT_UP,
//! Middle mouse button was left up.
EMIE_MMOUSE_LEFT_UP,
//! The mouse cursor changed its position.
EMIE_MOUSE_MOVED,
//! The mouse wheel was moved. Use Wheel value in event data to find out
//! in what direction and how fast.
EMIE_MOUSE_WHEEL,
//! Left mouse button double click.
//! This event is generated after the second EMIE_LMOUSE_PRESSED_DOWN event.
EMIE_LMOUSE_DOUBLE_CLICK,
//! Right mouse button double click.
//! This event is generated after the second EMIE_RMOUSE_PRESSED_DOWN event.
EMIE_RMOUSE_DOUBLE_CLICK,
//! Middle mouse button double click.
//! This event is generated after the second EMIE_MMOUSE_PRESSED_DOWN event.
EMIE_MMOUSE_DOUBLE_CLICK,
//! Left mouse button triple click.
//! This event is generated after the third EMIE_LMOUSE_PRESSED_DOWN event.
EMIE_LMOUSE_TRIPLE_CLICK,
//! Right mouse button triple click.
//! This event is generated after the third EMIE_RMOUSE_PRESSED_DOWN event.
EMIE_RMOUSE_TRIPLE_CLICK,
//! Middle mouse button triple click.
//! This event is generated after the third EMIE_MMOUSE_PRESSED_DOWN event.
EMIE_MMOUSE_TRIPLE_CLICK,
//! No real event. Just for convenience to get number of events
EMIE_COUNT
};
//! Masks for mouse button states
enum E_MOUSE_BUTTON_STATE_MASK
{
EMBSM_LEFT = 0x01,
EMBSM_RIGHT = 0x02,
EMBSM_MIDDLE = 0x04,
//! currently only on windows
EMBSM_EXTRA1 = 0x08,
//! currently only on windows
EMBSM_EXTRA2 = 0x10,
EMBSM_FORCE_32_BIT = 0x7fffffff
};
namespace gui
{
class IGUIElement;
//! Enumeration for all events which are sendable by the gui system
enum EGUI_EVENT_TYPE
{
//! A gui element has lost its focus.
/** GUIEvent.Caller is losing the focus to GUIEvent.Element.
If the event is absorbed then the focus will not be changed. */
EGET_ELEMENT_FOCUS_LOST = 0,
//! A gui element has got the focus.
/** If the event is absorbed then the focus will not be changed. */
EGET_ELEMENT_FOCUSED,
//! The mouse cursor hovered over a gui element.
+ /** If an element has sub-elements you also get this message for the subelements */
EGET_ELEMENT_HOVERED,
//! The mouse cursor left the hovered element.
+ /** If an element has sub-elements you also get this message for the subelements */
EGET_ELEMENT_LEFT,
//! An element would like to close.
/** Windows and context menus use this event when they would like to close,
this can be cancelled by absorbing the event. */
EGET_ELEMENT_CLOSED,
//! A button was clicked.
EGET_BUTTON_CLICKED,
//! A scrollbar has changed its position.
EGET_SCROLL_BAR_CHANGED,
//! A checkbox has changed its check state.
EGET_CHECKBOX_CHANGED,
//! A new item in a listbox was selected.
/** NOTE: You also get this event currently when the same item was clicked again after more than 500 ms. */
EGET_LISTBOX_CHANGED,
//! An item in the listbox was selected, which was already selected.
/** NOTE: You get the event currently only if the item was clicked again within 500 ms or selected by "enter" or "space". */
EGET_LISTBOX_SELECTED_AGAIN,
//! A file has been selected in the file dialog
EGET_FILE_SELECTED,
//! A directory has been selected in the file dialog
EGET_DIRECTORY_SELECTED,
//! A file open dialog has been closed without choosing a file
EGET_FILE_CHOOSE_DIALOG_CANCELLED,
//! 'Yes' was clicked on a messagebox
EGET_MESSAGEBOX_YES,
//! 'No' was clicked on a messagebox
EGET_MESSAGEBOX_NO,
//! 'OK' was clicked on a messagebox
EGET_MESSAGEBOX_OK,
//! 'Cancel' was clicked on a messagebox
EGET_MESSAGEBOX_CANCEL,
//! In an editbox 'ENTER' was pressed
EGET_EDITBOX_ENTER,
//! The text in an editbox was changed. This does not include automatic changes in text-breaking.
EGET_EDITBOX_CHANGED,
//! The marked area in an editbox was changed.
EGET_EDITBOX_MARKING_CHANGED,
//! The tab was changed in an tab control
EGET_TAB_CHANGED,
//! A menu item was selected in a (context) menu
EGET_MENU_ITEM_SELECTED,
//! The selection in a combo box has been changed
EGET_COMBO_BOX_CHANGED,
//! The value of a spin box has changed
EGET_SPINBOX_CHANGED,
//! A table has changed
EGET_TABLE_CHANGED,
EGET_TABLE_HEADER_CHANGED,
EGET_TABLE_SELECTED_AGAIN,
//! A tree view node lost selection. See IGUITreeView::getLastEventNode().
EGET_TREEVIEW_NODE_DESELECT,
//! A tree view node was selected. See IGUITreeView::getLastEventNode().
EGET_TREEVIEW_NODE_SELECT,
//! A tree view node was expanded. See IGUITreeView::getLastEventNode().
EGET_TREEVIEW_NODE_EXPAND,
//! A tree view node was collapsed. See IGUITreeView::getLastEventNode().
EGET_TREEVIEW_NODE_COLLAPS,
//! No real event. Just for convenience to get number of events
EGET_COUNT
};
} // end namespace gui
//! SEvents hold information about an event. See irr::IEventReceiver for details on event handling.
struct SEvent
{
//! Any kind of GUI event.
struct SGUIEvent
{
//! IGUIElement who called the event
gui::IGUIElement* Caller;
//! If the event has something to do with another element, it will be held here.
gui::IGUIElement* Element;
//! Type of GUI Event
gui::EGUI_EVENT_TYPE EventType;
};
//! Any kind of mouse event.
struct SMouseInput
{
//! X position of mouse cursor
s32 X;
//! Y position of mouse cursor
s32 Y;
//! mouse wheel delta, usually 1.0 or -1.0.
/** Only valid if event was EMIE_MOUSE_WHEEL */
f32 Wheel;
//! True if shift was also pressed
bool Shift:1;
//! True if ctrl was also pressed
bool Control:1;
//! A bitmap of button states. You can use isButtonPressed() to determine
//! if a button is pressed or not.
//! Currently only valid if the event was EMIE_MOUSE_MOVED
u32 ButtonStates;
//! Is the left button pressed down?
bool isLeftPressed() const { return 0 != ( ButtonStates & EMBSM_LEFT ); }
//! Is the right button pressed down?
bool isRightPressed() const { return 0 != ( ButtonStates & EMBSM_RIGHT ); }
//! Is the middle button pressed down?
bool isMiddlePressed() const { return 0 != ( ButtonStates & EMBSM_MIDDLE ); }
//! Type of mouse event
EMOUSE_INPUT_EVENT Event;
};
//! Any kind of keyboard event.
struct SKeyInput
{
//! Character corresponding to the key (0, if not a character)
wchar_t Char;
//! Key which has been pressed or released
EKEY_CODE Key;
//! If not true, then the key was left up
bool PressedDown:1;
//! True if shift was also pressed
bool Shift:1;
//! True if ctrl was also pressed
bool Control:1;
};
//! A joystick event.
/** Unlike other events, joystick events represent the result of polling
* each connected joystick once per run() of the device. Joystick events will
* not be generated by default. If joystick support is available for the
* active device, _IRR_COMPILE_WITH_JOYSTICK_EVENTS_ is defined, and
* @ref irr::IrrlichtDevice::activateJoysticks() has been called, an event of
* this type will be generated once per joystick per @ref IrrlichtDevice::run()
* regardless of whether the state of the joystick has actually changed. */
struct SJoystickEvent
{
enum
{
NUMBER_OF_BUTTONS = 32,
AXIS_X = 0, // e.g. analog stick 1 left to right
AXIS_Y, // e.g. analog stick 1 top to bottom
AXIS_Z, // e.g. throttle, or analog 2 stick 2 left to right
AXIS_R, // e.g. rudder, or analog 2 stick 2 top to bottom
AXIS_U,
AXIS_V,
NUMBER_OF_AXES
};
/** A bitmap of button states. You can use IsButtonPressed() to
( check the state of each button from 0 to (NUMBER_OF_BUTTONS - 1) */
u32 ButtonStates;
/** For AXIS_X, AXIS_Y, AXIS_Z, AXIS_R, AXIS_U and AXIS_V
* Values are in the range -32768 to 32767, with 0 representing
* the center position. You will receive the raw value from the
* joystick, and so will usually want to implement a dead zone around
* the center of the range. Axes not supported by this joystick will
* always have a value of 0. On Linux, POV hats are represented as axes,
* usually the last two active axis.
*/
s16 Axis[NUMBER_OF_AXES];
/** The POV represents the angle of the POV hat in degrees * 100,
* from 0 to 35,900. A value of 65535 indicates that the POV hat
* is centered (or not present).
* This value is only supported on Windows. On Linux, the POV hat
* will be sent as 2 axes instead. */
u16 POV;
//! The ID of the joystick which generated this event.
/** This is an internal Irrlicht index; it does not map directly
* to any particular hardware joystick. */
u8 Joystick;
//! A helper function to check if a button is pressed.
bool IsButtonPressed(u32 button) const
{
if(button >= (u32)NUMBER_OF_BUTTONS)
return false;
return (ButtonStates & (1 << button)) ? true : false;
}
};
//! Any kind of log event.
struct SLogEvent
{
//! Pointer to text which has been logged
const c8* Text;
//! Log level in which the text has been logged
ELOG_LEVEL Level;
};
//! Any kind of user event.
struct SUserEvent
{
//! Some user specified data as int
s32 UserData1;
//! Another user specified data as int
s32 UserData2;
};
EEVENT_TYPE EventType;
union
{
struct SGUIEvent GUIEvent;
struct SMouseInput MouseInput;
struct SKeyInput KeyInput;
struct SJoystickEvent JoystickEvent;
struct SLogEvent LogEvent;
struct SUserEvent UserEvent;
};
};
//! Interface of an object which can receive events.
/** Many of the engine's classes inherit IEventReceiver so they are able to
process events. Events usually start at a postEventFromUser function and are
passed down through a chain of event receivers until OnEvent returns true. See
irr::EEVENT_TYPE for a description of where each type of event starts, and the
path it takes through the system. */
class IEventReceiver
{
public:
//! Destructor
virtual ~IEventReceiver() {}
//! Called if an event happened.
/** Please take care that you should only return 'true' when you want to _prevent_ Irrlicht
* from processing the event any further. So 'true' does mean that an event is completely done.
* Therefore your return value for all unprocessed events should be 'false'.
\return True if the event was processed.
*/
virtual bool OnEvent(const SEvent& event) = 0;
};
//! Information on a joystick, returned from @ref irr::IrrlichtDevice::activateJoysticks()
struct SJoystickInfo
{
//! The ID of the joystick
/** This is an internal Irrlicht index; it does not map directly
* to any particular hardware joystick. It corresponds to the
* irr::SJoystickEvent Joystick ID. */
u8 Joystick;
//! The name that the joystick uses to identify itself.
core::stringc Name;
//! The number of buttons that the joystick has.
u32 Buttons;
//! The number of axes that the joystick has, i.e. X, Y, Z, R, U, V.
/** Note: with a Linux device, the POV hat (if any) will use two axes. These
* will be included in this count. */
u32 Axes;
//! An indication of whether the joystick has a POV hat.
/** A Windows device will identify the presence or absence or the POV hat. A
* Linux device cannot, and will always return POV_HAT_UNKNOWN. */
enum
{
//! A hat is definitely present.
POV_HAT_PRESENT,
//! A hat is definitely not present.
POV_HAT_ABSENT,
//! The presence or absence of a hat cannot be determined.
POV_HAT_UNKNOWN
} PovHat;
}; // struct SJoystickInfo
} // end namespace irr
#endif
diff --git a/source/Irrlicht/CGUIEnvironment.cpp b/source/Irrlicht/CGUIEnvironment.cpp
index 7a743bb..551c5c2 100644
--- a/source/Irrlicht/CGUIEnvironment.cpp
+++ b/source/Irrlicht/CGUIEnvironment.cpp
@@ -1,1007 +1,1045 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CGUIEnvironment.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include "IVideoDriver.h"
#include "CGUISkin.h"
#include "CGUIButton.h"
#include "CGUIWindow.h"
#include "CGUIScrollBar.h"
#include "CGUIFont.h"
#include "CGUISpriteBank.h"
#include "CGUIImage.h"
#include "CGUIMeshViewer.h"
#include "CGUICheckBox.h"
#include "CGUIListBox.h"
#include "CGUITreeView.h"
#include "CGUIImageList.h"
#include "CGUIFileOpenDialog.h"
#include "CGUIColorSelectDialog.h"
#include "CGUIStaticText.h"
#include "CGUIEditBox.h"
#include "CGUISpinBox.h"
#include "CGUIInOutFader.h"
#include "CGUIMessageBox.h"
#include "CGUIModalScreen.h"
#include "CGUITabControl.h"
#include "CGUIContextMenu.h"
#include "CGUIComboBox.h"
#include "CGUIMenu.h"
#include "CGUIToolBar.h"
#include "CGUITable.h"
#include "CDefaultGUIElementFactory.h"
#include "IWriteFile.h"
#include "IXMLWriter.h"
#include "BuiltInFont.h"
#include "os.h"
namespace irr
{
namespace gui
{
const wchar_t* IRR_XML_FORMAT_GUI_ENV = L"irr_gui";
const wchar_t* IRR_XML_FORMAT_GUI_ELEMENT = L"element";
const wchar_t* IRR_XML_FORMAT_GUI_ELEMENT_ATTR_TYPE = L"type";
//! constructor
CGUIEnvironment::CGUIEnvironment(io::IFileSystem* fs, video::IVideoDriver* driver, IOSOperator* op)
: IGUIElement(EGUIET_ELEMENT, 0, 0, 0, core::rect<s32>(core::position2d<s32>(0,0), driver ? core::dimension2d<s32>(driver->getScreenSize()) : core::dimension2d<s32>(0,0))),
- Driver(driver), Hovered(0), Focus(0), LastHoveredMousePos(0,0), CurrentSkin(0),
+ Driver(driver), Hovered(0), HoveredNoSubelement(0), Focus(0), LastHoveredMousePos(0,0), CurrentSkin(0),
FileSystem(fs), UserReceiver(0), Operator(op)
{
if (Driver)
Driver->grab();
if (FileSystem)
FileSystem->grab();
if (Operator)
Operator->grab();
#ifdef _DEBUG
IGUIEnvironment::setDebugName("CGUIEnvironment");
#endif
// gui factory
IGUIElementFactory* factory = new CDefaultGUIElementFactory(this);
registerGUIElementFactory(factory);
factory->drop();
loadBuiltInFont();
IGUISkin* skin = createSkin( gui::EGST_WINDOWS_METALLIC );
setSkin(skin);
skin->drop();
//set tooltip default
ToolTip.LastTime = 0;
+ ToolTip.EnterTime = 0;
ToolTip.LaunchTime = 1000;
+ ToolTip.RelaunchTime = 500;
ToolTip.Element = 0;
// environment is root tab group
Environment = this;
setTabGroup(true);
}
//! destructor
CGUIEnvironment::~CGUIEnvironment()
{
+ if ( HoveredNoSubelement && HoveredNoSubelement != this )
+ {
+ HoveredNoSubelement->drop();
+ HoveredNoSubelement = 0;
+ }
+
if (Hovered && Hovered != this)
{
Hovered->drop();
Hovered = 0;
}
if (Driver)
{
Driver->drop();
Driver = 0;
}
if (Focus)
{
Focus->drop();
Focus = 0;
}
if (ToolTip.Element)
{
ToolTip.Element->drop();
ToolTip.Element = 0;
}
if (FileSystem)
{
FileSystem->drop();
FileSystem = 0;
}
if (Operator)
{
Operator->drop();
Operator = 0;
}
// drop skin
if (CurrentSkin)
{
CurrentSkin->drop();
CurrentSkin = 0;
}
u32 i;
// delete all sprite banks
for (i=0; i<Banks.size(); ++i)
if (Banks[i].Bank)
Banks[i].Bank->drop();
// delete all fonts
for (i=0; i<Fonts.size(); ++i)
Fonts[i].Font->drop();
// remove all factories
for (i=0; i<GUIElementFactoryList.size(); ++i)
GUIElementFactoryList[i]->drop();
}
void CGUIEnvironment::loadBuiltInFont()
{
io::path filename = "#DefaultFont";
io::IReadFile* file = io::createMemoryReadFile(BuiltInFontData, BuiltInFontDataSize, filename, false);
CGUIFont* font = new CGUIFont(this, filename );
if (!font->load(file))
{
os::Printer::log("Error: Could not load built-in Font. Did you compile without the BMP loader?", ELL_ERROR);
font->drop();
file->drop();
return;
}
SFont f;
f.NamedPath.setPath(filename);
f.Font = font;
Fonts.push_back(f);
file->drop();
}
//! draws all gui elements
void CGUIEnvironment::drawAll()
{
if (Driver)
{
core::dimension2d<s32> dim(Driver->getScreenSize());
if (AbsoluteRect.LowerRightCorner.X != dim.Width ||
AbsoluteRect.LowerRightCorner.Y != dim.Height)
{
// resize gui environment
DesiredRect.LowerRightCorner = dim;
AbsoluteClippingRect = DesiredRect;
AbsoluteRect = DesiredRect;
updateAbsolutePosition();
}
}
// make sure tooltip is always on top
if (ToolTip.Element)
bringToFront(ToolTip.Element);
draw();
OnPostRender ( os::Timer::getTime () );
}
//! sets the focus to an element
bool CGUIEnvironment::setFocus(IGUIElement* element)
{
if (Focus == element)
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
// GUI Environment should not get the focus
if (element == this)
element = 0;
// stop element from being deleted
if (element)
element->grab();
// focus may change or be removed in this call
IGUIElement *currentFocus = 0;
if (Focus)
{
currentFocus = Focus;
currentFocus->grab();
SEvent e;
e.EventType = EET_GUI_EVENT;
e.GUIEvent.Caller = Focus;
e.GUIEvent.Element = element;
e.GUIEvent.EventType = EGET_ELEMENT_FOCUS_LOST;
if (Focus->OnEvent(e))
{
if (element)
element->drop();
currentFocus->drop();
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
currentFocus->drop();
currentFocus = 0;
}
if (element)
{
currentFocus = Focus;
if (currentFocus)
currentFocus->grab();
// send focused event
SEvent e;
e.EventType = EET_GUI_EVENT;
e.GUIEvent.Caller = element;
e.GUIEvent.Element = Focus;
e.GUIEvent.EventType = EGET_ELEMENT_FOCUSED;
if (element->OnEvent(e))
{
if (element)
element->drop();
if (currentFocus)
currentFocus->drop();
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
}
if (currentFocus)
currentFocus->drop();
if (Focus)
Focus->drop();
// element is the new focus so it doesn't have to be dropped
Focus = element;
return true;
}
//! returns the element with the focus
IGUIElement* CGUIEnvironment::getFocus() const
{
return Focus;
}
//! removes the focus from an element
bool CGUIEnvironment::removeFocus(IGUIElement* element)
{
if (Focus && Focus==element)
{
SEvent e;
e.EventType = EET_GUI_EVENT;
e.GUIEvent.Caller = Focus;
e.GUIEvent.Element = 0;
e.GUIEvent.EventType = EGET_ELEMENT_FOCUS_LOST;
if (Focus->OnEvent(e))
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
}
if (Focus)
{
Focus->drop();
Focus = 0;
}
return true;
}
//! Returns if the element has focus
bool CGUIEnvironment::hasFocus(IGUIElement* element) const
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return (element == Focus);
}
//! returns the current video driver
video::IVideoDriver* CGUIEnvironment::getVideoDriver() const
{
return Driver;
}
//! returns the current file system
io::IFileSystem* CGUIEnvironment::getFileSystem() const
{
return FileSystem;
}
//! returns the current file system
IOSOperator* CGUIEnvironment::getOSOperator() const
{
return Operator;
}
//! clear all GUI elements
void CGUIEnvironment::clear()
{
// Remove the focus
if (Focus)
{
Focus->drop();
Focus = 0;
}
if (Hovered && Hovered != this)
{
Hovered->drop();
Hovered = 0;
}
+ if ( HoveredNoSubelement && HoveredNoSubelement != this)
+ {
+ HoveredNoSubelement->drop();
+ HoveredNoSubelement = 0;
+ }
// get the root's children in case the root changes in future
const core::list<IGUIElement*>& children = getRootGUIElement()->getChildren();
while (!children.empty())
(*children.getLast())->remove();
}
//! called by ui if an event happened.
bool CGUIEnvironment::OnEvent(const SEvent& event)
{
bool ret = false;
if (UserReceiver
&& (event.EventType != EET_MOUSE_INPUT_EVENT)
&& (event.EventType != EET_KEY_INPUT_EVENT)
&& (event.EventType != EET_GUI_EVENT || event.GUIEvent.Caller != this))
{
ret = UserReceiver->OnEvent(event);
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return ret;
}
//
void CGUIEnvironment::OnPostRender( u32 time )
{
- // check tooltip
- IGUIElement * hoveredNonSub = Hovered;
- while ( hoveredNonSub && hoveredNonSub->isSubElement() )
- {
- hoveredNonSub = hoveredNonSub->getParent();
- }
-
// launch tooltip
- if ( time - ToolTip.LastTime >= ToolTip.LaunchTime &&
- hoveredNonSub && hoveredNonSub != this &&
- ToolTip.Element == 0 &&
- hoveredNonSub != ToolTip.Element &&
- hoveredNonSub->getToolTipText().size() &&
+ if ( ToolTip.Element == 0 &&
+ HoveredNoSubelement && HoveredNoSubelement != this &&
+ (time - ToolTip.EnterTime >= ToolTip.LaunchTime
+ || (time - ToolTip.LastTime >= ToolTip.RelaunchTime && time - ToolTip.LastTime < ToolTip.LaunchTime)) &&
+ HoveredNoSubelement->getToolTipText().size() &&
getSkin() &&
getSkin()->getFont(EGDF_TOOLTIP)
)
{
core::rect<s32> pos;
pos.UpperLeftCorner = LastHoveredMousePos;
- core::dimension2du dim = getSkin()->getFont(EGDF_TOOLTIP)->getDimension(hoveredNonSub->getToolTipText().c_str());
+ core::dimension2du dim = getSkin()->getFont(EGDF_TOOLTIP)->getDimension(HoveredNoSubelement->getToolTipText().c_str());
dim.Width += getSkin()->getSize(EGDS_TEXT_DISTANCE_X)*2;
dim.Height += getSkin()->getSize(EGDS_TEXT_DISTANCE_Y)*2;
pos.UpperLeftCorner.Y -= dim.Height+1;
pos.LowerRightCorner.Y = pos.UpperLeftCorner.Y + dim.Height-1;
pos.LowerRightCorner.X = pos.UpperLeftCorner.X + dim.Width;
pos.constrainTo(getAbsolutePosition());
- ToolTip.Element = addStaticText(hoveredNonSub->getToolTipText().c_str(), pos, true, true, this, -1, true);
+ ToolTip.Element = addStaticText(HoveredNoSubelement->getToolTipText().c_str(), pos, true, true, this, -1, true);
ToolTip.Element->setOverrideColor(getSkin()->getColor(EGDC_TOOLTIP));
ToolTip.Element->setBackgroundColor(getSkin()->getColor(EGDC_TOOLTIP_BACKGROUND));
ToolTip.Element->setOverrideFont(getSkin()->getFont(EGDF_TOOLTIP));
ToolTip.Element->setSubElement(true);
ToolTip.Element->grab();
s32 textHeight = ToolTip.Element->getTextHeight();
pos = ToolTip.Element->getRelativePosition();
pos.LowerRightCorner.Y = pos.UpperLeftCorner.Y + textHeight;
ToolTip.Element->setRelativePosition(pos);
+ }
+
+ if (ToolTip.Element && ToolTip.Element->isVisible() ) // (isVisible() check only because we might use visibility for ToolTip one day)
+ {
+ ToolTip.LastTime = time;
+ // got invisible or removed in the meantime?
+ if ( !HoveredNoSubelement ||
+ !HoveredNoSubelement->isVisible() ||
+ !HoveredNoSubelement->getParent()
+ ) // got invisible or removed in the meantime?
+ {
+ ToolTip.Element->remove();
+ ToolTip.Element->drop();
+ ToolTip.Element = 0;
+ }
}
IGUIElement::OnPostRender ( time );
}
//
void CGUIEnvironment::updateHoveredElement(core::position2d<s32> mousePos)
{
IGUIElement* lastHovered = Hovered;
+ IGUIElement* lastHoveredNoSubelement = HoveredNoSubelement;
LastHoveredMousePos = mousePos;
Hovered = getElementFromPoint(mousePos);
- if (Hovered)
+ if ( ToolTip.Element && Hovered == ToolTip.Element )
{
- u32 now = os::Timer::getTime();
+ // When the mouse is over the ToolTip we remove that so it will be re-created at a new position.
+ // Note that ToolTip.EnterTime does not get changed here, so it will be re-created at once.
+ ToolTip.Element->remove();
+ ToolTip.Element->drop();
+ ToolTip.Element = 0;
- if (Hovered != this)
- Hovered->grab();
+ // Get the real Hovered
+ Hovered = getElementFromPoint(mousePos);
+ }
- if (Hovered != lastHovered)
- {
- SEvent event;
- event.EventType = EET_GUI_EVENT;
+ // for tooltips we want the element itself and not some of it's subelements
+ HoveredNoSubelement = Hovered;
+ while ( HoveredNoSubelement && HoveredNoSubelement->isSubElement() )
+ {
+ HoveredNoSubelement = HoveredNoSubelement->getParent();
+ }
- if (lastHovered)
- {
- event.GUIEvent.Caller = lastHovered;
- event.GUIEvent.EventType = EGET_ELEMENT_LEFT;
- lastHovered->OnEvent(event);
- }
+ if (Hovered && Hovered != this)
+ Hovered->grab();
+ if ( HoveredNoSubelement && HoveredNoSubelement != this)
+ HoveredNoSubelement->grab();
- if (ToolTip.Element)
- {
- ToolTip.Element->remove();
- ToolTip.Element->drop();
- ToolTip.Element = 0;
- ToolTip.LastTime += 500;
- }
- else
- {
- // boost tooltip generation for relaunch
- if ( now - ToolTip.LastTime < ToolTip.LastTime )
- {
- ToolTip.LastTime += 500;
- }
- else
- {
- ToolTip.LastTime = now;
- }
- }
+ if (Hovered != lastHovered)
+ {
+ SEvent event;
+ event.EventType = EET_GUI_EVENT;
+ if (lastHovered)
+ {
+ event.GUIEvent.Caller = lastHovered;
+ event.GUIEvent.EventType = EGET_ELEMENT_LEFT;
+ lastHovered->OnEvent(event);
+ }
+ if ( Hovered )
+ {
event.GUIEvent.Caller = Hovered;
event.GUIEvent.Element = Hovered;
event.GUIEvent.EventType = EGET_ELEMENT_HOVERED;
Hovered->OnEvent(event);
}
}
+ if ( lastHoveredNoSubelement != HoveredNoSubelement )
+ {
+ if (ToolTip.Element)
+ {
+ ToolTip.Element->remove();
+ ToolTip.Element->drop();
+ ToolTip.Element = 0;
+ }
+
+ if ( HoveredNoSubelement )
+ {
+ u32 now = os::Timer::getTime();
+ ToolTip.EnterTime = now;
+ }
+ }
+
if (lastHovered && lastHovered != this)
lastHovered->drop();
+ if (lastHoveredNoSubelement && lastHoveredNoSubelement != this)
+ lastHoveredNoSubelement->drop();
}
//! This sets a new event receiver for gui events. Usually you do not have to
//! use this method, it is used by the internal engine.
void CGUIEnvironment::setUserEventReceiver(IEventReceiver* evr)
{
UserReceiver = evr;
}
//! posts an input event to the environment
bool CGUIEnvironment::postEventFromUser(const SEvent& event)
{
switch(event.EventType)
{
case EET_GUI_EVENT:
// hey, why is the user sending gui events..?
break;
case EET_MOUSE_INPUT_EVENT:
updateHoveredElement(core::position2d<s32>(event.MouseInput.X, event.MouseInput.Y));
if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
if ( (Hovered && Hovered != Focus) || !Focus )
{
setFocus(Hovered);
}
// sending input to focus
if (Focus && Focus->OnEvent(event))
return true;
// focus could have died in last call
if (!Focus && Hovered)
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return Hovered->OnEvent(event);
}
break;
case EET_KEY_INPUT_EVENT:
{
// send focus changing event
if (event.EventType == EET_KEY_INPUT_EVENT &&
event.KeyInput.PressedDown &&
event.KeyInput.Key == KEY_TAB)
{
IGUIElement *next = getNextElement(event.KeyInput.Shift, event.KeyInput.Control);
if (next && next != Focus)
{
if (setFocus(next))
return true;
}
}
if (Focus)
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return Focus->OnEvent(event);
}
}
break;
default:
break;
} // end switch
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
//! returns the current gui skin
IGUISkin* CGUIEnvironment::getSkin() const
{
return CurrentSkin;
}
//! Sets a new GUI Skin
void CGUIEnvironment::setSkin(IGUISkin* skin)
{
if (CurrentSkin==skin)
return;
if (CurrentSkin)
CurrentSkin->drop();
CurrentSkin = skin;
if (CurrentSkin)
CurrentSkin->grab();
}
//! Creates a new GUI Skin based on a template.
/** \return Returns a pointer to the created skin.
If you no longer need the skin, you should call IGUISkin::drop().
See IReferenceCounted::drop() for more information. */
IGUISkin* CGUIEnvironment::createSkin(EGUI_SKIN_TYPE type)
{
IGUISkin* skin = new CGUISkin(type, Driver);
IGUIFont* builtinfont = getBuiltInFont();
IGUIFontBitmap* bitfont = 0;
if (builtinfont && builtinfont->getType() == EGFT_BITMAP)
bitfont = (IGUIFontBitmap*)builtinfont;
IGUISpriteBank* bank = 0;
skin->setFont(builtinfont);
if (bitfont)
bank = bitfont->getSpriteBank();
skin->setSpriteBank(bank);
return skin;
}
//! Returns the default element factory which can create all built in elements
IGUIElementFactory* CGUIEnvironment::getDefaultGUIElementFactory() const
{
return getGUIElementFactory(0);
}
//! Adds an element factory to the gui environment.
/** Use this to extend the gui environment with new element types which it should be
able to create automaticly, for example when loading data from xml files. */
void CGUIEnvironment::registerGUIElementFactory(IGUIElementFactory* factoryToAdd)
{
if (factoryToAdd)
{
factoryToAdd->grab();
GUIElementFactoryList.push_back(factoryToAdd);
}
}
//! Returns amount of registered scene node factories.
u32 CGUIEnvironment::getRegisteredGUIElementFactoryCount() const
{
return GUIElementFactoryList.size();
}
//! Returns a scene node factory by index
IGUIElementFactory* CGUIEnvironment::getGUIElementFactory(u32 index) const
{
if (index < GUIElementFactoryList.size())
return GUIElementFactoryList[index];
else
return 0;
}
//! adds a GUI Element using its name
IGUIElement* CGUIEnvironment::addGUIElement(const c8* elementName, IGUIElement* parent)
{
IGUIElement* node=0;
if (!parent)
parent = this;
for (u32 i=0; i<GUIElementFactoryList.size() && !node; ++i)
node = GUIElementFactoryList[i]->addGUIElement(elementName, parent);
return node;
}
//! Saves the current gui into a file.
//! \param filename: Name of the file .
bool CGUIEnvironment::saveGUI(const io::path& filename, IGUIElement* start)
{
io::IWriteFile* file = FileSystem->createAndWriteFile(filename);
if (!file)
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
bool ret = saveGUI(file, start);
file->drop();
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return ret;
}
//! Saves the current gui into a file.
bool CGUIEnvironment::saveGUI(io::IWriteFile* file, IGUIElement* start)
{
if (!file)
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
io::IXMLWriter* writer = FileSystem->createXMLWriter(file);
if (!writer)
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
writer->writeXMLHeader();
writeGUIElement(writer, start ? start : this);
writer->drop();
return true;
}
//! Loads the gui. Note that the current gui is not cleared before.
//! \param filename: Name of the file.
bool CGUIEnvironment::loadGUI(const io::path& filename, IGUIElement* parent)
{
io::IReadFile* read = FileSystem->createAndOpenFile(filename);
if (!read)
{
os::Printer::log("Unable to open gui file", filename, ELL_ERROR);
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
bool ret = loadGUI(read, parent);
read->drop();
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return ret;
}
//! Loads the gui. Note that the current gui is not cleared before.
bool CGUIEnvironment::loadGUI(io::IReadFile* file, IGUIElement* parent)
{
if (!file)
{
os::Printer::log("Unable to open GUI file", ELL_ERROR);
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
io::IXMLReader* reader = FileSystem->createXMLReader(file);
if (!reader)
{
os::Printer::log("GUI is not a valid XML file", file->getFileName(), ELL_ERROR);
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
// read file
while(reader->read())
{
readGUIElement(reader, parent);
}
// finish up
reader->drop();
return true;
}
//! reads an element
void CGUIEnvironment::readGUIElement(io::IXMLReader* reader, IGUIElement* node)
{
if (!reader)
return;
io::EXML_NODE nodeType = reader->getNodeType();
if (nodeType == io::EXN_NONE || nodeType == io::EXN_UNKNOWN || nodeType == io::EXN_ELEMENT_END)
return;
if (!wcscmp(IRR_XML_FORMAT_GUI_ENV, reader->getNodeName()))
{
if (!node)
node = this; // root
}
else if (!wcscmp(IRR_XML_FORMAT_GUI_ELEMENT, reader->getNodeName()))
{
// find node type and create it
const core::stringc attrName = reader->getAttributeValue(IRR_XML_FORMAT_GUI_ELEMENT_ATTR_TYPE);
node = addGUIElement(attrName.c_str(), node);
if (!node)
os::Printer::log("Could not create GUI element of unknown type", attrName.c_str());
}
// read attributes
while(reader->read())
{
bool endreached = false;
switch (reader->getNodeType())
{
case io::EXN_ELEMENT_END:
if (!wcscmp(IRR_XML_FORMAT_GUI_ELEMENT, reader->getNodeName()) ||
!wcscmp(IRR_XML_FORMAT_GUI_ENV, reader->getNodeName()))
{
endreached = true;
}
break;
case io::EXN_ELEMENT:
if (!wcscmp(L"attributes", reader->getNodeName()))
{
// read attributes
io::IAttributes* attr = FileSystem->createEmptyAttributes(Driver);
attr->read(reader, true);
if (node)
node->deserializeAttributes(attr);
attr->drop();
}
else
if (!wcscmp(IRR_XML_FORMAT_GUI_ELEMENT, reader->getNodeName()) ||
!wcscmp(IRR_XML_FORMAT_GUI_ENV, reader->getNodeName()))
{
readGUIElement(reader, node);
}
else
{
os::Printer::log("Found unknown element in irrlicht GUI file",
core::stringc(reader->getNodeName()).c_str());
}
break;
default:
break;
}
if (endreached)
break;
}
}
//! writes an element
void CGUIEnvironment::writeGUIElement(io::IXMLWriter* writer, IGUIElement* node)
{
if (!writer || !node )
return;
const wchar_t* name = 0;
// write properties
io::IAttributes* attr = FileSystem->createEmptyAttributes();
node->serializeAttributes(attr);
// all gui elements must have at least one attribute
// if they have nothing then we ignore them.
if (attr->getAttributeCount() != 0)
{
if (node == this)
{
name = IRR_XML_FORMAT_GUI_ENV;
writer->writeElement(name, false);
}
else
{
name = IRR_XML_FORMAT_GUI_ELEMENT;
writer->writeElement(name, false, IRR_XML_FORMAT_GUI_ELEMENT_ATTR_TYPE,
core::stringw(node->getTypeName()).c_str());
}
writer->writeLineBreak();
writer->writeLineBreak();
attr->write(writer);
writer->writeLineBreak();
}
// write children
core::list<IGUIElement*>::ConstIterator it = node->getChildren().begin();
for (; it != node->getChildren().end(); ++it)
{
if (!(*it)->isSubElement())
writeGUIElement(writer, (*it));
}
// write closing brace if required
if (attr->getAttributeCount() != 0)
{
writer->writeClosingTag(name);
writer->writeLineBreak();
writer->writeLineBreak();
}
attr->drop();
}
//! Writes attributes of the environment
void CGUIEnvironment::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const
{
IGUISkin* skin = getSkin();
if (skin)
{
out->addEnum("Skin", getSkin()->getType(), GUISkinTypeNames);
skin->serializeAttributes(out, options);
}
}
//! Reads attributes of the environment
void CGUIEnvironment::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
if (in->existsAttribute("Skin"))
{
IGUISkin *skin = getSkin();
EGUI_SKIN_TYPE t = (EGUI_SKIN_TYPE) in->getAttributeAsEnumeration("Skin",GUISkinTypeNames);
if ( !skin || t != skin->getType())
{
skin = createSkin(t);
setSkin(skin);
skin->drop();
}
skin = getSkin();
if (skin)
{
skin->deserializeAttributes(in, options);
}
}
RelativeRect = AbsoluteRect =
core::rect<s32>(core::position2d<s32>(0,0),
Driver ? core::dimension2di(Driver->getScreenSize()) : core::dimension2d<s32>(0,0));
}
//! adds a button. The returned pointer must not be dropped.
IGUIButton* CGUIEnvironment::addButton(const core::rect<s32>& rectangle, IGUIElement* parent, s32 id, const wchar_t* text, const wchar_t *tooltiptext)
{
IGUIButton* button = new CGUIButton(this, parent ? parent : this, id, rectangle);
if (text)
button->setText(text);
if ( tooltiptext )
button->setToolTipText ( tooltiptext );
button->drop();
return button;
}
//! adds a window. The returned pointer must not be dropped.
IGUIWindow* CGUIEnvironment::addWindow(const core::rect<s32>& rectangle, bool modal,
const wchar_t* text, IGUIElement* parent, s32 id)
{
parent = parent ? parent : this;
IGUIWindow* win = new CGUIWindow(this, parent, id, rectangle);
if (text)
win->setText(text);
win->drop();
if (modal)
{
// Careful, don't just set the modal as parent above. That will mess up the focus (and is hard to change because we have to be very
// careful not to get virtual function call, like OnEvent, in the window.
CGUIModalScreen * modalScreen = new CGUIModalScreen(this, parent, -1);
modalScreen->drop();
modalScreen->addChild(win);
}
return win;
}
//! adds a modal screen. The returned pointer must not be dropped.
IGUIElement* CGUIEnvironment::addModalScreen(IGUIElement* parent)
{
parent = parent ? parent : this;
IGUIElement *win = new CGUIModalScreen(this, parent, -1);
win->drop();
return win;
}
//! Adds a message box.
IGUIWindow* CGUIEnvironment::addMessageBox(const wchar_t* caption, const wchar_t* text,
bool modal, s32 flag, IGUIElement* parent, s32 id, video::ITexture* image)
{
if (!CurrentSkin)
return 0;
parent = parent ? parent : this;
core::rect<s32> rect;
core::dimension2d<u32> screenDim, msgBoxDim;
screenDim.Width = parent->getAbsolutePosition().getWidth();
screenDim.Height = parent->getAbsolutePosition().getHeight();
msgBoxDim.Width = 2;
msgBoxDim.Height = 2;
rect.UpperLeftCorner.X = (screenDim.Width - msgBoxDim.Width) / 2;
rect.UpperLeftCorner.Y = (screenDim.Height - msgBoxDim.Height) / 2;
rect.LowerRightCorner.X = rect.UpperLeftCorner.X + msgBoxDim.Width;
diff --git a/source/Irrlicht/CGUIEnvironment.h b/source/Irrlicht/CGUIEnvironment.h
index 10919a8..16ca8ea 100644
--- a/source/Irrlicht/CGUIEnvironment.h
+++ b/source/Irrlicht/CGUIEnvironment.h
@@ -1,311 +1,314 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_GUI_ENVIRONMENT_H_INCLUDED__
#define __C_GUI_ENVIRONMENT_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include "IGUIEnvironment.h"
#include "IGUIElement.h"
#include "irrArray.h"
#include "IFileSystem.h"
#include "IOSOperator.h"
namespace irr
{
namespace io
{
class IXMLWriter;
}
namespace gui
{
class CGUIEnvironment : public IGUIEnvironment, public IGUIElement
{
public:
//! constructor
CGUIEnvironment(io::IFileSystem* fs, video::IVideoDriver* driver, IOSOperator* op);
//! destructor
virtual ~CGUIEnvironment();
//! draws all gui elements
virtual void drawAll();
//! returns the current video driver
virtual video::IVideoDriver* getVideoDriver() const;
//! returns pointer to the filesystem
virtual io::IFileSystem* getFileSystem() const;
//! returns a pointer to the OS operator
virtual IOSOperator* getOSOperator() const;
//! posts an input event to the environment
virtual bool postEventFromUser(const SEvent& event);
//! This sets a new event receiver for gui events. Usually you do not have to
//! use this method, it is used by the internal engine.
virtual void setUserEventReceiver(IEventReceiver* evr);
//! removes all elements from the environment
virtual void clear();
//! called if an event happened.
virtual bool OnEvent(const SEvent& event);
//! returns the current gui skin
virtual IGUISkin* getSkin() const;
//! Sets a new GUI Skin
virtual void setSkin(IGUISkin* skin);
//! Creates a new GUI Skin based on a template.
/** \return Returns a pointer to the created skin.
If you no longer need the skin, you should call IGUISkin::drop().
See IReferenceCounted::drop() for more information. */
virtual IGUISkin* createSkin(EGUI_SKIN_TYPE type);
//! Creates the image list from the given texture.
virtual IGUIImageList* createImageList( video::ITexture* texture,
core::dimension2d<s32> imageSize, bool useAlphaChannel );
//! returns the font
virtual IGUIFont* getFont(const io::path& filename);
//! add an externally loaded font
virtual IGUIFont* addFont(const io::path& name, IGUIFont* font);
//! returns default font
virtual IGUIFont* getBuiltInFont() const;
//! returns the sprite bank
virtual IGUISpriteBank* getSpriteBank(const io::path& filename);
//! returns the sprite bank
virtual IGUISpriteBank* addEmptySpriteBank(const io::path& name);
//! adds an button. The returned pointer must not be dropped.
virtual IGUIButton* addButton(const core::rect<s32>& rectangle, IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0,const wchar_t* tooltiptext = 0);
//! adds a window. The returned pointer must not be dropped.
virtual IGUIWindow* addWindow(const core::rect<s32>& rectangle, bool modal = false,
const wchar_t* text=0, IGUIElement* parent=0, s32 id=-1);
//! adds a modal screen. The returned pointer must not be dropped.
virtual IGUIElement* addModalScreen(IGUIElement* parent);
//! Adds a message box.
virtual IGUIWindow* addMessageBox(const wchar_t* caption, const wchar_t* text=0,
bool modal = true, s32 flag = EMBF_OK, IGUIElement* parent=0, s32 id=-1, video::ITexture* image=0);
//! adds a scrollbar. The returned pointer must not be dropped.
virtual IGUIScrollBar* addScrollBar(bool horizontal, const core::rect<s32>& rectangle,
IGUIElement* parent=0, s32 id=-1);
//! Adds an image element.
virtual IGUIImage* addImage(video::ITexture* image, core::position2d<s32> pos,
bool useAlphaChannel=true, IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0);
//! adds an image. The returned pointer must not be dropped.
virtual IGUIImage* addImage(const core::rect<s32>& rectangle,
IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0);
//! adds a checkbox
virtual IGUICheckBox* addCheckBox(bool checked, const core::rect<s32>& rectangle, IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0);
//! adds a list box
virtual IGUIListBox* addListBox(const core::rect<s32>& rectangle,
IGUIElement* parent=0, s32 id=-1, bool drawBackground=false);
//! adds a tree view
virtual IGUITreeView* addTreeView(const core::rect<s32>& rectangle,
IGUIElement* parent=0, s32 id=-1, bool drawBackground=false,
bool scrollBarVertical = true, bool scrollBarHorizontal = false);
//! adds an mesh viewer. The returned pointer must not be dropped.
virtual IGUIMeshViewer* addMeshViewer(const core::rect<s32>& rectangle, IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0);
//! Adds a file open dialog.
virtual IGUIFileOpenDialog* addFileOpenDialog(const wchar_t* title = 0, bool modal=true, IGUIElement* parent=0, s32 id=-1);
//! Adds a color select dialog.
virtual IGUIColorSelectDialog* addColorSelectDialog(const wchar_t* title = 0, bool modal=true, IGUIElement* parent=0, s32 id=-1);
//! adds a static text. The returned pointer must not be dropped.
virtual IGUIStaticText* addStaticText(const wchar_t* text, const core::rect<s32>& rectangle,
bool border=false, bool wordWrap=true, IGUIElement* parent=0, s32 id=-1, bool drawBackground = false);
//! Adds an edit box. The returned pointer must not be dropped.
virtual IGUIEditBox* addEditBox(const wchar_t* text, const core::rect<s32>& rectangle,
bool border=false, IGUIElement* parent=0, s32 id=-1);
//! Adds a spin box to the environment
virtual IGUISpinBox* addSpinBox(const wchar_t* text, const core::rect<s32>& rectangle,
bool border=false,IGUIElement* parent=0, s32 id=-1);
//! Adds a tab control to the environment.
virtual IGUITabControl* addTabControl(const core::rect<s32>& rectangle,
IGUIElement* parent=0, bool fillbackground=false, bool border=true, s32 id=-1);
//! Adds tab to the environment.
virtual IGUITab* addTab(const core::rect<s32>& rectangle,
IGUIElement* parent=0, s32 id=-1);
//! Adds a context menu to the environment.
virtual IGUIContextMenu* addContextMenu(const core::rect<s32>& rectangle,
IGUIElement* parent=0, s32 id=-1);
//! Adds a menu to the environment.
virtual IGUIContextMenu* addMenu(IGUIElement* parent=0, s32 id=-1);
//! Adds a toolbar to the environment. It is like a menu is always placed on top
//! in its parent, and contains buttons.
virtual IGUIToolBar* addToolBar(IGUIElement* parent=0, s32 id=-1);
//! Adds a combo box to the environment.
virtual IGUIComboBox* addComboBox(const core::rect<s32>& rectangle,
IGUIElement* parent=0, s32 id=-1);
//! Adds a table element.
virtual IGUITable* addTable(const core::rect<s32>& rectangle,
IGUIElement* parent=0, s32 id=-1, bool drawBackground=false);
//! sets the focus to an element
virtual bool setFocus(IGUIElement* element);
//! removes the focus from an element
virtual bool removeFocus(IGUIElement* element);
//! Returns if the element has focus
virtual bool hasFocus(IGUIElement* element) const;
//! Returns the element with the focus
virtual IGUIElement* getFocus() const;
//! Adds an element for fading in or out.
virtual IGUIInOutFader* addInOutFader(const core::rect<s32>* rectangle=0, IGUIElement* parent=0, s32 id=-1);
//! Returns the root gui element.
virtual IGUIElement* getRootGUIElement();
virtual void OnPostRender( u32 time );
//! Returns the default element factory which can create all built in elements
virtual IGUIElementFactory* getDefaultGUIElementFactory() const;
//! Adds an element factory to the gui environment.
/** Use this to extend the gui environment with new element types which it should be
able to create automaticly, for example when loading data from xml files. */
virtual void registerGUIElementFactory(IGUIElementFactory* factoryToAdd);
//! Returns amount of registered scene node factories.
virtual u32 getRegisteredGUIElementFactoryCount() const;
//! Returns a scene node factory by index
virtual IGUIElementFactory* getGUIElementFactory(u32 index) const;
//! Adds a GUI Element by its name
virtual IGUIElement* addGUIElement(const c8* elementName, IGUIElement* parent=0);
//! Saves the current gui into a file.
/** \param filename: Name of the file.
\param start: The element to start saving from.
if not specified, the root element will be used */
virtual bool saveGUI( const io::path& filename, IGUIElement* start=0);
//! Saves the current gui into a file.
/** \param file: The file to save the GUI to.
\param start: The element to start saving from.
if not specified, the root element will be used */
virtual bool saveGUI(io::IWriteFile* file, IGUIElement* start=0);
//! Loads the gui. Note that the current gui is not cleared before.
/** \param filename: Name of the file.
\param parent: The parent of all loaded GUI elements,
if not specified, the root element will be used */
virtual bool loadGUI(const io::path& filename, IGUIElement* parent=0);
//! Loads the gui. Note that the current gui is not cleared before.
/** \param file: IReadFile to load the GUI from
\param parent: The parent of all loaded GUI elements,
if not specified, the root element will be used */
virtual bool loadGUI(io::IReadFile* file, IGUIElement* parent=0);
//! Writes attributes of the environment
virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const;
//! Reads attributes of the environment.
virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0);
//! writes an element
virtual void writeGUIElement(io::IXMLWriter* writer, IGUIElement* node);
//! reads an element
virtual void readGUIElement(io::IXMLReader* reader, IGUIElement* node);
private:
IGUIElement* getNextElement(bool reverse=false, bool group=false);
void updateHoveredElement(core::position2d<s32> mousePos);
void loadBuiltInFont();
struct SFont
{
io::SNamedPath NamedPath;
IGUIFont* Font;
bool operator < (const SFont& other) const
{
return (NamedPath < other.NamedPath);
}
};
struct SSpriteBank
{
io::SNamedPath NamedPath;
IGUISpriteBank* Bank;
bool operator < (const SSpriteBank& other) const
{
return (NamedPath < other.NamedPath);
}
};
struct SToolTip
{
IGUIStaticText* Element;
u32 LastTime;
+ u32 EnterTime;
u32 LaunchTime;
+ u32 RelaunchTime;
};
SToolTip ToolTip;
core::array<IGUIElementFactory*> GUIElementFactoryList;
core::array<SFont> Fonts;
core::array<SSpriteBank> Banks;
video::IVideoDriver* Driver;
IGUIElement* Hovered;
+ IGUIElement* HoveredNoSubelement; // subelements replaced by their parent, so you only have 'real' elements here
IGUIElement* Focus;
core::position2d<s32> LastHoveredMousePos;
IGUISkin* CurrentSkin;
io::IFileSystem* FileSystem;
IEventReceiver* UserReceiver;
IOSOperator* Operator;
};
} // end namespace gui
} // end namespace irr
#endif // _IRR_COMPILE_WITH_GUI_
#endif // __C_GUI_ENVIRONMENT_H_INCLUDED__
|
paupawsan/Irrlicht
|
72bd759594b6314dce1cb748cdd125e66ebd833d
|
Fix reading of empty pass elements in Ogre materials.
|
diff --git a/source/Irrlicht/COgreMeshFileLoader.cpp b/source/Irrlicht/COgreMeshFileLoader.cpp
index 540308b..96c8064 100644
--- a/source/Irrlicht/COgreMeshFileLoader.cpp
+++ b/source/Irrlicht/COgreMeshFileLoader.cpp
@@ -417,1024 +417,1026 @@ bool COgreMeshFileLoader::readSubMesh(io::IReadFile* file, ChunkData& parent, Og
break;
case COGRE_SUBMESH_TEXTURE_ALIAS:
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Submesh Texture Alias");
#endif
core::stringc texture, alias;
readString(file, data, texture);
readString(file, data, alias);
subMesh.TextureAliases.push_back(OgreTextureAlias(texture,alias));
}
break;
case COGRE_SUBMESH_BONE_ASSIGNMENT:
{
subMesh.BoneAssignments.push_back(OgreBoneAssignment());
readInt(file, data, &subMesh.BoneAssignments.getLast().VertexID);
readShort(file, data, &subMesh.BoneAssignments.getLast().BoneID);
readFloat(file, data, &subMesh.BoneAssignments.getLast().Weight);
}
break;
default:
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Skipping", core::stringc(data.header.id));
#endif
parent.read=parent.header.length;
file->seek(-(long)sizeof(ChunkHeader), true);
return true;
}
parent.read += data.read;
}
return true;
}
void COgreMeshFileLoader::composeMeshBufferMaterial(scene::IMeshBuffer* mb, const core::stringc& materialName)
{
video::SMaterial& material=mb->getMaterial();
for (u32 k=0; k<Materials.size(); ++k)
{
if ((materialName==Materials[k].Name)&&(Materials[k].Techniques.size())&&(Materials[k].Techniques[0].Passes.size()))
{
material=Materials[k].Techniques[0].Passes[0].Material;
if (Materials[k].Techniques[0].Passes[0].Texture.Filename.size())
{
if (FileSystem->existFile(Materials[k].Techniques[0].Passes[0].Texture.Filename))
material.setTexture(0, Driver->getTexture(Materials[k].Techniques[0].Passes[0].Texture.Filename));
else
material.setTexture(0, Driver->getTexture((CurrentlyLoadingFromPath+"/"+FileSystem->getFileBasename(Materials[k].Techniques[0].Passes[0].Texture.Filename))));
}
break;
}
}
}
scene::SMeshBuffer* COgreMeshFileLoader::composeMeshBuffer(const core::array<s32>& indices, const OgreGeometry& geom)
{
scene::SMeshBuffer *mb=new scene::SMeshBuffer();
u32 i;
mb->Indices.set_used(indices.size());
for (i=0; i<indices.size(); ++i)
mb->Indices[i]=indices[i];
mb->Vertices.set_used(geom.NumVertex);
for (i=0; i<geom.Elements.size(); ++i)
{
if (geom.Elements[i].Semantic==1) //Pos
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->Vertices[k].Color=mb->Material.DiffuseColor;
mb->Vertices[k].Pos.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]);
ePos += eSize;
}
}
}
}
if (geom.Elements[i].Semantic==4) //Normal
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->Vertices[k].Normal.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]);
ePos += eSize;
}
}
}
}
if (geom.Elements[i].Semantic==7) //TexCoord
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->Vertices[k].TCoords.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1]);
ePos += eSize;
}
}
}
}
}
return mb;
}
scene::SMeshBufferLightMap* COgreMeshFileLoader::composeMeshBufferLightMap(const core::array<s32>& indices, const OgreGeometry& geom)
{
scene::SMeshBufferLightMap *mb=new scene::SMeshBufferLightMap();
u32 i;
mb->Indices.set_used(indices.size());
for (i=0; i<indices.size(); ++i)
mb->Indices[i]=indices[i];
mb->Vertices.set_used(geom.NumVertex);
for (i=0; i<geom.Elements.size(); ++i)
{
if (geom.Elements[i].Semantic==1) //Pos
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->Vertices[k].Color=mb->Material.DiffuseColor;
mb->Vertices[k].Pos.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]);
ePos += eSize;
}
}
}
}
if (geom.Elements[i].Semantic==4) //Normal
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->Vertices[k].Normal.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]);
ePos += eSize;
}
}
}
}
if (geom.Elements[i].Semantic==7) //TexCoord
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->Vertices[k].TCoords.set(geom.Buffers[j].Data[ePos], geom.Buffers[j].Data[ePos+1]);
mb->Vertices[k].TCoords2.set(geom.Buffers[j].Data[ePos+2], geom.Buffers[j].Data[ePos+3]);
ePos += eSize;
}
}
}
}
}
return mb;
}
scene::IMeshBuffer* COgreMeshFileLoader::composeMeshBufferSkinned(scene::CSkinnedMesh& mesh, const core::array<s32>& indices, const OgreGeometry& geom)
{
scene::SSkinMeshBuffer *mb=mesh.addMeshBuffer();
if (NumUV>1)
{
mb->convertTo2TCoords();
mb->Vertices_2TCoords.set_used(geom.NumVertex);
}
else
mb->Vertices_Standard.set_used(geom.NumVertex);
u32 i;
mb->Indices.set_used(indices.size());
for (i=0; i<indices.size(); i+=3)
{
mb->Indices[i+0]=indices[i+2];
mb->Indices[i+1]=indices[i+1];
mb->Indices[i+2]=indices[i+0];
}
for (i=0; i<geom.Elements.size(); ++i)
{
if (geom.Elements[i].Semantic==1) //Pos
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
if (NumUV>1)
mb->Vertices_2TCoords[k].Color=mb->Material.DiffuseColor;
else
mb->Vertices_Standard[k].Color=mb->Material.DiffuseColor;
mb->getPosition(k).set(-geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]);
ePos += eSize;
}
}
}
}
if (geom.Elements[i].Semantic==4) //Normal
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->getNormal(k).set(-geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]);
ePos += eSize;
}
}
}
}
if (geom.Elements[i].Semantic==7) //TexCoord
{
for (u32 j=0; j<geom.Buffers.size(); ++j)
{
if (geom.Elements[i].Source==geom.Buffers[j].BindIndex)
{
u32 eSize=geom.Buffers[j].VertexSize;
u32 ePos=geom.Elements[i].Offset;
for (s32 k=0; k<geom.NumVertex; ++k)
{
mb->getTCoords(k).set(geom.Buffers[j].Data[ePos], geom.Buffers[j].Data[ePos+1]);
if (NumUV>1)
mb->Vertices_2TCoords[k].TCoords2.set(geom.Buffers[j].Data[ePos+2], geom.Buffers[j].Data[ePos+3]);
ePos += eSize;
}
}
}
}
}
return mb;
}
void COgreMeshFileLoader::composeObject(void)
{
for (u32 i=0; i<Meshes.size(); ++i)
{
for (u32 j=0; j<Meshes[i].SubMeshes.size(); ++j)
{
IMeshBuffer* mb;
if (Meshes[i].SubMeshes[j].SharedVertices)
{
if (Skeleton.Bones.size())
{
mb = composeMeshBufferSkinned(*(CSkinnedMesh*)Mesh, Meshes[i].SubMeshes[j].Indices, Meshes[i].Geometry);
}
else if (NumUV < 2)
{
mb = composeMeshBuffer(Meshes[i].SubMeshes[j].Indices, Meshes[i].Geometry);
}
else
{
mb = composeMeshBufferLightMap(Meshes[i].SubMeshes[j].Indices, Meshes[i].Geometry);
}
}
else
{
if (Skeleton.Bones.size())
{
mb = composeMeshBufferSkinned(*(CSkinnedMesh*)Mesh, Meshes[i].SubMeshes[j].Indices, Meshes[i].SubMeshes[j].Geometry);
}
else if (NumUV < 2)
{
mb = composeMeshBuffer(Meshes[i].SubMeshes[j].Indices, Meshes[i].SubMeshes[j].Geometry);
}
else
{
mb = composeMeshBufferLightMap(Meshes[i].SubMeshes[j].Indices, Meshes[i].SubMeshes[j].Geometry);
}
}
if (mb != 0)
{
composeMeshBufferMaterial(mb, Meshes[i].SubMeshes[j].Material);
if (!Skeleton.Bones.size())
{
((SMesh*)Mesh)->addMeshBuffer(mb);
mb->drop();
}
}
}
}
if (Skeleton.Bones.size())
{
CSkinnedMesh* m = (CSkinnedMesh*)Mesh;
// Create Joints
for (u32 i=0; i<Skeleton.Bones.size(); ++i)
{
ISkinnedMesh::SJoint* joint = m->addJoint();
joint->Name=Skeleton.Bones[i].Name;
joint->LocalMatrix = Skeleton.Bones[i].Orientation.getMatrix();
if (Skeleton.Bones[i].Scale != core::vector3df(1,1,1))
{
core::matrix4 scaleMatrix;
scaleMatrix.setScale( Skeleton.Bones[i].Scale );
joint->LocalMatrix *= scaleMatrix;
}
joint->LocalMatrix.setTranslation( Skeleton.Bones[i].Position );
}
// Joints hierarchy
for (u32 i=0; i<Skeleton.Bones.size(); ++i)
{
if (Skeleton.Bones[i].Parent<m->getJointCount())
{
m->getAllJoints()[Skeleton.Bones[i].Parent]->Children.push_back(m->getAllJoints()[Skeleton.Bones[i].Handle]);
}
}
// Weights
u32 bufCount=0;
for (u32 i=0; i<Meshes.size(); ++i)
{
for (u32 j=0; j<Meshes[i].SubMeshes.size(); ++j)
{
for (u32 k=0; k<Meshes[i].SubMeshes[j].BoneAssignments.size(); ++k)
{
OgreBoneAssignment& ba = Meshes[i].SubMeshes[j].BoneAssignments[k];
ISkinnedMesh::SWeight* w = m->addWeight(m->getAllJoints()[ba.BoneID]);
w->strength=ba.Weight;
w->vertex_id=ba.VertexID;
w->buffer_id=bufCount;
}
++bufCount;
}
}
for (u32 i=0; i<Skeleton.Animations.size(); ++i)
{
for (u32 j=0; j<Skeleton.Animations[i].Keyframes.size(); ++j)
{
OgreKeyframe& frame = Skeleton.Animations[i].Keyframes[j];
ISkinnedMesh::SJoint* keyjoint = m->getAllJoints()[frame.BoneID];
ISkinnedMesh::SPositionKey* poskey = m->addPositionKey(keyjoint);
poskey->frame=frame.Time*25;
poskey->position=keyjoint->LocalMatrix.getTranslation()+frame.Position;
ISkinnedMesh::SRotationKey* rotkey = m->addRotationKey(keyjoint);
rotkey->frame=frame.Time*25;
rotkey->rotation=core::quaternion(keyjoint->LocalMatrix)*frame.Orientation;
ISkinnedMesh::SScaleKey* scalekey = m->addScaleKey(keyjoint);
scalekey->frame=frame.Time*25;
scalekey->scale=frame.Scale;
}
}
m->finalize();
}
}
void COgreMeshFileLoader::getMaterialToken(io::IReadFile* file, core::stringc& token, bool noNewLine)
{
bool parseString=false;
c8 c=0;
token = "";
if (file->getPos() >= file->getSize())
return;
file->read(&c, sizeof(c8));
// search for word beginning
while ( core::isspace(c) && (file->getPos() < file->getSize()))
{
if (noNewLine && c=='\n')
{
file->seek(-1, true);
return;
}
file->read(&c, sizeof(c8));
}
// check if we read a string
if (c=='"')
{
parseString = true;
file->read(&c, sizeof(c8));
}
do
{
if (c=='/')
{
file->read(&c, sizeof(c8));
// check for comments, cannot be part of strings
if (!parseString && (c=='/'))
{
// skip comments
while(c!='\n')
file->read(&c, sizeof(c8));
if (!token.size())
{
// if we start with a comment we need to skip
// following whitespaces, so restart
getMaterialToken(file, token, noNewLine);
return;
}
else
{
// else continue with next character
file->read(&c, sizeof(c8));
continue;
}
}
else
{
// else append first slash and check if second char
// ends this token
token.append('/');
if ((!parseString && core::isspace(c)) ||
(parseString && (c=='"')))
return;
}
}
token.append(c);
file->read(&c, sizeof(c8));
// read until a token delimiter is found
}
while (((!parseString && !core::isspace(c)) || (parseString && (c!='"'))) &&
(file->getPos() < file->getSize()));
// we want to skip the last quotes of a string , but other chars might be the next
// token already.
if (!parseString)
file->seek(-1, true);
}
bool COgreMeshFileLoader::readColor(io::IReadFile* file, video::SColor& col)
{
core::stringc token;
getMaterialToken(file, token);
if (token!="vertexcolour")
{
video::SColorf col_f;
col_f.r=core::fast_atof(token.c_str());
getMaterialToken(file, token);
col_f.g=core::fast_atof(token.c_str());
getMaterialToken(file, token);
col_f.b=core::fast_atof(token.c_str());
getMaterialToken(file, token, true);
if (token.size())
col_f.a=core::fast_atof(token.c_str());
else
col_f.a=1.0f;
if ((col_f.r==0.0f)&&(col_f.g==0.0f)&&(col_f.b==0.0f))
col.set(255,255,255,255);
else
col=col_f.toSColor();
return false;
}
return true;
}
void COgreMeshFileLoader::readPass(io::IReadFile* file, OgreTechnique& technique)
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Pass");
#endif
core::stringc token;
technique.Passes.push_back(OgrePass());
OgrePass& pass=technique.Passes.getLast();
getMaterialToken(file, token); //open brace or name
if (token != "{")
getMaterialToken(file, token); //open brace
getMaterialToken(file, token);
+ if (token == "}")
+ return;
u32 inBlocks=1;
u32 textureUnit=0;
while(inBlocks)
{
if (token=="ambient")
pass.AmbientTokenColor=readColor(file, pass.Material.AmbientColor);
else if (token=="diffuse")
pass.DiffuseTokenColor=readColor(file, pass.Material.DiffuseColor);
else if (token=="specular")
{
pass.SpecularTokenColor=readColor(file, pass.Material.SpecularColor);
getMaterialToken(file, token);
pass.Material.Shininess=core::fast_atof(token.c_str());
}
else if (token=="emissive")
pass.EmissiveTokenColor=readColor(file, pass.Material.EmissiveColor);
else if (token=="scene_blend")
{ // TODO: Choose correct values
getMaterialToken(file, token);
if (token=="add")
pass.Material.MaterialType=video::EMT_TRANSPARENT_ADD_COLOR;
else if (token=="modulate")
pass.Material.MaterialType=video::EMT_SOLID;
else if (token=="alpha_blend")
pass.Material.MaterialType=video::EMT_TRANSPARENT_ALPHA_CHANNEL;
else if (token=="colour_blend")
pass.Material.MaterialType=video::EMT_TRANSPARENT_VERTEX_ALPHA;
else
getMaterialToken(file, token);
}
else if (token=="depth_check")
{
getMaterialToken(file, token);
if (token!="on")
pass.Material.ZBuffer=video::ECFN_NEVER;
}
else if (token=="depth_write")
{
getMaterialToken(file, token);
pass.Material.ZWriteEnable=(token=="on");
}
else if (token=="depth_func")
{
getMaterialToken(file, token); // Function name
if (token=="always_fail")
pass.Material.ZBuffer=video::ECFN_NEVER;
else if (token=="always_pass")
pass.Material.ZBuffer=video::ECFN_ALWAYS;
else if (token=="equal")
pass.Material.ZBuffer=video::ECFN_EQUAL;
else if (token=="greater")
pass.Material.ZBuffer=video::ECFN_GREATER;
else if (token=="greater_equal")
pass.Material.ZBuffer=video::ECFN_GREATEREQUAL;
else if (token=="less")
pass.Material.ZBuffer=video::ECFN_LESS;
else if (token=="less_equal")
pass.Material.ZBuffer=video::ECFN_LESSEQUAL;
else if (token=="not_equal")
pass.Material.ZBuffer=video::ECFN_NOTEQUAL;
}
else if (token=="normalise_normals")
{
getMaterialToken(file, token);
pass.Material.NormalizeNormals=(token=="on");
}
else if (token=="depth_bias")
{
getMaterialToken(file, token); // bias value
}
else if (token=="alpha_rejection")
{
getMaterialToken(file, token); // function name
getMaterialToken(file, token); // value
pass.Material.MaterialTypeParam=core::fast_atof(token.c_str());
}
else if (token=="alpha_to_coverage")
{
getMaterialToken(file, token);
if (token=="on")
pass.Material.AntiAliasing |= video::EAAM_ALPHA_TO_COVERAGE;
}
else if (token=="colour_write")
{
getMaterialToken(file, token);
pass.Material.ColorMask = (token=="on")?video::ECP_ALL:video::ECP_NONE;
}
else if (token=="cull_hardware")
{
getMaterialToken(file, token); // rotation name
}
else if (token=="cull_software")
{
getMaterialToken(file, token); // culling side
}
else if (token=="lighting")
{
getMaterialToken(file, token);
pass.Material.Lighting=(token=="on");
}
else if (token=="shading")
{
getMaterialToken(file, token);
// We take phong as gouraud
pass.Material.GouraudShading=(token!="flat");
}
else if (token=="polygon_mode")
{
getMaterialToken(file, token);
pass.Material.Wireframe=(token=="wireframe");
pass.Material.PointCloud=(token=="points");
}
else if (token=="max_lights")
{
getMaterialToken(file, token);
pass.MaxLights=strtol(token.c_str(),NULL,10);
}
else if (token=="point_size")
{
getMaterialToken(file, token);
pass.PointSize=core::fast_atof(token.c_str());
}
else if (token=="point_sprites")
{
getMaterialToken(file, token);
pass.PointSprites=(token=="on");
}
else if (token=="point_size_min")
{
getMaterialToken(file, token);
pass.PointSizeMin=strtol(token.c_str(),NULL,10);
}
else if (token=="point_size_max")
{
getMaterialToken(file, token);
pass.PointSizeMax=strtol(token.c_str(),NULL,10);
}
else if (token=="texture_unit")
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Texture unit");
#endif
getMaterialToken(file, token); //open brace
getMaterialToken(file, token);
while(token != "}")
{
if (token=="texture")
{
getMaterialToken(file, pass.Texture.Filename);
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Texture", pass.Texture.Filename.c_str());
#endif
getMaterialToken(file, pass.Texture.CoordsType, true);
getMaterialToken(file, pass.Texture.MipMaps, true);
getMaterialToken(file, pass.Texture.Alpha, true);
}
else if (token=="filtering")
{
getMaterialToken(file, token);
pass.Material.TextureLayer[textureUnit].AnisotropicFilter=0;
if (token=="point")
{
pass.Material.TextureLayer[textureUnit].BilinearFilter=false;
pass.Material.TextureLayer[textureUnit].TrilinearFilter=false;
getMaterialToken(file, token);
getMaterialToken(file, token);
}
else if (token=="linear")
{
getMaterialToken(file, token);
if (token=="point")
{
pass.Material.TextureLayer[textureUnit].BilinearFilter=false;
pass.Material.TextureLayer[textureUnit].TrilinearFilter=false;
getMaterialToken(file, token);
}
else
{
pass.Material.TextureLayer[textureUnit].BilinearFilter=true;
getMaterialToken(file, token);
pass.Material.TextureLayer[textureUnit].TrilinearFilter=(token=="linear");
}
}
else
{
pass.Material.TextureLayer[textureUnit].BilinearFilter=(token=="bilinear");
pass.Material.TextureLayer[textureUnit].TrilinearFilter=(token=="trilinear");
pass.Material.TextureLayer[textureUnit].AnisotropicFilter=(token=="anisotropic")?2:1;
}
}
else if (token=="max_anisotropy")
{
getMaterialToken(file, token);
pass.Material.TextureLayer[textureUnit].AnisotropicFilter=(u8)core::strtol10(token.c_str());
}
else if (token=="texture_alias")
{
getMaterialToken(file, pass.Texture.Alias);
}
else if (token=="mipmap_bias")
{
getMaterialToken(file, token);
pass.Material.TextureLayer[textureUnit].LODBias=(s8)core::fast_atof(token.c_str());
}
else if (token=="colour_op")
{ // TODO: Choose correct values
getMaterialToken(file, token);
if (token=="add")
pass.Material.MaterialType=video::EMT_TRANSPARENT_ADD_COLOR;
else if (token=="modulate")
pass.Material.MaterialType=video::EMT_SOLID;
else if (token=="alpha_blend")
pass.Material.MaterialType=video::EMT_TRANSPARENT_ALPHA_CHANNEL;
else if (token=="colour_blend")
pass.Material.MaterialType=video::EMT_TRANSPARENT_VERTEX_ALPHA;
else
getMaterialToken(file, token);
}
getMaterialToken(file, token);
}
++textureUnit;
}
else if (token=="shadow_caster_program_ref")
{
do
{
getMaterialToken(file, token);
} while (token != "}");
}
else if (token=="shadow_caster_vertex_program_ref")
{
do
{
getMaterialToken(file, token);
} while (token != "}");
}
else if (token=="vertex_program_ref")
{
do
{
getMaterialToken(file, token);
} while (token != "}");
}
//fog_override, iteration, point_size_attenuation
//not considered yet!
getMaterialToken(file, token);
if (token=="{")
++inBlocks;
else if (token=="}")
--inBlocks;
}
}
void COgreMeshFileLoader::readTechnique(io::IReadFile* file, OgreMaterial& mat)
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Read Technique");
#endif
core::stringc token;
mat.Techniques.push_back(OgreTechnique());
OgreTechnique& technique=mat.Techniques.getLast();
getMaterialToken(file, technique.Name); //open brace or name
if (technique.Name != "{")
getMaterialToken(file, token); //open brace
else
technique.Name=core::stringc((int)mat.Techniques.size());
getMaterialToken(file, token);
while (token != "}")
{
if (token == "pass")
readPass(file, technique);
else if (token == "scheme")
getMaterialToken(file, token);
else if (token == "lod_index")
getMaterialToken(file, token);
getMaterialToken(file, token);
}
}
void COgreMeshFileLoader::loadMaterials(io::IReadFile* meshFile)
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Load Materials");
#endif
core::stringc token;
io::IReadFile* file = 0;
io::path filename = FileSystem->getFileBasename(meshFile->getFileName(), false) + ".material";
if (FileSystem->existFile(filename))
file = FileSystem->createAndOpenFile(filename);
else
file = FileSystem->createAndOpenFile(FileSystem->getFileDir(meshFile->getFileName())+"/"+filename);
if (!file)
{
os::Printer::log("Could not load OGRE material", filename);
return;
}
getMaterialToken(file, token);
while (file->getPos() < file->getSize())
{
if ((token == "fragment_program") || (token == "vertex_program"))
{
// skip whole block
u32 blocks=1;
do
{
getMaterialToken(file, token);
} while (token != "{");
do
{
getMaterialToken(file, token);
if (token == "{")
++blocks;
else if (token == "}")
--blocks;
} while (blocks);
getMaterialToken(file, token);
continue;
}
if (token != "material")
{
if (token.trim().size())
os::Printer::log("Unknown material group", token.c_str());
break;
}
Materials.push_back(OgreMaterial());
OgreMaterial& mat = Materials.getLast();
getMaterialToken(file, mat.Name);
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Load Material", mat.Name.c_str());
#endif
getMaterialToken(file, token); //open brace
getMaterialToken(file, token);
while(token != "}")
{
if (token=="lod_distances") // can have several items
getMaterialToken(file, token);
else if (token=="receive_shadows")
{
getMaterialToken(file, token);
mat.ReceiveShadows=(token=="on");
}
else if (token=="transparency_casts_shadows")
{
getMaterialToken(file, token);
mat.TransparencyCastsShadows=(token=="on");
}
else if (token=="set_texture_alias")
{
getMaterialToken(file, token);
getMaterialToken(file, token);
}
else if (token=="technique")
readTechnique(file, mat);
getMaterialToken(file, token);
}
getMaterialToken(file, token);
}
file->drop();
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Finished loading Materials");
#endif
}
bool COgreMeshFileLoader::loadSkeleton(io::IReadFile* meshFile, const core::stringc& name)
{
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Load Skeleton", name);
#endif
io::IReadFile* file = 0;
io::path filename;
if (FileSystem->existFile(name))
file = FileSystem->createAndOpenFile(name);
else if (FileSystem->existFile(filename = FileSystem->getFileDir(meshFile->getFileName())+"/"+name))
file = FileSystem->createAndOpenFile(filename);
else if (FileSystem->existFile(filename = FileSystem->getFileBasename(meshFile->getFileName(), false) + ".skeleton"))
file = FileSystem->createAndOpenFile(filename);
else
file = FileSystem->createAndOpenFile(FileSystem->getFileDir(meshFile->getFileName())+"/"+filename);
if (!file)
{
os::Printer::log("Could not load matching skeleton", name);
return false;
}
s16 id;
file->read(&id, 2);
if (SwapEndian)
id = os::Byteswap::byteswap(id);
if (id != COGRE_HEADER)
{
file->drop();
return false;
}
core::stringc skeletonVersion;
ChunkData head;
readString(file, head, skeletonVersion);
if (skeletonVersion != "[Serializer_v1.10]")
{
file->drop();
return false;
}
u16 bone=0;
f32 animationTotal=0.f;
while(file->getPos() < file->getSize())
{
ChunkData data;
readChunkData(file, data);
switch(data.header.id)
{
case COGRE_SKELETON:
{
Skeleton.Bones.push_back(OgreBone());
OgreBone& bone = Skeleton.Bones.getLast();
readString(file, data, bone.Name);
readShort(file, data, &bone.Handle);
readVector(file, data, bone.Position);
readQuaternion(file, data, bone.Orientation);
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Bone", bone.Name+" ("+core::stringc(bone.Handle)+")");
os::Printer::log("Position", core::stringc(bone.Position.X)+" "+core::stringc(bone.Position.Y)+" "+core::stringc(bone.Position.Z));
os::Printer::log("Rotation quat", core::stringc(bone.Orientation.W)+" "+core::stringc(bone.Orientation.X)+" "+core::stringc(bone.Orientation.Y)+" "+core::stringc(bone.Orientation.Z));
// core::vector3df rot;
// bone.Orientation.toEuler(rot);
// rot *= core::RADTODEG;
// os::Printer::log("Rotation", core::stringc(rot.X)+" "+core::stringc(rot.Y)+" "+core::stringc(rot.Z));
#endif
if (data.read<(data.header.length-bone.Name.size()))
{
readVector(file, data, bone.Scale);
bone.Scale.X *= -1.f;
}
else
bone.Scale=core::vector3df(1,1,1);
bone.Parent=0xffff;
}
break;
case COGRE_BONE_PARENT:
{
u16 parent;
readShort(file, data, &bone);
readShort(file, data, &parent);
if (bone<Skeleton.Bones.size() && parent<Skeleton.Bones.size())
Skeleton.Bones[bone].Parent=parent;
}
break;
case COGRE_ANIMATION:
{
if (Skeleton.Animations.size())
animationTotal+=Skeleton.Animations.getLast().Length;
Skeleton.Animations.push_back(OgreAnimation());
OgreAnimation& anim = Skeleton.Animations.getLast();
readString(file, data, anim.Name);
readFloat(file, data, &anim.Length);
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Animation", anim.Name);
os::Printer::log("Length", core::stringc(anim.Length));
#endif
}
break;
case COGRE_ANIMATION_TRACK:
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("for Bone ", core::stringc(bone));
#endif
readShort(file, data, &bone); // store current bone
break;
case COGRE_ANIMATION_KEYFRAME:
{
Skeleton.Animations.getLast().Keyframes.push_back(OgreKeyframe());
OgreKeyframe& keyframe = Skeleton.Animations.getLast().Keyframes.getLast();
readFloat(file, data, &keyframe.Time);
keyframe.Time+=animationTotal;
readQuaternion(file, data, keyframe.Orientation);
readVector(file, data, keyframe.Position);
if (data.read<data.header.length)
{
readVector(file, data, keyframe.Scale);
keyframe.Scale.X *= -1.f;
}
else
keyframe.Scale=core::vector3df(1,1,1);
keyframe.BoneID=bone;
}
break;
case COGRE_ANIMATION_LINK:
#ifdef IRR_OGRE_LOADER_DEBUG
os::Printer::log("Animation link");
#endif
break;
default:
break;
}
}
file->drop();
return true;
}
void COgreMeshFileLoader::readChunkData(io::IReadFile* file, ChunkData& data)
|
paupawsan/Irrlicht
|
c042701b028b49d4f5597d5d2ff956e88ba4aa6e
|
Fix bug (endless loop) in string::remove with empty strings found by Ulf.
|
diff --git a/changes.txt b/changes.txt
index 5e9e193..1638cec 100644
--- a/changes.txt
+++ b/changes.txt
@@ -1,512 +1,518 @@
+----------------
+Changes in 1.7.1
+
+ - Fix string::remove which got in an endless loop when remove was called with an empty string (found and fixed by Ulf)
+
+----------------
Changes in 1.7
- Implement minimize and deminimize under OSX.
- Define sorting order for vector2d and vector3d in operators <, <=, > and >= to fix bugs 2783509 and 2783510. Operators order now by X,Y,Z and use float tolerances.
- Ogre mesh 32bit indices fixed.
- Fix tooltips for gui-elements with sub-element like IGUISpinBox (id: 2927079, found by ArakisTheKitsune)
- ITimer no longer stops when started twice
- wchar_t filesystem updates under Windows.
- Joystick POV fixed under Windows, ids fixed under OSX.
- Some updates to skinned mesh for better bones support and scaling animations.
- OSX supports external window id in creation parameters now.
- Fix bbox collision tests.
- Updates for win32 key handling
- new convenience method for flat plane creation.
- Sky dome and other meshes use VBOs by default now.
- Speed up b3d loading for files with many frames, material color flags and vertex color support enhanced.
- Add hasType to IGUIElement as a dynamic_cast substitute.
- Add another parameter to IGUISkin::draw3DWindowBackground to allow getting the client area without actually drawing
- Add function getClientRect to IGUIWindow for getting the draw-able area
- Fix bug that menus on IGUIWindows with titlebar got drawn too high (id: 2714400)
- Renamed OctTree to Octree
- Allow getting a ConstIterator from a non-const core:list
- Add swap functions to irrMath and to the core classes.
- Deprecate map::isEmpty() and replace it with map::empty() to make it similar to other base classes.
- Allow to set the logging level already in SIrrlichtCreationParameters.
- Add clearSystemMessages to devices (implemented only for Linux and Win32 so far).
- Support changing the render window from beginScene also with OpenGL driver.
- Add getMaterial2D which allows to alter the 2d render state settings, such as filtering, anti-aliasing, thickness, etc.
- Fix incorrect cursorpos for resizable windows on Windows Vista (found and patched by buffer)
- Change the beginScene window parameter from void* to SExposedVideoData&. This will allow to manage contexts for OpenGL at some point.
- Add bzip2 and LZMA decompression modes for zip loader.
- Add OBJ_TEXTURE_PATH and B3D_TEXTURE_PATH to SceneParameters to allow setting texture-paths for obj and b3d.
- Irrlicht keeps now filenames additionally to the internally used names, thereby fixing some problems with uppercase-filenames on Linux.
- Bugfix: Mousewheel no longer sends EMIE_MOUSE_WHEEL messages twice on Linux.
- Use latest jpeglib
- refactoring: E_ATTRIBUTE_TYPE and IAttribute have now own headers
- CStringWArrayAttribute speedup
- SceneNodeAnimatorFollowSpline can now loop and pingpong
- Meshviewer.example got some fast-scale buttons.
- Support AES-encrypted zip files. Should work with 128, 196, and 256 bit AES. This addition also adds a new PRNG, SHA, and other algorithms to the engine, though no interface is yet added for them. The implementation of the encryption algorithms is provided by Dr Brian Gladman.
- flattenFilename and getAbsolutePath fixed and properly added at several places.
- Added geometry shaders for OpenGL. A first version of the code was submitted by Matthew Kielan (devsh).
- Bugfix: irrArray should no longer crash when using other allocators.
- Add MaterialViewer example.
- Texture activation now back in setMaterial, which simplifies writing external material renderers (OpenGL only).
- Checkbox uses now disabled text color when disabled.
- Changed colors for window-title caption to keep them readable when not active.
- Draw sub-menus to left side if they would be outside main-window otherwise.
- Give ListBox better defaults for the ScrollBar stepsizes.
- Double and triple click events now for each mouse-button. Old events for that got removed.
- Fix adding archives twice, which caused multiple archives of the same name and type covering each other. This one required a texture name change from using backslashes to slashes under Windows.
- Give access to texture mipmaps. You can provide custom mipmap textures upon generation, regeneration, and locking.
Make sure the provided data is large enough and covers all miplevels. Also the returned pointer (from lock) will only cover the smaller data of the mipmap level dimension chosen (level 0 is the original texture).
- Separate TextureWrap mode into U and V fields
- Add mirror texture wrap modes
- windows show now active/inactive state
- remove unneeded drop/grab calls found by manik_sheeri
- fix rounding problem in IGUIElements which have EGUIA_SCALE alignments.
- MessageBox supports now automatic resizing and images.
Deprecated EGDS_MESSAGE_BOX_WIDTH and EGDS_MESSAGE_BOX_HEIGHT
- Let maya-cam animator react on a setTarget call to the camera which happened outside it's own control
- New contextmenue features:
automatic checking for checked flag.
close handling now customizable
serialization can handle incomplete xml's
setEventParent now in public interface
New function findItemWithCommandId
New function insertItem
- new vector3d::getSphericalCoordinateAngles method.
- new triangle3d::isTotalOutsideBox method.
- Newly introduced VertexManipulator interface. This allows for very easy creation of vertex manipulation algorithms. Several manipulators, e.g. vertex color changer and transformation algorithms are already available.
- createMeshWith1TCoords avoids vertex duplication
- getRotation now handles matrices with scaling as well
- Ogre format animations now supported.
- irrArray: Fixed issues with push_front and reallocation
Changed behavior for set_pointer and clear, when free_when_destroyed is false
- NPK (Nebula device archive) reader added, it's an uncompressed PAK-like format
- SSkinMeshBuffer::MoveTo* methods renamed to convertTo*
- Multiple Render Target (MRT) support added, including some enhanced blend features where supported
- Directory changing fixed for virtual file systems (Archives etc)
- Fix texture matrix init in scene manager and driver
- More draw2dimage support in software drivers
- Sphere node now properly chooses a good tesselation based on the parameters
- Active camera not registered twice anymore
- Parallax/normal map shader rotation bug under OpenGL fixed
- bump map handling for obj files fixed
- Fog serialization added
- New context menu features added
- Bounding Box updates for skinned meshes fixed
- The current FPS for an animated scene node can be queried now, added some variables to serialization
- Scrollbars fixed
- Fixed 2d vertex primitive method to correctly handle transparency
- Fullscreen handling has been enhanced for Windows, now proper resolution is restored on Alt-Tab etc.
- Cameras can now be added to the scene node without automatically activating them
Clone method added
- New video driver method getMaxTextureSize
- PAK archive reader fixed
- TRANSPARENT_ALPHA_CHANNEL_REF uses modulate to enable lighting
- LIGHTMAP_ADD now always uses add operator
- Some Unicode file system fixes
- destructor of irrString not virtual anymore, please don't derive from irrString
Some new methods added, for searching and splitting
Assignment operator optimized
- new lightness method for SColor
- draw3DTriangle now renders filled polygons, old behavior can be achieved by setting EMT_WIREFRAME
----------------
Changes in 1.6.1
- Fix pingpong for CSceneNodeAnimatorFlyStraight (found by gbox)
- Fix bug with IGUIEditBox where the cursor position is reset on text change.
- Make sure the window top-left corner on Windows is not negative on start so that Windows sytem-menu is always visible.
- Fix problem that the window did sometimes not get the keyboard focus in X11 in fullscreen. Add more debug output in case focus grabbing goes wrong.
- Fix screensize in videodriver when we didn't get the requested window size. This also prevents that gui-clicks are no longer synchronized with gui-drawing and elements can't be hit anymore.
- Bugfix: Prevent a crash when getTypeName was called for the guienvironment. EGUIET_ELEMENT got changed for this.
- Bugfix: Horizontal centered font with linebreaks draw now all lines. For example multiline TextSceneNodes work again.
- Bugfix: spinbox can no longer get in an endless loop due to floating point rounding error (found by slavik262)
- !!API change!! Disabled AntiAliasing of Lines in material default
Please enable this manually per material when sure that it won't lead to SW rendering.
- IGUIComboBox: clicking on the statictext displaying the active selection does now close and open listbox correctly. (Bug found by Reiko)
- Scrollbuttons in IGUITabControl adapt now to tab-height.
- Fix texturing of cylinder mesh
- Fix modal dialog position (found by LoneBoco: http://sourceforge.net/tracker/?func=detail&aid=2900266&group_id=74339&atid=540676)
- Fix DMF loading
- Fixing left+right special keys (ctrl, shift, alt) on Win32 (thanks to pc0de for good patch-ideas).
- Make stringarrays for enums in IGUISkin a little safer
- Add support for keys KEY_PRINT, KEY_HOME (on numpad) and KEY_NUMLOCK on Linux.
- Fix material handling in createMeshWith1TCoords
- Fix another (OldValue == NewValue) before drop()/grap(), this time in CTextureAttribute::setTexture.
- Fix LIGHTMAP_LIGHTING for D3D drivers.
- AntiAliasing disabled for debug render elements.
- Bugfix: CGUIToolBar::addButton does no longer mess up when no image is set and does now actually work with the text.
- Fix ninja animation range which got messed up a little when b3d animations got fixed (thx gbox for finding)
---------------------------
Changes in 1.6 (23.09.2009)
- Added IFileSystem::createEmptyFileList, exposed IFileList::sort, addItem and added getID
- Fix MAKE_IRR_ID so it can be used from outside the irr namespace (Micha's patch)
- Renamed some methods in ISkinnedMesh to match the official Irrlicht naming scheme according to createXXX()
- Change debug data to draw using lines instead of arrows, which is much faster. Patch by pc0de
- Fix a bug with FPS camera animator causing stutters. Patch by FuzzYspo0N
- Fix scrolling controls in CGUITabControl
- Fix a bug when getting optimal texture size in D3D drivers, by Jetro Lauha (tonic)
- Added EGDS_TITLEBARTEXT_DISTANCE_X and EGDS_TITLEBARTEXT_DISTANCE_Y to GUI, submitted by FuzzYspo0N
- Fix for UFT8 filenames displayed in file dialog, patch by MadHyde.
- Added const method for array::binary_search, potentially slow as it doesn't sort the list!
- Add support for scaling button images.
- Irrlicht can now come with multiple device types compiled in, the device to use is selected by SIrrlichtCreationParameters.DeviceType. This defaults to EIDT_BEST which automatically select the best device available starting with native, then X11, SDL and finally the console.
- Added support for EXP2 fog distribution. This required a change in the setFog parameters where now an enum value instead of the bool linear is given.
- IFileSystem changes:
- Renamed the following functions-
IFileArchive::getArchiveType to getType
IFileSystem::registerFileArchive to addFileArchive
IFileSystem::unregisterFileArchive to removeFileArchive
IFileArchive::openFile to createAndOpenFile
- New enum, E_FILE_ARCHIVE_TYPE. getType on IArchiveLoader and IFileArchive now both return this.
- IFileSystem::addFileArchive takes a parameter to specify the archive type rather always using the file extension. IFileSystem::addZipFileArchive, addFolderFileArchive and addPakFileArchive now use this but these functions are now marked as deprecated. Users should now use addFileArchive instead.
- Added TAR archive loader.
- The ZIP archive loader can now load gzip files, combined with the TAR loader this means Irrlicht now has native support for .tar.gz
Currently this must be done in two calls, for example:
fileSystem->addFileArchive("path/to/myArchive.tar.gz");
fileSystem->addFileArchive("myArchive.tar");
- Fix highlighting in IGUIEditBox where kerning pairs are used in the font. For example in future italic, OS or other custom fonts.
- IOSOperator::getTextFromClipboard returns now const c8* instead of c8*
- Support for copy&paste on linux (X11) added (fixing bug 2804014 found by Pan)
- bugfix for 2795321 found by egrath: Don't rely anymore on broken XkbSetDetectableAutoRepeat.
- bugfix: CMountPointReader::openFile no longer returns true for empty files. Corresponding test added.
- Direct3D now also uses screen coordinates in 2d mode, just like OpenGL. This means that screen coords are going from 0..ScreenWidth and 0..ScreenHeight instead of -1..1.
- ALT+F4 keypress now closes Windows SDL device
- Allow Direct3D drivers in SDL, patch by Halifax
- Added compiler error when attempting to compile with VC6.
- Use setWindowTextA in Windows device for WIN64 platform, posted by veegun
- ELL_ERROR log events are now created when shaders fail to compile or link, reported by Halan
- irrList now uses irrAllocator, fixed by Nox
- Added IGUIWindow::setDraggable and IGUIWindow::isDraggable, by Nox
- Added SGI RGB file reader by Gary Conway, for loading Silicon Graphics .rgb, .rgba, .sgi, .int and .inta textures
- Renamed setResizeAble to setResizable
- Added new device method minimizeWindow which minimizes the window (just as if the minimize button has been clicked).
- SkyDome is now serialized correctly
- Added PLY mesh reader and writer
- Ensure ListBox on combo box doesn't hang off the bottom of the GUI root, by Matthias Specht
- Made IGUIElements recalculate clipping rectangle after setNotClipped, reported by Aelis440
- Bug fix for the combo box where it showed white text instead of skin colour before being focused, fix posted by drewbacca
- EGDS_MESSAGE_BOX_HEIGHT is now honoured, bug reported by Spkka
- Fixed a bug in the edit box where events are sometimes sent to a null parent, reported by Sudi.
- Coordinate system fix for OpenGL in SDL device
- Added generic console device. You can now use Irrlicht to create and manipuate graphics on a shell where no graphics hardware
or windowing system is available. To enable it uncomment #define _IRR_USE_CONSOLE_DEVICE_ in IrrCompileConfig.h
- The console device can now present images from the software drivers and display them as ASCII art in the console
- By default it replaces the default font in the skin, to prevent fonts from being huge.
- Fixed problems with changing cursor visibility while mouse is pressed on windows
- Allow control of background drawing in listbox
- Allow control of drawing background and titlebar in windows
- Improved window serialization
- Add mouse events EMIE_MOUSE_DOUBLE_CLICK and EMIE_MOUSE_TRIPLE_CLICK (thx to Ulf for patch proposal)
- Set "ButtonStates" for mouse events also on Linux (was only for Windows formerly)
- Add Shift+Control states to mouse event
- bugfix (2003238): serialize modal screens
- allow stacking modal screens
- allowing hiding modals
- replace many IsVisible checks with virtual isVisible() checks in IGUIElement
- bugfix: reset selected row when clearing CGUITable
- adding events EGET_EDITBOX_CHANGED and EGET_EDITBOX_MARKING_CHANGED
- prevent editbox from recalculating its textbreaking each frame
- let spinbox react on each textchange without waiting for enter to prevent getting value changes without corresponding EGET_SPINBOX_CHANGED events.
- new test for zipreader
- prevent dropping objects accidentally in many set functions
- Reversed change in vector3d::normalize.
Works now again as documented and a corresponding test has been added.
Does fix bug 2770709 (https://sourceforge.net/tracker/?func=detail&aid=2770709&group_id=74339&atid=540676)
- Animations can now be paused by setting the fps to 0.
- Avoid fp-precision problem in getPickedNodeBB (see also http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=33838&highlight=).
This change might also fix the problem with picking nodes found by aanderse (http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=32890&highlight=)
- implemented isALoadableFileFormat ( File *file ) for the Archive Loader
- PixelBlend16 and PixelBlend16_simd are working for the new rules.
- bugfix. CLightSceneNode didn't correctly update it's attributes
- vector template and equals tests
also set the equal test for s32 to behave like the f32 routine.
The function equals always implements a weak test.
that means a tolerance MUST always be used if you use the equal function. default is 1.
- VideoDriver drawPixel
The HW renderes are using the alpha components for blending.
The Software Renderes and image loaders are using CImage::setPixel copy.
so setPixel is engaged to either blends or copy the pixel
default: false
- Burningvideo
added RenderMaterial EMT_SPHERE_MAP
pushed burningsvideo to 0.43
added RenderMaterial EMT_REFLECTION_2_LAYER
pushed burningsvideo to 0.44
set EMT_TRANSPARENT_ALPHA_CHANNEL_REF
to use AlphaRef 0.5 like Direct3D
One Note: in OpenGL there is know difference between sphere_map and reflection layer
both using GL_TEXTURE_GEN_MODE GL_SPHERE_MAP, whereas in d3d one time using camera_normal
on sphere and reflection on refletcion_layer.
The visual difference is that on sphere map the "image is not moving" when you rotate the
viewer. For Burning i took the opengl visual. always moving
- rename quake3 SEntity to IEntity to be confom with IShader
- fixed createMeshWith2TCoords, normals were missing during copy.
- added
//! Creates a copy of the mesh, which will only consist of S3DVertex vertices.
IMesh* CMeshManipulator::createMeshWith1TCoords(IMesh* mesh) const
- added io::IFileSystem* CSceneManager::getFileSystem()
- added virtual const c8* ISceneManager::getAnimatorTypeName(ESCENE_NODE_ANIMATOR_TYPE type);
- added CSceneNodeAnimatorFlyCircle::radiusEllipsoid.
if radiusEllipsoid == 0 the default circle animation is done
else radiusEllipsoid forms the b-axe of the ellipsoid.
-> gummiball bouncing
- added ISceneManager::createFlyStraightAnimator variable bool ping-pong
used in loop mode to device if start from beginning ( default ) or make ping-pong
-> straight bouncing
- changed IFileSystem::registerFileArchive
remove the index of the hierarchy and added a new interface method
//! move the hirarchy of the filesystem. moves sourceIndex relative up or down
virtual bool moveFileArchive( u32 sourceIndex, s32 relative ) = 0;
- bugfix and changes in SViewFrustum::SViewFrustum
wrong size of Matrices copy.
renamed E_TRANSFORMATION_STATE_2 to E_TRANSFORMATION_STATE_FRUSTUM
therefore also changed SViewFrustum::setTransformState to not tap
in the pitfall again of wrong memory...
- moved
//! EMT_ONETEXTURE_BLEND: has BlendFactor Alphablending
inline bool textureBlendFunc_hasAlpha ( E_BLEND_FACTOR factor ) const
from the material renderes ( 3x declared ) to SMaterial.h
- updated managed light example to use standard driver selection
- BurningsVideo
- LightModel reworked.
Point Light & Direction Light works for Diffuse Color as expected
Specular and Fog still have problems ( needs new pixel shader )
pushed burningsvideo to 0.42 for this major step
- removed obsolete matrix transformations
renamed E_TRANSFORMATION_STATE_2 to E_TRANSFORMATION_STATE_BURNING
- cleaned line3d.h vector3d.h template behavior.
many mixed f32/f64 implementations are here. i'm not sure if this should be
the default behavior to use f64 for example for 1.0/x value, because they
benefit from more precisions, but in my point of view the user is responsible
of choosing a vector3d<f32> or vector3d<f64>.
- added core::squareroot to irrmath.h
-> for having candidates for faster math in the same file
- added AllowZWriteOnTransparent from SceneManager to burningsvideo
-added hasAlpha() to ITexture
This info can be used for e.q to downgrade a transparent alpha channel blit
to add if the texture has no alpha channel.
- FileSystem 2.0 SUPER MASTER MAJOR API CHANGE !!!
The FileSystem is now build internally like for e.g. the image- and meshloaders.
There exists a known list of ArchiveLoaders, which know how to produce a Archive.
The Loaders and the Archives can be attached/detached on runtime.
The FileNames are now stored as core::string<c16>. where c16 is toggled between char/wchar
with the #define flag _IRR_WCHAR_FILESYSTEM, to supported unicode backends (default:off)
Replaced most (const c8* filename) to string references.
Basically the FileSystem is divided into two regions. Native and Virtual.
Native means using the backend OS.
Virtual means only use currently attached IArchives.
Browsing
each FileSystem has it's own workdirectory and it's own methods to
- create a FileTree
- add/remove files & directory ( to be done )
Hint: store a savegame in a zip archive...
basic browsing for all archives is implemented.
Example 21. Quake3Explorer shows this
TODO:
- a file filter should be implemented.
- The IArchive should have a function to create a filetree
for now CFileList is used.
diff --git a/include/irrString.h b/include/irrString.h
index de8e213..ebf84dd 100644
--- a/include/irrString.h
+++ b/include/irrString.h
@@ -407,718 +407,720 @@ public:
/** \return pointer to C-style NUL terminated string. */
const T* c_str() const
{
return array;
}
//! Makes the string lower case.
void make_lower()
{
for (u32 i=0; i<used; ++i)
array[i] = locale_lower ( array[i] );
}
//! Makes the string upper case.
void make_upper()
{
for (u32 i=0; i<used; ++i)
array[i] = locale_upper ( array[i] );
}
//! Compares the strings ignoring case.
/** \param other: Other string to compare.
\return True if the strings are equal ignoring case. */
bool equals_ignore_case(const string<T,TAlloc>& other) const
{
for(u32 i=0; array[i] && other[i]; ++i)
if (locale_lower( array[i]) != locale_lower(other[i]))
return false;
return used == other.used;
}
//! Compares the strings ignoring case.
/** \param other: Other string to compare.
\param sourcePos: where to start to compare in the string
\return True if the strings are equal ignoring case. */
bool equals_substring_ignore_case(const string<T,TAlloc>&other, const s32 sourcePos = 0 ) const
{
if ( (u32) sourcePos > used )
return false;
u32 i;
for( i=0; array[sourcePos + i] && other[i]; ++i)
if (locale_lower( array[sourcePos + i]) != locale_lower(other[i]))
return false;
return array[sourcePos + i] == 0 && other[i] == 0;
}
//! Compares the strings ignoring case.
/** \param other: Other string to compare.
\return True if this string is smaller ignoring case. */
bool lower_ignore_case(const string<T,TAlloc>& other) const
{
for(u32 i=0; array[i] && other.array[i]; ++i)
{
s32 diff = (s32) locale_lower ( array[i] ) - (s32) locale_lower ( other.array[i] );
if ( diff )
return diff < 0;
}
return used < other.used;
}
//! compares the first n characters of the strings
/** \param other Other string to compare.
\param n Number of characters to compare
\return True if the n first characters of both strings are equal. */
bool equalsn(const string<T,TAlloc>& other, u32 n) const
{
u32 i;
for(i=0; array[i] && other[i] && i < n; ++i)
if (array[i] != other[i])
return false;
// if one (or both) of the strings was smaller then they
// are only equal if they have the same length
return (i == n) || (used == other.used);
}
//! compares the first n characters of the strings
/** \param str Other string to compare.
\param n Number of characters to compare
\return True if the n first characters of both strings are equal. */
bool equalsn(const T* const str, u32 n) const
{
if (!str)
return false;
u32 i;
for(i=0; array[i] && str[i] && i < n; ++i)
if (array[i] != str[i])
return false;
// if one (or both) of the strings was smaller then they
// are only equal if they have the same length
return (i == n) || (array[i] == 0 && str[i] == 0);
}
//! Appends a character to this string
/** \param character: Character to append. */
void append(T character)
{
if (used + 1 > allocated)
reallocate(used + 1);
++used;
array[used-2] = character;
array[used-1] = 0;
}
//! Appends a char string to this string
/** \param other: Char string to append. */
void append(const T* const other)
{
if (!other)
return;
u32 len = 0;
const T* p = other;
while(*p)
{
++len;
++p;
}
if (used + len > allocated)
reallocate(used + len);
--used;
++len;
for (u32 l=0; l<len; ++l)
array[l+used] = *(other+l);
used += len;
}
//! Appends a string to this string
/** \param other: String to append. */
void append(const string<T,TAlloc>& other)
{
--used;
u32 len = other.size()+1;
if (used + len > allocated)
reallocate(used + len);
for (u32 l=0; l<len; ++l)
array[used+l] = other[l];
used += len;
}
//! Appends a string of the length l to this string.
/** \param other: other String to append to this string.
\param length: How much characters of the other string to add to this one. */
void append(const string<T,TAlloc>& other, u32 length)
{
if (other.size() < length)
{
append(other);
return;
}
if (used + length > allocated)
reallocate(used + length);
--used;
for (u32 l=0; l<length; ++l)
array[l+used] = other[l];
used += length;
// ensure proper termination
array[used]=0;
++used;
}
//! Reserves some memory.
/** \param count: Amount of characters to reserve. */
void reserve(u32 count)
{
if (count < allocated)
return;
reallocate(count);
}
//! finds first occurrence of character in string
/** \param c: Character to search for.
\return Position where the character has been found,
or -1 if not found. */
s32 findFirst(T c) const
{
for (u32 i=0; i<used; ++i)
if (array[i] == c)
return i;
return -1;
}
//! finds first occurrence of a character of a list in string
/** \param c: List of characters to find. For example if the method
should find the first occurrence of 'a' or 'b', this parameter should be "ab".
\param count: Amount of characters in the list. Usually,
this should be strlen(c)
\return Position where one of the characters has been found,
or -1 if not found. */
s32 findFirstChar(const T* const c, u32 count) const
{
if (!c)
return -1;
for (u32 i=0; i<used; ++i)
for (u32 j=0; j<count; ++j)
if (array[i] == c[j])
return i;
return -1;
}
//! Finds first position of a character not in a given list.
/** \param c: List of characters not to find. For example if the method
should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab".
\param count: Amount of characters in the list. Usually,
this should be strlen(c)
\return Position where the character has been found,
or -1 if not found. */
template <class B>
s32 findFirstCharNotInList(const B* const c, u32 count) const
{
for (u32 i=0; i<used-1; ++i)
{
u32 j;
for (j=0; j<count; ++j)
if (array[i] == c[j])
break;
if (j==count)
return i;
}
return -1;
}
//! Finds last position of a character not in a given list.
/** \param c: List of characters not to find. For example if the method
should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab".
\param count: Amount of characters in the list. Usually,
this should be strlen(c)
\return Position where the character has been found,
or -1 if not found. */
template <class B>
s32 findLastCharNotInList(const B* const c, u32 count) const
{
for (s32 i=(s32)(used-2); i>=0; --i)
{
u32 j;
for (j=0; j<count; ++j)
if (array[i] == c[j])
break;
if (j==count)
return i;
}
return -1;
}
//! finds next occurrence of character in string
/** \param c: Character to search for.
\param startPos: Position in string to start searching.
\return Position where the character has been found,
or -1 if not found. */
s32 findNext(T c, u32 startPos) const
{
for (u32 i=startPos; i<used; ++i)
if (array[i] == c)
return i;
return -1;
}
//! finds last occurrence of character in string
/** \param c: Character to search for.
\param start: start to search reverse ( default = -1, on end )
\return Position where the character has been found,
or -1 if not found. */
s32 findLast(T c, s32 start = -1) const
{
start = core::clamp ( start < 0 ? (s32)(used) - 1 : start, 0, (s32)(used) - 1 );
for (s32 i=start; i>=0; --i)
if (array[i] == c)
return i;
return -1;
}
//! finds last occurrence of a character of a list in string
/** \param c: List of strings to find. For example if the method
should find the last occurrence of 'a' or 'b', this parameter should be "ab".
\param count: Amount of characters in the list. Usually,
this should be strlen(c)
\return Position where one of the characters has been found,
or -1 if not found. */
s32 findLastChar(const T* const c, u32 count) const
{
if (!c)
return -1;
for (s32 i=used-1; i>=0; --i)
for (u32 j=0; j<count; ++j)
if (array[i] == c[j])
return i;
return -1;
}
//! finds another string in this string
/** \param str: Another string
\param start: Start position of the search
\return Positions where the string has been found,
or -1 if not found. */
template <class B>
s32 find(const B* const str, const u32 start = 0) const
{
if (str && *str)
{
u32 len = 0;
while (str[len])
++len;
if (len > used-1)
return -1;
for (u32 i=start; i<used-len; ++i)
{
u32 j=0;
while(str[j] && array[i+j] == str[j])
++j;
if (!str[j])
return i;
}
}
return -1;
}
//! Returns a substring
/** \param begin: Start of substring.
\param length: Length of substring. */
string<T,TAlloc> subString(u32 begin, s32 length) const
{
// if start after string
// or no proper substring length
if ((length <= 0) || (begin>=size()))
return string<T,TAlloc>("");
// clamp length to maximal value
if ((length+begin) > size())
length = size()-begin;
string<T,TAlloc> o;
o.reserve(length+1);
for (s32 i=0; i<length; ++i)
o.array[i] = array[i+begin];
o.array[length] = 0;
o.used = o.allocated;
return o;
}
//! Appends a character to this string
/** \param c Character to append. */
string<T,TAlloc>& operator += (T c)
{
append(c);
return *this;
}
//! Appends a char string to this string
/** \param c Char string to append. */
string<T,TAlloc>& operator += (const T* const c)
{
append(c);
return *this;
}
//! Appends a string to this string
/** \param other String to append. */
string<T,TAlloc>& operator += (const string<T,TAlloc>& other)
{
append(other);
return *this;
}
//! Appends a string representation of a number to this string
/** \param i Number to append. */
string<T,TAlloc>& operator += (const int i)
{
append(string<T,TAlloc>(i));
return *this;
}
//! Appends a string representation of a number to this string
/** \param i Number to append. */
string<T,TAlloc>& operator += (const unsigned int i)
{
append(string<T,TAlloc>(i));
return *this;
}
//! Appends a string representation of a number to this string
/** \param i Number to append. */
string<T,TAlloc>& operator += (const long i)
{
append(string<T,TAlloc>(i));
return *this;
}
//! Appends a string representation of a number to this string
/** \param i Number to append. */
string<T,TAlloc>& operator += (const unsigned long& i)
{
append(string<T,TAlloc>(i));
return *this;
}
//! Appends a string representation of a number to this string
/** \param i Number to append. */
string<T,TAlloc>& operator += (const double i)
{
append(string<T,TAlloc>(i));
return *this;
}
//! Appends a string representation of a number to this string
/** \param i Number to append. */
string<T,TAlloc>& operator += (const float i)
{
append(string<T,TAlloc>(i));
return *this;
}
//! Replaces all characters of a special type with another one
/** \param toReplace Character to replace.
\param replaceWith Character replacing the old one. */
void replace(T toReplace, T replaceWith)
{
for (u32 i=0; i<used; ++i)
if (array[i] == toReplace)
array[i] = replaceWith;
}
//! Removes characters from a string.
/** \param c: Character to remove. */
void remove(T c)
{
u32 pos = 0;
u32 found = 0;
for (u32 i=0; i<used; ++i)
{
if (array[i] == c)
{
++found;
continue;
}
array[pos++] = array[i];
}
used -= found;
array[used] = 0;
}
//! Removes a string from the string.
/** \param toRemove: String to remove. */
void remove(const string<T,TAlloc> toRemove)
{
u32 size = toRemove.size();
+ if ( size == 0 )
+ return;
u32 pos = 0;
u32 found = 0;
for (u32 i=0; i<used; ++i)
{
u32 j = 0;
while (j < size)
{
if (array[i + j] != toRemove[j])
break;
++j;
}
if (j == size)
{
found += size;
i += size - 1;
continue;
}
array[pos++] = array[i];
}
used -= found;
array[used] = 0;
}
//! Removes characters from a string.
/** \param characters: Characters to remove. */
void removeChars(const string<T,TAlloc> & characters)
{
u32 pos = 0;
u32 found = 0;
for (u32 i=0; i<used; ++i)
{
// Don't use characters.findFirst as it finds the \0,
// causing used to become incorrect.
bool docontinue = false;
for (u32 j=0; j<characters.size(); ++j)
{
if (characters[j] == array[i])
{
++found;
docontinue = true;
break;
}
}
if (docontinue)
continue;
array[pos++] = array[i];
}
used -= found;
array[used] = 0;
}
//! Trims the string.
/** Removes the specified characters (by default, Latin-1 whitespace)
from the begining and the end of the string. */
string<T,TAlloc>& trim(const string<T,TAlloc> & whitespace = " \t\n\r")
{
// find start and end of the substring without the specified characters
const s32 begin = findFirstCharNotInList(whitespace.c_str(), whitespace.used);
if (begin == -1)
return (*this="");
const s32 end = findLastCharNotInList(whitespace.c_str(), whitespace.used);
return (*this = subString(begin, (end +1) - begin));
}
//! Erases a character from the string.
/** May be slow, because all elements
following after the erased element have to be copied.
\param index: Index of element to be erased. */
void erase(u32 index)
{
_IRR_DEBUG_BREAK_IF(index>=used) // access violation
for (u32 i=index+1; i<used; ++i)
array[i-1] = array[i];
--used;
}
//! verify the existing string.
void validate()
{
// terminate on existing null
for (u32 i=0; i<allocated; ++i)
{
if (array[i] == 0)
{
used = i + 1;
return;
}
}
// terminate
if ( allocated > 0 )
{
used = allocated - 1;
array[used] = 0;
}
else
{
used = 0;
}
}
//! gets the last char of a string or null
T lastChar() const
{
return used > 1 ? array[used-2] : 0;
}
//! split string into parts.
/** This method will split a string at certain delimiter characters
into the container passed in as reference. The type of the container
has to be given as template parameter. It must provide a push_back and
a size method.
\param ret The result container
\param c C-style string of delimiter characters
\param count Number of delimiter characters
\param ignoreEmptyTokens Flag to avoid empty substrings in the result
container. If two delimiters occur without a character in between, an
empty substring would be placed in the result. If this flag is set,
only non-empty strings are stored.
\param keepSeparators Flag which allows to add the separator to the
result string. If this flag is true, the concatenation of the
substrings results in the original string. Otherwise, only the
characters between the delimiters are returned.
\return The number of resulting substrings
*/
template<class container>
u32 split(container& ret, const T* const c, u32 count=1, bool ignoreEmptyTokens=true, bool keepSeparators=false) const
{
if (!c)
return 0;
const u32 oldSize=ret.size();
u32 lastpos = 0;
bool lastWasSeparator = false;
for (u32 i=0; i<used; ++i)
{
bool foundSeparator = false;
for (u32 j=0; j<count; ++j)
{
if (array[i] == c[j])
{
if ((!ignoreEmptyTokens || i - lastpos != 0) &&
!lastWasSeparator)
ret.push_back(string<T,TAlloc>(&array[lastpos], i - lastpos));
foundSeparator = true;
lastpos = (keepSeparators ? i : i + 1);
break;
}
}
lastWasSeparator = foundSeparator;
}
if ((used - 1) > lastpos)
ret.push_back(string<T,TAlloc>(&array[lastpos], (used - 1) - lastpos));
return ret.size()-oldSize;
}
private:
//! Reallocate the array, make it bigger or smaller
void reallocate(u32 new_size)
{
T* old_array = array;
array = allocator.allocate(new_size); //new T[new_size];
allocated = new_size;
u32 amount = used < new_size ? used : new_size;
for (u32 i=0; i<amount; ++i)
array[i] = old_array[i];
if (allocated < used)
used = allocated;
allocator.deallocate(old_array); // delete [] old_array;
}
//--- member variables
T* array;
u32 allocated;
u32 used;
TAlloc allocator;
};
//! Typedef for character strings
typedef string<c8> stringc;
//! Typedef for wide character strings
typedef string<wchar_t> stringw;
} // end namespace core
} // end namespace irr
#endif
diff --git a/tests/tests-last-passed-at.txt b/tests/tests-last-passed-at.txt
index 045f2a5..8d480e7 100644
--- a/tests/tests-last-passed-at.txt
+++ b/tests/tests-last-passed-at.txt
@@ -1,4 +1,4 @@
-Tests finished. 51 tests of 51 passed.
-Compiled as DEBUG
-Test suite pass at GMT Fri Feb 05 14:28:53 2010
-
+Tests finished. 51 tests of 51 passed.
+Compiled as DEBUG
+Test suite pass at GMT Fri Feb 12 21:54:42 2010
+
|
paupawsan/Irrlicht
|
8645d6d7f063326f84a9fa3d040bce194762b5c0
|
Backport of the shader release fix and GLSL extension method name changes from trunk.
|
diff --git a/source/Irrlicht/COpenGLExtensionHandler.cpp b/source/Irrlicht/COpenGLExtensionHandler.cpp
index 970d414..8ad9499 100644
--- a/source/Irrlicht/COpenGLExtensionHandler.cpp
+++ b/source/Irrlicht/COpenGLExtensionHandler.cpp
@@ -1,617 +1,624 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_OPENGL_
#include "COpenGLExtensionHandler.h"
#include "irrString.h"
#include "SMaterial.h" // for MATERIAL_MAX_TEXTURES
#include "fast_atof.h"
namespace irr
{
namespace video
{
COpenGLExtensionHandler::COpenGLExtensionHandler() :
StencilBuffer(false), MultiTextureExtension(false),
TextureCompressionExtension(false),
MaxTextureUnits(1), MaxLights(1), MaxAnisotropy(1),
MaxUserClipPlanes(0), MaxAuxBuffers(0),
MaxMultipleRenderTargets(1), MaxIndices(65535),
MaxTextureSize(1), MaxGeometryVerticesOut(0),
MaxTextureLODBias(0.f), Version(0), ShaderLanguageVersion(0)
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
,pGlActiveTextureARB(0), pGlClientActiveTextureARB(0),
pGlGenProgramsARB(0), pGlGenProgramsNV(0),
pGlBindProgramARB(0), pGlBindProgramNV(0),
pGlDeleteProgramsARB(0), pGlDeleteProgramsNV(0),
pGlProgramStringARB(0), pGlLoadProgramNV(0),
pGlProgramLocalParameter4fvARB(0),
pGlCreateShaderObjectARB(0), pGlShaderSourceARB(0),
pGlCompileShaderARB(0), pGlCreateProgramObjectARB(0), pGlAttachObjectARB(0),
pGlLinkProgramARB(0), pGlUseProgramObjectARB(0), pGlDeleteObjectARB(0),
+ pGlGetAttachedObjectsARB(0), pGlGetInfoLogARB(0),
pGlGetObjectParameterivARB(0), pGlGetUniformLocationARB(0),
pGlUniform1ivARB(0), pGlUniform1fvARB(0), pGlUniform2fvARB(0), pGlUniform3fvARB(0), pGlUniform4fvARB(0), pGlUniformMatrix2fvARB(0),
- pGlUniformMatrix3fvARB(0), pGlUniformMatrix4fvARB(0), pGlGetActiveUniformARB(0), pGlPointParameterfARB(0), pGlPointParameterfvARB(0),
+ pGlUniformMatrix3fvARB(0), pGlUniformMatrix4fvARB(0),
+ pGlGetActiveUniformARB(0),
+ pGlPointParameterfARB(0), pGlPointParameterfvARB(0),
pGlStencilFuncSeparate(0), pGlStencilOpSeparate(0),
pGlStencilFuncSeparateATI(0), pGlStencilOpSeparateATI(0),
pGlCompressedTexImage2D(0),
#if defined(GLX_SGI_swap_control)
glxSwapIntervalSGI(0),
#endif
pGlBindFramebufferEXT(0), pGlDeleteFramebuffersEXT(0), pGlGenFramebuffersEXT(0),
pGlCheckFramebufferStatusEXT(0), pGlFramebufferTexture2DEXT(0),
pGlBindRenderbufferEXT(0), pGlDeleteRenderbuffersEXT(0), pGlGenRenderbuffersEXT(0),
pGlRenderbufferStorageEXT(0), pGlFramebufferRenderbufferEXT(0),
pGlDrawBuffersARB(0), pGlDrawBuffersATI(0),
pGlGenBuffersARB(0), pGlBindBufferARB(0), pGlBufferDataARB(0), pGlDeleteBuffersARB(0),
pGlBufferSubDataARB(0), pGlGetBufferSubDataARB(0), pGlMapBufferARB(0), pGlUnmapBufferARB(0),
pGlIsBufferARB(0), pGlGetBufferParameterivARB(0), pGlGetBufferPointervARB(0),
pGlProvokingVertexARB(0), pGlProvokingVertexEXT(0),
pGlColorMaskIndexedEXT(0), pGlEnableIndexedEXT(0), pGlDisableIndexedEXT(0),
pGlBlendFuncIndexedAMD(0), pGlBlendFunciARB(0),
pGlProgramParameteriARB(0), pGlProgramParameteriEXT(0)
#endif // _IRR_OPENGL_USE_EXTPOINTER_
{
for (u32 i=0; i<IRR_OpenGL_Feature_Count; ++i)
FeatureAvailable[i]=false;
DimAliasedLine[0]=1.f;
DimAliasedLine[1]=1.f;
DimAliasedPoint[0]=1.f;
DimAliasedPoint[1]=1.f;
DimSmoothedLine[0]=1.f;
DimSmoothedLine[1]=1.f;
DimSmoothedPoint[0]=1.f;
DimSmoothedPoint[1]=1.f;
}
void COpenGLExtensionHandler::dump() const
{
for (u32 i=0; i<IRR_OpenGL_Feature_Count; ++i)
os::Printer::log(OpenGLFeatureStrings[i], FeatureAvailable[i]?" true":" false");
}
void COpenGLExtensionHandler::initExtensions(bool stencilBuffer)
{
const f32 ogl_ver = core::fast_atof(reinterpret_cast<const c8*>(glGetString(GL_VERSION)));
Version = static_cast<u16>(core::floor32(ogl_ver)*100+core::round32(core::fract(ogl_ver)*10.0f));
if ( Version >= 102)
os::Printer::log("OpenGL driver version is 1.2 or better.", ELL_INFORMATION);
else
os::Printer::log("OpenGL driver version is not 1.2 or better.", ELL_WARNING);
{
const char* t = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
size_t len = 0;
c8 *str = 0;
if (t)
{
len = strlen(t);
str = new c8[len+1];
}
c8* p = str;
for (size_t i=0; i<len; ++i)
{
str[i] = static_cast<char>(t[i]);
if (str[i] == ' ')
{
str[i] = 0;
for (u32 j=0; j<IRR_OpenGL_Feature_Count; ++j)
{
if (!strcmp(OpenGLFeatureStrings[j], p))
{
FeatureAvailable[j] = true;
break;
}
}
p = p + strlen(p) + 1;
}
}
delete [] str;
}
MultiTextureExtension = FeatureAvailable[IRR_ARB_multitexture];
TextureCompressionExtension = FeatureAvailable[IRR_ARB_texture_compression];
StencilBuffer=stencilBuffer;
#ifdef _IRR_WINDOWS_API_
// get multitexturing function pointers
pGlActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC) wglGetProcAddress("glActiveTextureARB");
pGlClientActiveTextureARB = (PFNGLCLIENTACTIVETEXTUREARBPROC) wglGetProcAddress("glClientActiveTextureARB");
// get fragment and vertex program function pointers
pGlGenProgramsARB = (PFNGLGENPROGRAMSARBPROC) wglGetProcAddress("glGenProgramsARB");
pGlGenProgramsNV = (PFNGLGENPROGRAMSNVPROC) wglGetProcAddress("glGenProgramsNV");
pGlBindProgramARB = (PFNGLBINDPROGRAMARBPROC) wglGetProcAddress("glBindProgramARB");
pGlBindProgramNV = (PFNGLBINDPROGRAMNVPROC) wglGetProcAddress("glBindProgramNV");
pGlProgramStringARB = (PFNGLPROGRAMSTRINGARBPROC) wglGetProcAddress("glProgramStringARB");
pGlLoadProgramNV = (PFNGLLOADPROGRAMNVPROC) wglGetProcAddress("glLoadProgramNV");
pGlDeleteProgramsARB = (PFNGLDELETEPROGRAMSARBPROC) wglGetProcAddress("glDeleteProgramsARB");
pGlDeleteProgramsNV = (PFNGLDELETEPROGRAMSNVPROC) wglGetProcAddress("glDeleteProgramsNV");
pGlProgramLocalParameter4fvARB = (PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) wglGetProcAddress("glProgramLocalParameter4fvARB");
pGlCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC) wglGetProcAddress("glCreateShaderObjectARB");
pGlShaderSourceARB = (PFNGLSHADERSOURCEARBPROC) wglGetProcAddress("glShaderSourceARB");
pGlCompileShaderARB = (PFNGLCOMPILESHADERARBPROC) wglGetProcAddress("glCompileShaderARB");
pGlCreateProgramObjectARB = (PFNGLCREATEPROGRAMOBJECTARBPROC) wglGetProcAddress("glCreateProgramObjectARB");
pGlAttachObjectARB = (PFNGLATTACHOBJECTARBPROC) wglGetProcAddress("glAttachObjectARB");
pGlLinkProgramARB = (PFNGLLINKPROGRAMARBPROC) wglGetProcAddress("glLinkProgramARB");
pGlUseProgramObjectARB = (PFNGLUSEPROGRAMOBJECTARBPROC) wglGetProcAddress("glUseProgramObjectARB");
pGlDeleteObjectARB = (PFNGLDELETEOBJECTARBPROC) wglGetProcAddress("glDeleteObjectARB");
+ pGlGetAttachedObjectsARB = (PFNGLGETATTACHEDOBJECTSARBPROC) wglGetProcAddress("glGetAttachedObjectsARB");
pGlGetInfoLogARB = (PFNGLGETINFOLOGARBPROC) wglGetProcAddress("glGetInfoLogARB");
pGlGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC) wglGetProcAddress("glGetObjectParameterivARB");
pGlGetUniformLocationARB = (PFNGLGETUNIFORMLOCATIONARBPROC) wglGetProcAddress("glGetUniformLocationARB");
pGlUniform4fvARB = (PFNGLUNIFORM4FVARBPROC) wglGetProcAddress("glUniform4fvARB");
pGlUniform1ivARB = (PFNGLUNIFORM1IVARBPROC) wglGetProcAddress("glUniform1ivARB");
pGlUniform1fvARB = (PFNGLUNIFORM1FVARBPROC) wglGetProcAddress("glUniform1fvARB");
pGlUniform2fvARB = (PFNGLUNIFORM2FVARBPROC) wglGetProcAddress("glUniform2fvARB");
pGlUniform3fvARB = (PFNGLUNIFORM3FVARBPROC) wglGetProcAddress("glUniform3fvARB");
pGlUniformMatrix2fvARB = (PFNGLUNIFORMMATRIX2FVARBPROC) wglGetProcAddress("glUniformMatrix2fvARB");
pGlUniformMatrix3fvARB = (PFNGLUNIFORMMATRIX3FVARBPROC) wglGetProcAddress("glUniformMatrix3fvARB");
pGlUniformMatrix4fvARB = (PFNGLUNIFORMMATRIX4FVARBPROC) wglGetProcAddress("glUniformMatrix4fvARB");
pGlGetActiveUniformARB = (PFNGLGETACTIVEUNIFORMARBPROC) wglGetProcAddress("glGetActiveUniformARB");
// get point parameter extension
pGlPointParameterfARB = (PFNGLPOINTPARAMETERFARBPROC) wglGetProcAddress("glPointParameterfARB");
pGlPointParameterfvARB = (PFNGLPOINTPARAMETERFVARBPROC) wglGetProcAddress("glPointParameterfvARB");
// get stencil extension
pGlStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC) wglGetProcAddress("glStencilFuncSeparate");
pGlStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC) wglGetProcAddress("glStencilOpSeparate");
pGlStencilFuncSeparateATI = (PFNGLSTENCILFUNCSEPARATEATIPROC) wglGetProcAddress("glStencilFuncSeparateATI");
pGlStencilOpSeparateATI = (PFNGLSTENCILOPSEPARATEATIPROC) wglGetProcAddress("glStencilOpSeparateATI");
// compressed textures
pGlCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC) wglGetProcAddress("glCompressedTexImage2D");
// FrameBufferObjects
pGlBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC) wglGetProcAddress("glBindFramebufferEXT");
pGlDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC) wglGetProcAddress("glDeleteFramebuffersEXT");
pGlGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC) wglGetProcAddress("glGenFramebuffersEXT");
pGlCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) wglGetProcAddress("glCheckFramebufferStatusEXT");
pGlFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) wglGetProcAddress("glFramebufferTexture2DEXT");
pGlBindRenderbufferEXT = (PFNGLBINDRENDERBUFFEREXTPROC) wglGetProcAddress("glBindRenderbufferEXT");
pGlDeleteRenderbuffersEXT = (PFNGLDELETERENDERBUFFERSEXTPROC) wglGetProcAddress("glDeleteRenderbuffersEXT");
pGlGenRenderbuffersEXT = (PFNGLGENRENDERBUFFERSEXTPROC) wglGetProcAddress("glGenRenderbuffersEXT");
pGlRenderbufferStorageEXT = (PFNGLRENDERBUFFERSTORAGEEXTPROC) wglGetProcAddress("glRenderbufferStorageEXT");
pGlFramebufferRenderbufferEXT = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) wglGetProcAddress("glFramebufferRenderbufferEXT");
pGlDrawBuffersARB = (PFNGLDRAWBUFFERSARBPROC) wglGetProcAddress("glDrawBuffersARB");
pGlDrawBuffersATI = (PFNGLDRAWBUFFERSATIPROC) wglGetProcAddress("glDrawBuffersATI");
// get vertex buffer extension
pGlGenBuffersARB = (PFNGLGENBUFFERSARBPROC) wglGetProcAddress("glGenBuffersARB");
pGlBindBufferARB = (PFNGLBINDBUFFERARBPROC) wglGetProcAddress("glBindBufferARB");
pGlBufferDataARB = (PFNGLBUFFERDATAARBPROC) wglGetProcAddress("glBufferDataARB");
pGlDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC) wglGetProcAddress("glDeleteBuffersARB");
pGlBufferSubDataARB= (PFNGLBUFFERSUBDATAARBPROC) wglGetProcAddress("glBufferSubDataARB");
pGlGetBufferSubDataARB= (PFNGLGETBUFFERSUBDATAARBPROC)wglGetProcAddress("glGetBufferSubDataARB");
pGlMapBufferARB= (PFNGLMAPBUFFERARBPROC) wglGetProcAddress("glMapBufferARB");
pGlUnmapBufferARB= (PFNGLUNMAPBUFFERARBPROC) wglGetProcAddress("glUnmapBufferARB");
pGlIsBufferARB= (PFNGLISBUFFERARBPROC) wglGetProcAddress("glIsBufferARB");
pGlGetBufferParameterivARB= (PFNGLGETBUFFERPARAMETERIVARBPROC) wglGetProcAddress("glGetBufferParameterivARB");
pGlGetBufferPointervARB= (PFNGLGETBUFFERPOINTERVARBPROC) wglGetProcAddress("glGetBufferPointervARB");
pGlProvokingVertexARB= (PFNGLPROVOKINGVERTEXPROC) wglGetProcAddress("glProvokingVertex");
pGlProvokingVertexEXT= (PFNGLPROVOKINGVERTEXEXTPROC) wglGetProcAddress("glProvokingVertexEXT");
pGlColorMaskIndexedEXT= (PFNGLCOLORMASKINDEXEDEXTPROC) wglGetProcAddress("glColorMaskIndexedEXT");
pGlEnableIndexedEXT= (PFNGLENABLEINDEXEDEXTPROC) wglGetProcAddress("glEnableIndexedEXT");
pGlDisableIndexedEXT= (PFNGLDISABLEINDEXEDEXTPROC) wglGetProcAddress("glDisableIndexedEXT");
pGlBlendFuncIndexedAMD= (PFNGLBLENDFUNCINDEXEDAMDPROC) wglGetProcAddress("glBlendFuncIndexedAMD");
pGlBlendFunciARB= (PFNGLBLENDFUNCIPROC) wglGetProcAddress("glBlendFunciARB");
pGlProgramParameteriARB= (PFNGLPROGRAMPARAMETERIARBPROC) wglGetProcAddress("glProgramParameteriARB");
pGlProgramParameteriEXT= (PFNGLPROGRAMPARAMETERIEXTPROC) wglGetProcAddress("glProgramParameteriEXT");
#elif defined(_IRR_COMPILE_WITH_X11_DEVICE_) || defined (_IRR_COMPILE_WITH_SDL_DEVICE_)
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
#if defined(_IRR_COMPILE_WITH_SDL_DEVICE_) && !defined(_IRR_COMPILE_WITH_X11_DEVICE_)
#define IRR_OGL_LOAD_EXTENSION(x) SDL_GL_GetProcAddress(reinterpret_cast<const char*>(x))
#else
// Accessing the correct function is quite complex
// All libraries should support the ARB version, however
// since GLX 1.4 the non-ARB version is the official one
// So we have to check the runtime environment and
// choose the proper symbol
// In case you still have problems please enable the
// next line by uncommenting it
// #define _IRR_GETPROCADDRESS_WORKAROUND_
#ifndef _IRR_GETPROCADDRESS_WORKAROUND_
__GLXextFuncPtr (*IRR_OGL_LOAD_EXTENSION)(const GLubyte*)=0;
#ifdef GLX_VERSION_1_4
int major=0,minor=0;
if (glXGetCurrentDisplay())
glXQueryVersion(glXGetCurrentDisplay(), &major, &minor);
if ((major>1) || (minor>3))
IRR_OGL_LOAD_EXTENSION=glXGetProcAddress;
else
#endif
IRR_OGL_LOAD_EXTENSION=glXGetProcAddressARB;
#else
#define IRR_OGL_LOAD_EXTENSION glXGetProcAddressARB
#endif
#endif
pGlActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glActiveTextureARB"));
pGlClientActiveTextureARB = (PFNGLCLIENTACTIVETEXTUREARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glClientActiveTextureARB"));
// get fragment and vertex program function pointers
pGlGenProgramsARB = (PFNGLGENPROGRAMSARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glGenProgramsARB"));
pGlGenProgramsNV = (PFNGLGENPROGRAMSNVPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glGenProgramsNV"));
pGlBindProgramARB = (PFNGLBINDPROGRAMARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glBindProgramARB"));
pGlBindProgramNV = (PFNGLBINDPROGRAMNVPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glBindProgramNV"));
pGlDeleteProgramsARB = (PFNGLDELETEPROGRAMSARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glDeleteProgramsARB"));
pGlDeleteProgramsNV = (PFNGLDELETEPROGRAMSNVPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glDeleteProgramsNV"));
pGlProgramStringARB = (PFNGLPROGRAMSTRINGARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glProgramStringARB"));
pGlLoadProgramNV = (PFNGLLOADPROGRAMNVPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glLoadProgramNV"));
pGlProgramLocalParameter4fvARB = (PFNGLPROGRAMLOCALPARAMETER4FVARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glProgramLocalParameter4fvARB"));
pGlCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glCreateShaderObjectARB"));
pGlShaderSourceARB = (PFNGLSHADERSOURCEARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glShaderSourceARB"));
pGlCompileShaderARB = (PFNGLCOMPILESHADERARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glCompileShaderARB"));
pGlCreateProgramObjectARB = (PFNGLCREATEPROGRAMOBJECTARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glCreateProgramObjectARB"));
pGlAttachObjectARB = (PFNGLATTACHOBJECTARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glAttachObjectARB"));
pGlLinkProgramARB = (PFNGLLINKPROGRAMARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glLinkProgramARB"));
pGlUseProgramObjectARB = (PFNGLUSEPROGRAMOBJECTARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glUseProgramObjectARB"));
pGlDeleteObjectARB = (PFNGLDELETEOBJECTARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glDeleteObjectARB"));
+ pGlGetAttachedObjectsARB = (PFNGLGETATTACHEDOBJECTSARBPROC)
+ IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glGetAttachedObjectsARB"));
+
pGlGetInfoLogARB = (PFNGLGETINFOLOGARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glGetInfoLogARB"));
pGlGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glGetObjectParameterivARB"));
pGlGetUniformLocationARB = (PFNGLGETUNIFORMLOCATIONARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glGetUniformLocationARB"));
pGlUniform4fvARB = (PFNGLUNIFORM4FVARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glUniform4fvARB"));
pGlUniform1ivARB = (PFNGLUNIFORM1IVARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glUniform1ivARB"));
pGlUniform1fvARB = (PFNGLUNIFORM1FVARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glUniform1fvARB"));
pGlUniform2fvARB = (PFNGLUNIFORM2FVARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glUniform2fvARB"));
pGlUniform3fvARB = (PFNGLUNIFORM3FVARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glUniform3fvARB"));
pGlUniform4fvARB = (PFNGLUNIFORM4FVARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glUniform4fvARB"));
pGlUniformMatrix2fvARB = (PFNGLUNIFORMMATRIX2FVARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glUniformMatrix2fvARB"));
pGlUniformMatrix3fvARB = (PFNGLUNIFORMMATRIX3FVARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glUniformMatrix3fvARB"));
pGlUniformMatrix4fvARB = (PFNGLUNIFORMMATRIX4FVARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glUniformMatrix4fvARB"));
pGlGetActiveUniformARB = (PFNGLGETACTIVEUNIFORMARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glGetActiveUniformARB"));
// get point parameter extension
pGlPointParameterfARB = (PFNGLPOINTPARAMETERFARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glPointParameterfARB"));
pGlPointParameterfvARB = (PFNGLPOINTPARAMETERFVARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glPointParameterfvARB"));
// get stencil extension
pGlStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glStencilFuncSeparate"));
pGlStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glStencilOpSeparate"));
pGlStencilFuncSeparateATI = (PFNGLSTENCILFUNCSEPARATEATIPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glStencilFuncSeparateATI"));
pGlStencilOpSeparateATI = (PFNGLSTENCILOPSEPARATEATIPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glStencilOpSeparateATI"));
// compressed textures
pGlCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glCompressedTexImage2D"));
#if defined(GLX_SGI_swap_control) && !defined(_IRR_COMPILE_WITH_SDL_DEVICE_)
// get vsync extension
glxSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glXSwapIntervalSGI"));
#endif
// FrameBufferObjects
pGlBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glBindFramebufferEXT"));
pGlDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glDeleteFramebuffersEXT"));
pGlGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glGenFramebuffersEXT"));
pGlCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glCheckFramebufferStatusEXT"));
pGlFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glFramebufferTexture2DEXT"));
pGlBindRenderbufferEXT = (PFNGLBINDRENDERBUFFEREXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glBindRenderbufferEXT"));
pGlDeleteRenderbuffersEXT = (PFNGLDELETERENDERBUFFERSEXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glDeleteRenderbuffersEXT"));
pGlGenRenderbuffersEXT = (PFNGLGENRENDERBUFFERSEXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glGenRenderbuffersEXT"));
pGlRenderbufferStorageEXT = (PFNGLRENDERBUFFERSTORAGEEXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glRenderbufferStorageEXT"));
pGlFramebufferRenderbufferEXT = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glFramebufferRenderbufferEXT"));
pGlDrawBuffersARB = (PFNGLDRAWBUFFERSARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glDrawBuffersARB"));
pGlDrawBuffersATI = (PFNGLDRAWBUFFERSATIPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glDrawBuffersATI"));
pGlGenBuffersARB = (PFNGLGENBUFFERSARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glGenBuffersARB"));
pGlBindBufferARB = (PFNGLBINDBUFFERARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glBindBufferARB"));
pGlBufferDataARB = (PFNGLBUFFERDATAARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glBufferDataARB"));
pGlDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glDeleteBuffersARB"));
pGlBufferSubDataARB = (PFNGLBUFFERSUBDATAARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glBufferSubDataARB"));
pGlGetBufferSubDataARB = (PFNGLGETBUFFERSUBDATAARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glGetBufferSubDataARB"));
pGlMapBufferARB = (PFNGLMAPBUFFERARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glMapBufferARB"));
pGlUnmapBufferARB = (PFNGLUNMAPBUFFERARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glUnmapBufferARB"));
pGlIsBufferARB = (PFNGLISBUFFERARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glIsBufferARB"));
pGlGetBufferParameterivARB = (PFNGLGETBUFFERPARAMETERIVARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glGetBufferParameterivARB"));
pGlGetBufferPointervARB = (PFNGLGETBUFFERPOINTERVARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glGetBufferPointervARB"));
pGlProvokingVertexARB= (PFNGLPROVOKINGVERTEXPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glProvokingVertex"));
pGlProvokingVertexEXT= (PFNGLPROVOKINGVERTEXEXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glProvokingVertexEXT"));
pGlColorMaskIndexedEXT= (PFNGLCOLORMASKINDEXEDEXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glColorMaskIndexedEXT"));
pGlEnableIndexedEXT= (PFNGLENABLEINDEXEDEXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glEnableIndexedEXT"));
pGlDisableIndexedEXT= (PFNGLDISABLEINDEXEDEXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glDisableIndexedEXT"));
pGlBlendFuncIndexedAMD= (PFNGLBLENDFUNCINDEXEDAMDPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glBlendFuncIndexedAMD"));
pGlBlendFunciARB= (PFNGLBLENDFUNCIPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glBlendFunciARB"));
pGlProgramParameteriARB = (PFNGLPROGRAMPARAMETERIARBPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glProgramParameteriARB"));
pGlProgramParameteriEXT = (PFNGLPROGRAMPARAMETERIEXTPROC)
IRR_OGL_LOAD_EXTENSION(reinterpret_cast<const GLubyte*>("glProgramParameteriEXT"));
#endif // _IRR_OPENGL_USE_EXTPOINTER_
#endif // _IRR_WINDOWS_API_
GLint num;
// set some properties
#if defined(GL_ARB_multitexture) || defined(GL_VERSION_1_3)
if (Version>102 || FeatureAvailable[IRR_ARB_multitexture])
{
glGetIntegerv(GL_MAX_TEXTURE_UNITS, &num);
MaxTextureUnits=static_cast<u8>(num);
}
#endif
glGetIntegerv(GL_MAX_LIGHTS, &num);
MaxLights=static_cast<u8>(num);
#ifdef GL_EXT_texture_filter_anisotropic
if (FeatureAvailable[IRR_EXT_texture_filter_anisotropic])
{
glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &num);
MaxAnisotropy=static_cast<u8>(num);
}
#endif
#ifdef GL_VERSION_1_2
if (Version>101)
{
glGetIntegerv(GL_MAX_ELEMENTS_INDICES, &num);
MaxIndices=num;
}
#endif
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &num);
MaxTextureSize=static_cast<u32>(num);
if (queryFeature(EVDF_GEOMETRY_SHADER))
{
#if defined(GL_ARB_geometry_shader4) || defined(GL_EXT_geometry_shader4) || defined(GL_NV_geometry_shader4)
glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT, &num);
MaxGeometryVerticesOut=static_cast<u32>(num);
#elif defined(GL_NV_geometry_program4)
extGlGetProgramiv(GEOMETRY_PROGRAM_NV, GL_MAX_PROGRAM_OUTPUT_VERTICES_NV, &num);
MaxGeometryVerticesOut=static_cast<u32>(num);
#endif
}
#ifdef GL_EXT_texture_lod_bias
if (FeatureAvailable[IRR_EXT_texture_lod_bias])
glGetFloatv(GL_MAX_TEXTURE_LOD_BIAS_EXT, &MaxTextureLODBias);
#endif
glGetIntegerv(GL_MAX_CLIP_PLANES, &num);
MaxUserClipPlanes=static_cast<u8>(num);
glGetIntegerv(GL_AUX_BUFFERS, &num);
MaxAuxBuffers=static_cast<u8>(num);
#ifdef GL_ARB_draw_buffers
if (FeatureAvailable[IRR_ARB_draw_buffers])
{
glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &num);
MaxMultipleRenderTargets = static_cast<u8>(num);
}
#elif defined(GL_ATI_draw_buffers)
if (FeatureAvailable[IRR_ATI_draw_buffers])
{
glGetIntegerv(GL_MAX_DRAW_BUFFERS_ATI, &num);
MaxMultipleRenderTargets = static_cast<u8>(num);
}
#endif
glGetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, DimAliasedLine);
glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, DimAliasedPoint);
glGetFloatv(GL_SMOOTH_LINE_WIDTH_RANGE, DimSmoothedLine);
glGetFloatv(GL_SMOOTH_POINT_SIZE_RANGE, DimSmoothedPoint);
#if defined(GL_ARB_shading_language_100) || defined (GL_VERSION_2_0)
if (FeatureAvailable[IRR_ARB_shading_language_100] || Version>=200)
{
glGetError(); // clean error buffer
#ifdef GL_SHADING_LANGUAGE_VERSION
const GLubyte* shaderVersion = glGetString(GL_SHADING_LANGUAGE_VERSION);
#else
const GLubyte* shaderVersion = glGetString(GL_SHADING_LANGUAGE_VERSION_ARB);
#endif
if (glGetError() == GL_INVALID_ENUM)
ShaderLanguageVersion = 100;
else
{
const f32 sl_ver = core::fast_atof(reinterpret_cast<const c8*>(shaderVersion));
ShaderLanguageVersion = static_cast<u16>(core::floor32(sl_ver)*100+core::round32(core::fract(sl_ver)*10.0f));
}
}
#endif
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (!pGlActiveTextureARB || !pGlClientActiveTextureARB)
{
MultiTextureExtension = false;
os::Printer::log("Failed to load OpenGL's multitexture extension, proceeding without.", ELL_WARNING);
}
else
#endif
if (MaxTextureUnits < 2)
{
MultiTextureExtension = false;
os::Printer::log("Warning: OpenGL device only has one texture unit. Disabling multitexturing.", ELL_WARNING);
}
MaxTextureUnits = core::min_(MaxTextureUnits,static_cast<u8>(MATERIAL_MAX_TEXTURES));
}
bool COpenGLExtensionHandler::queryFeature(E_VIDEO_DRIVER_FEATURE feature) const
{
switch (feature)
{
case EVDF_RENDER_TO_TARGET:
return true;
case EVDF_HARDWARE_TL:
return true; // we cannot tell other things
case EVDF_MULTITEXTURE:
return MultiTextureExtension;
case EVDF_BILINEAR_FILTER:
return true;
case EVDF_MIP_MAP:
return true;
case EVDF_MIP_MAP_AUTO_UPDATE:
return FeatureAvailable[IRR_SGIS_generate_mipmap];
case EVDF_STENCIL_BUFFER:
return StencilBuffer;
case EVDF_VERTEX_SHADER_1_1:
case EVDF_ARB_VERTEX_PROGRAM_1:
return FeatureAvailable[IRR_ARB_vertex_program] || FeatureAvailable[IRR_NV_vertex_program1_1];
case EVDF_PIXEL_SHADER_1_1:
case EVDF_PIXEL_SHADER_1_2:
case EVDF_ARB_FRAGMENT_PROGRAM_1:
return FeatureAvailable[IRR_ARB_fragment_program] || FeatureAvailable[IRR_NV_fragment_program];
case EVDF_PIXEL_SHADER_2_0:
case EVDF_VERTEX_SHADER_2_0:
case EVDF_ARB_GLSL:
return (FeatureAvailable[IRR_ARB_shading_language_100]||Version>=200);
case EVDF_TEXTURE_NSQUARE:
return true; // non-square is always supported
case EVDF_TEXTURE_NPOT:
// Some ATI cards seem to have only SW support in OpenGL 2.0
// drivers if the extension is not exposed, so we skip this
// extra test for now!
// return (FeatureAvailable[IRR_ARB_texture_non_power_of_two]||Version>=200);
return (FeatureAvailable[IRR_ARB_texture_non_power_of_two]);
case EVDF_FRAMEBUFFER_OBJECT:
return FeatureAvailable[IRR_EXT_framebuffer_object];
case EVDF_VERTEX_BUFFER_OBJECT:
return FeatureAvailable[IRR_ARB_vertex_buffer_object];
case EVDF_COLOR_MASK:
return true;
case EVDF_ALPHA_TO_COVERAGE:
return FeatureAvailable[IRR_ARB_multisample];
case EVDF_GEOMETRY_SHADER:
return FeatureAvailable[IRR_ARB_geometry_shader4] || FeatureAvailable[IRR_EXT_geometry_shader4] || FeatureAvailable[IRR_NV_geometry_program4] || FeatureAvailable[IRR_NV_geometry_shader4];
case EVDF_MULTIPLE_RENDER_TARGETS:
return FeatureAvailable[IRR_ARB_draw_buffers] || FeatureAvailable[IRR_ATI_draw_buffers];
case EVDF_MRT_BLEND:
case EVDF_MRT_COLOR_MASK:
return FeatureAvailable[IRR_EXT_draw_buffers2];
case EVDF_MRT_BLEND_FUNC:
return FeatureAvailable[IRR_ARB_draw_buffers_blend] || FeatureAvailable[IRR_AMD_draw_buffers_blend];
default:
return false;
};
}
}
}
#endif
diff --git a/source/Irrlicht/COpenGLExtensionHandler.h b/source/Irrlicht/COpenGLExtensionHandler.h
index d8083fa..654cd8b 100644
--- a/source/Irrlicht/COpenGLExtensionHandler.h
+++ b/source/Irrlicht/COpenGLExtensionHandler.h
@@ -347,1465 +347,1482 @@ static const char* const OpenGLFeatureStrings[] = {
"GL_OES_read_format",
"GL_OML_interlace",
"GL_OML_resample",
"GL_OML_subsample",
"GL_PGI_misc_hints",
"GL_PGI_vertex_hints",
"GL_REND_screen_coordinates",
"GL_S3_s3tc",
"GL_SGI_color_matrix",
"GL_SGI_color_table",
"GL_SGI_depth_pass_instrument",
"GL_SGIS_detail_texture",
"GL_SGIS_fog_function",
"GL_SGIS_generate_mipmap",
"GL_SGIS_multisample",
"GL_SGIS_pixel_texture",
"GL_SGIS_point_line_texgen",
"GL_SGIS_point_parameters",
"GL_SGIS_sharpen_texture",
"GL_SGIS_texture4D",
"GL_SGIS_texture_border_clamp",
"GL_SGIS_texture_color_mask",
"GL_SGIS_texture_edge_clamp",
"GL_SGIS_texture_filter4",
"GL_SGIS_texture_lod",
"GL_SGIS_texture_select",
"GL_SGI_texture_color_table",
"GL_SGIX_async",
"GL_SGIX_async_histogram",
"GL_SGIX_async_pixel",
"GL_SGIX_blend_alpha_minmax",
"GL_SGIX_calligraphic_fragment",
"GL_SGIX_clipmap",
"GL_SGIX_convolution_accuracy",
"GL_SGIX_depth_pass_instrument",
"GL_SGIX_depth_texture",
"GL_SGIX_flush_raster",
"GL_SGIX_fog_offset",
"GL_SGIX_fog_scale",
"GL_SGIX_fragment_lighting",
"GL_SGIX_framezoom",
"GL_SGIX_igloo_interface",
"GL_SGIX_impact_pixel_texture",
"GL_SGIX_instruments",
"GL_SGIX_interlace",
"GL_SGIX_ir_instrument1",
"GL_SGIX_list_priority",
"GL_SGIX_pixel_texture",
"GL_SGIX_pixel_tiles",
"GL_SGIX_polynomial_ffd",
"GL_SGIX_reference_plane",
"GL_SGIX_resample",
"GL_SGIX_scalebias_hint",
"GL_SGIX_shadow",
"GL_SGIX_shadow_ambient",
"GL_SGIX_sprite",
"GL_SGIX_subsample",
"GL_SGIX_tag_sample_buffer",
"GL_SGIX_texture_add_env",
"GL_SGIX_texture_coordinate_clamp",
"GL_SGIX_texture_lod_bias",
"GL_SGIX_texture_multi_buffer",
"GL_SGIX_texture_scale_bias",
"GL_SGIX_texture_select",
"GL_SGIX_vertex_preclip",
"GL_SGIX_ycrcb",
"GL_SGIX_ycrcba",
"GL_SGIX_ycrcb_subsample",
"GL_SUN_convolution_border_modes",
"GL_SUN_global_alpha",
"GL_SUN_mesh_array",
"GL_SUN_slice_accum",
"GL_SUN_triangle_list",
"GL_SUN_vertex",
"GL_SUNX_constant_data",
"GL_WIN_phong_shading",
"GL_WIN_specular_fog"
};
class COpenGLExtensionHandler
{
public:
enum EOpenGLFeatures {
IRR_3DFX_multisample = 0,
IRR_3DFX_tbuffer,
IRR_3DFX_texture_compression_FXT1,
IRR_AMD_draw_buffers_blend,
IRR_AMD_performance_monitor,
IRR_AMD_texture_texture4,
IRR_AMD_vertex_shader_tesselator,
IRR_APPLE_aux_depth_stencil,
IRR_APPLE_client_storage,
IRR_APPLE_element_array,
IRR_APPLE_fence,
IRR_APPLE_float_pixels,
IRR_APPLE_flush_buffer_range,
IRR_APPLE_object_purgeable,
IRR_APPLE_rgb_422,
IRR_APPLE_row_bytes,
IRR_APPLE_specular_vector,
IRR_APPLE_texture_range,
IRR_APPLE_transform_hint,
IRR_APPLE_vertex_array_object,
IRR_APPLE_vertex_array_range,
IRR_APPLE_vertex_program_evaluators,
IRR_APPLE_ycbcr_422,
IRR_ARB_color_buffer_float,
IRR_ARB_compatibility,
IRR_ARB_copy_buffer,
IRR_ARB_depth_buffer_float,
IRR_ARB_depth_clamp,
IRR_ARB_depth_texture,
IRR_ARB_draw_buffers,
IRR_ARB_draw_buffers_blend,
IRR_ARB_draw_elements_base_vertex,
IRR_ARB_draw_instanced,
IRR_ARB_fragment_coord_conventions,
IRR_ARB_fragment_program,
IRR_ARB_fragment_program_shadow,
IRR_ARB_fragment_shader,
IRR_ARB_framebuffer_object,
IRR_ARB_framebuffer_sRGB,
IRR_ARB_geometry_shader4,
IRR_ARB_half_float_pixel,
IRR_ARB_half_float_vertex,
IRR_ARB_imaging,
IRR_ARB_instanced_arrays,
IRR_ARB_map_buffer_range,
IRR_ARB_matrix_palette,
IRR_ARB_multisample,
IRR_ARB_multitexture,
IRR_ARB_occlusion_query,
IRR_ARB_pixel_buffer_object,
IRR_ARB_point_parameters,
IRR_ARB_point_sprite,
IRR_ARB_provoking_vertex,
IRR_ARB_sample_shading,
IRR_ARB_seamless_cube_map,
IRR_ARB_shader_objects,
IRR_ARB_shader_texture_lod,
IRR_ARB_shading_language_100,
IRR_ARB_shadow,
IRR_ARB_shadow_ambient,
IRR_ARB_sync,
IRR_ARB_texture_border_clamp,
IRR_ARB_texture_buffer_object,
IRR_ARB_texture_compression,
IRR_ARB_texture_compression_rgtc,
IRR_ARB_texture_cube_map,
IRR_ARB_texture_cube_map_array,
IRR_ARB_texture_env_add,
IRR_ARB_texture_env_combine,
IRR_ARB_texture_env_crossbar,
IRR_ARB_texture_env_dot3,
IRR_ARB_texture_float,
IRR_ARB_texture_gather,
IRR_ARB_texture_mirrored_repeat,
IRR_ARB_texture_multisample,
IRR_ARB_texture_non_power_of_two,
IRR_ARB_texture_query_lod,
IRR_ARB_texture_rectangle,
IRR_ARB_texture_rg,
IRR_ARB_transpose_matrix,
IRR_ARB_uniform_buffer_object,
IRR_ARB_vertex_array_bgra,
IRR_ARB_vertex_array_object,
IRR_ARB_vertex_blend,
IRR_ARB_vertex_buffer_object,
IRR_ARB_vertex_program,
IRR_ARB_vertex_shader,
IRR_ARB_window_pos,
IRR_ATI_draw_buffers,
IRR_ATI_element_array,
IRR_ATI_envmap_bumpmap,
IRR_ATI_fragment_shader,
IRR_ATI_map_object_buffer,
IRR_ATI_meminfo,
IRR_ATI_pixel_format_float,
IRR_ATI_pn_triangles,
IRR_ATI_separate_stencil,
IRR_ATI_text_fragment_shader,
IRR_ATI_texture_env_combine3,
IRR_ATI_texture_float,
IRR_ATI_texture_mirror_once,
IRR_ATI_vertex_array_object,
IRR_ATI_vertex_attrib_array_object,
IRR_ATI_vertex_streams,
IRR_EXT_422_pixels,
IRR_EXT_abgr,
IRR_EXT_bgra,
IRR_EXT_bindable_uniform,
IRR_EXT_blend_color,
IRR_EXT_blend_equation_separate,
IRR_EXT_blend_func_separate,
IRR_EXT_blend_logic_op,
IRR_EXT_blend_minmax,
IRR_EXT_blend_subtract,
IRR_EXT_clip_volume_hint,
IRR_EXT_cmyka,
IRR_EXT_color_subtable,
IRR_EXT_compiled_vertex_array,
IRR_EXT_convolution,
IRR_EXT_coordinate_frame,
IRR_EXT_copy_texture,
IRR_EXT_cull_vertex,
IRR_EXT_depth_bounds_test,
IRR_EXT_direct_state_access,
IRR_EXT_draw_buffers2,
IRR_EXT_draw_instanced,
IRR_EXT_draw_range_elements,
IRR_EXT_fog_coord,
IRR_EXT_framebuffer_blit,
IRR_EXT_framebuffer_multisample,
IRR_EXT_framebuffer_object,
IRR_EXT_framebuffer_sRGB,
IRR_EXT_geometry_shader4,
IRR_EXT_gpu_program_parameters,
IRR_EXT_gpu_shader4,
IRR_EXT_histogram,
IRR_EXT_index_array_formats,
IRR_EXT_index_func,
IRR_EXT_index_material,
IRR_EXT_index_texture,
IRR_EXT_light_texture,
IRR_EXT_misc_attribute,
IRR_EXT_multi_draw_arrays,
IRR_EXT_multisample,
IRR_EXT_packed_depth_stencil,
IRR_EXT_packed_float,
IRR_EXT_packed_pixels,
IRR_EXT_paletted_texture,
IRR_EXT_pixel_buffer_object,
IRR_EXT_pixel_transform,
IRR_EXT_pixel_transform_color_table,
IRR_EXT_point_parameters,
IRR_EXT_polygon_offset,
IRR_EXT_provoking_vertex,
IRR_EXT_rescale_normal,
IRR_EXT_secondary_color,
IRR_EXT_separate_shader_objects,
IRR_EXT_separate_specular_color,
IRR_EXT_shadow_funcs,
IRR_EXT_shared_texture_palette,
IRR_EXT_stencil_clear_tag,
IRR_EXT_stencil_two_side,
IRR_EXT_stencil_wrap,
IRR_EXT_subtexture,
IRR_EXT_texture,
IRR_EXT_texture3D,
IRR_EXT_texture_array,
IRR_EXT_texture_buffer_object,
IRR_EXT_texture_compression_latc,
IRR_EXT_texture_compression_rgtc,
IRR_EXT_texture_compression_s3tc,
IRR_EXT_texture_cube_map,
IRR_EXT_texture_env_add,
IRR_EXT_texture_env_combine,
IRR_EXT_texture_env_dot3,
IRR_EXT_texture_filter_anisotropic,
IRR_EXT_texture_integer,
IRR_EXT_texture_lod_bias,
IRR_EXT_texture_mirror_clamp,
IRR_EXT_texture_object,
IRR_EXT_texture_perturb_normal,
IRR_EXT_texture_shared_exponent,
IRR_EXT_texture_snorm,
IRR_EXT_texture_sRGB,
IRR_EXT_texture_swizzle,
IRR_EXT_timer_query,
IRR_EXT_transform_feedback,
IRR_EXT_vertex_array,
IRR_EXT_vertex_array_bgra,
IRR_EXT_vertex_shader,
IRR_EXT_vertex_weighting,
IRR_FfdMaskSGIX,
IRR_GREMEDY_frame_terminator,
IRR_GREMEDY_string_marker,
IRR_HP_convolution_border_modes,
IRR_HP_image_transform,
IRR_HP_occlusion_test,
IRR_HP_texture_lighting,
IRR_IBM_cull_vertex,
IRR_IBM_multimode_draw_arrays,
IRR_IBM_rasterpos_clip,
IRR_IBM_texture_mirrored_repeat,
IRR_IBM_vertex_array_lists,
IRR_INGR_blend_func_separate,
IRR_INGR_color_clamp,
IRR_INGR_interlace_read,
IRR_INGR_palette_buffer,
IRR_INTEL_parallel_arrays,
IRR_INTEL_texture_scissor,
IRR_MESA_pack_invert,
IRR_MESA_resize_buffers,
IRR_MESA_window_pos,
IRR_MESAX_texture_stack,
IRR_MESA_ycbcr_texture,
IRR_NV_blend_square,
IRR_NV_conditional_render,
IRR_NV_copy_depth_to_color,
IRR_NV_copy_image,
IRR_NV_depth_buffer_float,
IRR_NV_depth_clamp,
IRR_NV_evaluators,
IRR_NV_explicit_multisample,
IRR_NV_fence,
IRR_NV_float_buffer,
IRR_NV_fog_distance,
IRR_NV_fragment_program,
IRR_NV_fragment_program2,
IRR_NV_fragment_program4,
IRR_NV_fragment_program_option,
IRR_NV_framebuffer_multisample_coverage,
IRR_NV_geometry_program4,
IRR_NV_geometry_shader4,
IRR_NV_gpu_program4,
IRR_NV_half_float,
IRR_NV_light_max_exponent,
IRR_NV_multisample_filter_hint,
IRR_NV_occlusion_query,
IRR_NV_packed_depth_stencil,
IRR_NV_parameter_buffer_object,
IRR_NV_parameter_buffer_object2,
IRR_NV_pixel_data_range,
IRR_NV_point_sprite,
IRR_NV_present_video,
IRR_NV_primitive_restart,
IRR_NV_register_combiners,
IRR_NV_register_combiners2,
IRR_NV_shader_buffer_load,
IRR_NV_texgen_emboss,
IRR_NV_texgen_reflection,
IRR_NV_texture_barrier,
IRR_NV_texture_compression_vtc,
IRR_NV_texture_env_combine4,
IRR_NV_texture_expand_normal,
IRR_NV_texture_rectangle,
IRR_NV_texture_shader,
IRR_NV_texture_shader2,
IRR_NV_texture_shader3,
IRR_NV_transform_feedback,
IRR_NV_transform_feedback2,
IRR_NV_vertex_array_range,
IRR_NV_vertex_array_range2,
IRR_NV_vertex_buffer_unified_memory,
IRR_NV_vertex_program,
IRR_NV_vertex_program1_1,
IRR_NV_vertex_program2,
IRR_NV_vertex_program2_option,
IRR_NV_vertex_program3,
IRR_NV_vertex_program4,
IRR_NV_video_capture,
IRR_OES_read_format,
IRR_OML_interlace,
IRR_OML_resample,
IRR_OML_subsample,
IRR_PGI_misc_hints,
IRR_PGI_vertex_hints,
IRR_REND_screen_coordinates,
IRR_S3_s3tc,
IRR_SGI_color_matrix,
IRR_SGI_color_table,
IRR_SGI_depth_pass_instrument,
IRR_SGIS_detail_texture,
IRR_SGIS_fog_function,
IRR_SGIS_generate_mipmap,
IRR_SGIS_multisample,
IRR_SGIS_pixel_texture,
IRR_SGIS_point_line_texgen,
IRR_SGIS_point_parameters,
IRR_SGIS_sharpen_texture,
IRR_SGIS_texture4D,
IRR_SGIS_texture_border_clamp,
IRR_SGIS_texture_color_mask,
IRR_SGIS_texture_edge_clamp,
IRR_SGIS_texture_filter4,
IRR_SGIS_texture_lod,
IRR_SGIS_texture_select,
IRR_SGI_texture_color_table,
IRR_SGIX_async,
IRR_SGIX_async_histogram,
IRR_SGIX_async_pixel,
IRR_SGIX_blend_alpha_minmax,
IRR_SGIX_calligraphic_fragment,
IRR_SGIX_clipmap,
IRR_SGIX_convolution_accuracy,
IRR_SGIX_depth_pass_instrument,
IRR_SGIX_depth_texture,
IRR_SGIX_flush_raster,
IRR_SGIX_fog_offset,
IRR_SGIX_fog_scale,
IRR_SGIX_fragment_lighting,
IRR_SGIX_framezoom,
IRR_SGIX_igloo_interface,
IRR_SGIX_impact_pixel_texture,
IRR_SGIX_instruments,
IRR_SGIX_interlace,
IRR_SGIX_ir_instrument1,
IRR_SGIX_list_priority,
IRR_SGIX_pixel_texture,
IRR_SGIX_pixel_tiles,
IRR_SGIX_polynomial_ffd,
IRR_SGIX_reference_plane,
IRR_SGIX_resample,
IRR_SGIX_scalebias_hint,
IRR_SGIX_shadow,
IRR_SGIX_shadow_ambient,
IRR_SGIX_sprite,
IRR_SGIX_subsample,
IRR_SGIX_tag_sample_buffer,
IRR_SGIX_texture_add_env,
IRR_SGIX_texture_coordinate_clamp,
IRR_SGIX_texture_lod_bias,
IRR_SGIX_texture_multi_buffer,
IRR_SGIX_texture_scale_bias,
IRR_SGIX_texture_select,
IRR_SGIX_vertex_preclip,
IRR_SGIX_ycrcb,
IRR_SGIX_ycrcba,
IRR_SGIX_ycrcb_subsample,
IRR_SUN_convolution_border_modes,
IRR_SUN_global_alpha,
IRR_SUN_mesh_array,
IRR_SUN_slice_accum,
IRR_SUN_triangle_list,
IRR_SUN_vertex,
IRR_SUNX_constant_data,
IRR_WIN_phong_shading,
IRR_WIN_specular_fog,
IRR_OpenGL_Feature_Count
};
// constructor
COpenGLExtensionHandler();
// deferred initialization
void initExtensions(bool stencilBuffer);
//! queries the features of the driver, returns true if feature is available
bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const;
//! queries the features of the driver, returns true if feature is available
bool queryOpenGLFeature(EOpenGLFeatures feature) const
{
return FeatureAvailable[feature];
}
//! show all features with availablity
void dump() const;
// Some variables for properties
bool StencilBuffer;
bool MultiTextureExtension;
bool TextureCompressionExtension;
// Some non-boolean properties
//! Maxmimum texture layers supported by the fixed pipeline
u8 MaxTextureUnits;
//! Maximum hardware lights supported
u8 MaxLights;
//! Maximal Anisotropy
u8 MaxAnisotropy;
//! Number of user clipplanes
u8 MaxUserClipPlanes;
//! Number of auxiliary buffers
u8 MaxAuxBuffers;
//! Number of rendertargets available as MRTs
u8 MaxMultipleRenderTargets;
//! Optimal number of indices per meshbuffer
u32 MaxIndices;
//! Maximal texture dimension
u32 MaxTextureSize;
//! Maximal vertices handled by geometry shaders
u32 MaxGeometryVerticesOut;
//! Maximal LOD Bias
f32 MaxTextureLODBias;
//! Minimal and maximal supported thickness for lines without smoothing
GLfloat DimAliasedLine[2];
//! Minimal and maximal supported thickness for points without smoothing
GLfloat DimAliasedPoint[2];
//! Minimal and maximal supported thickness for lines with smoothing
GLfloat DimSmoothedLine[2];
//! Minimal and maximal supported thickness for points with smoothing
GLfloat DimSmoothedPoint[2];
//! OpenGL version as Integer: 100*Major+Minor, i.e. 2.1 becomes 201
u16 Version;
//! GLSL version as Integer: 100*Major+Minor
u16 ShaderLanguageVersion;
// public access to the (loaded) extensions.
// general functions
void extGlActiveTexture(GLenum texture);
void extGlClientActiveTexture(GLenum texture);
void extGlPointParameterf(GLint loc, GLfloat f);
void extGlPointParameterfv(GLint loc, const GLfloat *v);
void extGlStencilFuncSeparate (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);
void extGlStencilOpSeparate (GLenum face, GLenum fail, GLenum zfail, GLenum zpass);
void extGlCompressedTexImage2D(GLenum target, GLint level,
GLenum internalformat, GLsizei width, GLsizei height,
GLint border, GLsizei imageSize, const void* data);
// shader programming
void extGlGenPrograms(GLsizei n, GLuint *programs);
void extGlBindProgram(GLenum target, GLuint program);
void extGlProgramString(GLenum target, GLenum format, GLsizei len, const GLvoid *string);
void extGlLoadProgram(GLenum target, GLuint id, GLsizei len, const GLubyte *string);
void extGlDeletePrograms(GLsizei n, const GLuint *programs);
void extGlProgramLocalParameter4fv(GLenum, GLuint, const GLfloat *);
GLhandleARB extGlCreateShaderObject(GLenum shaderType);
- void extGlShaderSource(GLhandleARB shader, int numOfStrings, const char **strings, int *lenOfStrings);
- void extGlCompileShader(GLhandleARB shader);
+ // note: Due to the type confusion between shader_objects and OpenGL 2.0
+ // we have to add the ARB extension for proper method definitions in case
+ // that handleARB and uint are the same type
+ void extGlShaderSourceARB(GLhandleARB shader, int numOfStrings, const char **strings, int *lenOfStrings);
+ void extGlCompileShaderARB(GLhandleARB shader);
GLhandleARB extGlCreateProgramObject(void);
void extGlAttachObject(GLhandleARB program, GLhandleARB shader);
- void extGlLinkProgram(GLhandleARB program);
+ void extGlLinkProgramARB(GLhandleARB program);
void extGlUseProgramObject(GLhandleARB prog);
void extGlDeleteObject(GLhandleARB object);
+ void extGlGetAttachedObjects(GLhandleARB program, GLsizei maxcount, GLsizei* count, GLhandleARB* shaders);
void extGlGetInfoLog(GLhandleARB object, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);
- void extGlGetObjectParameteriv(GLhandleARB object, GLenum type, int *param);
- GLint extGlGetUniformLocation(GLhandleARB program, const char *name);
+ void extGlGetObjectParameteriv(GLhandleARB object, GLenum type, GLint *param);
+ GLint extGlGetUniformLocationARB(GLhandleARB program, const char *name);
void extGlUniform4fv(GLint location, GLsizei count, const GLfloat *v);
void extGlUniform1iv(GLint loc, GLsizei count, const GLint *v);
void extGlUniform1fv(GLint loc, GLsizei count, const GLfloat *v);
void extGlUniform2fv(GLint loc, GLsizei count, const GLfloat *v);
void extGlUniform3fv(GLint loc, GLsizei count, const GLfloat *v);
void extGlUniformMatrix2fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v);
void extGlUniformMatrix3fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v);
void extGlUniformMatrix4fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v);
- void extGlGetActiveUniform(GLhandleARB program, GLuint index, GLsizei maxlength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
+ void extGlGetActiveUniformARB(GLhandleARB program, GLuint index, GLsizei maxlength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
// framebuffer objects
void extGlBindFramebuffer(GLenum target, GLuint framebuffer);
void extGlDeleteFramebuffers(GLsizei n, const GLuint *framebuffers);
void extGlGenFramebuffers(GLsizei n, GLuint *framebuffers);
GLenum extGlCheckFramebufferStatus(GLenum target);
void extGlFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
void extGlBindRenderbuffer(GLenum target, GLuint renderbuffer);
void extGlDeleteRenderbuffers(GLsizei n, const GLuint *renderbuffers);
void extGlGenRenderbuffers(GLsizei n, GLuint *renderbuffers);
void extGlRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
void extGlFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
void extGlActiveStencilFace(GLenum face);
void extGlDrawBuffers(GLsizei n, const GLenum *bufs);
// vertex buffer object
void extGlGenBuffers(GLsizei n, GLuint *buffers);
void extGlBindBuffer(GLenum target, GLuint buffer);
void extGlBufferData(GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage);
void extGlDeleteBuffers(GLsizei n, const GLuint *buffers);
void extGlBufferSubData (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data);
void extGlGetBufferSubData (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data);
void *extGlMapBuffer (GLenum target, GLenum access);
GLboolean extGlUnmapBuffer (GLenum target);
GLboolean extGlIsBuffer (GLuint buffer);
void extGlGetBufferParameteriv (GLenum target, GLenum pname, GLint *params);
void extGlGetBufferPointerv (GLenum target, GLenum pname, GLvoid **params);
void extGlProvokingVertex(GLenum mode);
void extGlColorMaskIndexed(GLuint buf, GLboolean r, GLboolean g, GLboolean b, GLboolean a);
void extGlEnableIndexed(GLenum target, GLuint index);
void extGlDisableIndexed(GLenum target, GLuint index);
void extGlBlendFuncIndexed(GLuint buf, GLenum src, GLenum dst);
void extGlProgramParameteri(GLuint program, GLenum pname, GLint value);
protected:
// the global feature array
bool FeatureAvailable[IRR_OpenGL_Feature_Count];
#if defined(_IRR_OPENGL_USE_EXTPOINTER_)
PFNGLACTIVETEXTUREARBPROC pGlActiveTextureARB;
PFNGLCLIENTACTIVETEXTUREARBPROC pGlClientActiveTextureARB;
PFNGLGENPROGRAMSARBPROC pGlGenProgramsARB;
PFNGLGENPROGRAMSNVPROC pGlGenProgramsNV;
PFNGLBINDPROGRAMARBPROC pGlBindProgramARB;
PFNGLBINDPROGRAMNVPROC pGlBindProgramNV;
PFNGLDELETEPROGRAMSARBPROC pGlDeleteProgramsARB;
PFNGLDELETEPROGRAMSNVPROC pGlDeleteProgramsNV;
PFNGLPROGRAMSTRINGARBPROC pGlProgramStringARB;
PFNGLLOADPROGRAMNVPROC pGlLoadProgramNV;
PFNGLPROGRAMLOCALPARAMETER4FVARBPROC pGlProgramLocalParameter4fvARB;
PFNGLCREATESHADEROBJECTARBPROC pGlCreateShaderObjectARB;
PFNGLSHADERSOURCEARBPROC pGlShaderSourceARB;
PFNGLCOMPILESHADERARBPROC pGlCompileShaderARB;
PFNGLCREATEPROGRAMOBJECTARBPROC pGlCreateProgramObjectARB;
PFNGLATTACHOBJECTARBPROC pGlAttachObjectARB;
PFNGLLINKPROGRAMARBPROC pGlLinkProgramARB;
PFNGLUSEPROGRAMOBJECTARBPROC pGlUseProgramObjectARB;
PFNGLDELETEOBJECTARBPROC pGlDeleteObjectARB;
+ PFNGLGETATTACHEDOBJECTSARBPROC pGlGetAttachedObjectsARB;
PFNGLGETINFOLOGARBPROC pGlGetInfoLogARB;
PFNGLGETOBJECTPARAMETERIVARBPROC pGlGetObjectParameterivARB;
PFNGLGETUNIFORMLOCATIONARBPROC pGlGetUniformLocationARB;
PFNGLUNIFORM1IVARBPROC pGlUniform1ivARB;
PFNGLUNIFORM1FVARBPROC pGlUniform1fvARB;
PFNGLUNIFORM2FVARBPROC pGlUniform2fvARB;
PFNGLUNIFORM3FVARBPROC pGlUniform3fvARB;
PFNGLUNIFORM4FVARBPROC pGlUniform4fvARB;
PFNGLUNIFORMMATRIX2FVARBPROC pGlUniformMatrix2fvARB;
PFNGLUNIFORMMATRIX3FVARBPROC pGlUniformMatrix3fvARB;
PFNGLUNIFORMMATRIX4FVARBPROC pGlUniformMatrix4fvARB;
PFNGLGETACTIVEUNIFORMARBPROC pGlGetActiveUniformARB;
PFNGLPOINTPARAMETERFARBPROC pGlPointParameterfARB;
PFNGLPOINTPARAMETERFVARBPROC pGlPointParameterfvARB;
PFNGLSTENCILFUNCSEPARATEPROC pGlStencilFuncSeparate;
PFNGLSTENCILOPSEPARATEPROC pGlStencilOpSeparate;
PFNGLSTENCILFUNCSEPARATEATIPROC pGlStencilFuncSeparateATI;
PFNGLSTENCILOPSEPARATEATIPROC pGlStencilOpSeparateATI;
PFNGLCOMPRESSEDTEXIMAGE2DPROC pGlCompressedTexImage2D;
#if defined(_IRR_LINUX_PLATFORM_) && defined(GLX_SGI_swap_control)
PFNGLXSWAPINTERVALSGIPROC glxSwapIntervalSGI;
#endif
PFNGLBINDFRAMEBUFFEREXTPROC pGlBindFramebufferEXT;
PFNGLDELETEFRAMEBUFFERSEXTPROC pGlDeleteFramebuffersEXT;
PFNGLGENFRAMEBUFFERSEXTPROC pGlGenFramebuffersEXT;
PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC pGlCheckFramebufferStatusEXT;
PFNGLFRAMEBUFFERTEXTURE2DEXTPROC pGlFramebufferTexture2DEXT;
PFNGLBINDRENDERBUFFEREXTPROC pGlBindRenderbufferEXT;
PFNGLDELETERENDERBUFFERSEXTPROC pGlDeleteRenderbuffersEXT;
PFNGLGENRENDERBUFFERSEXTPROC pGlGenRenderbuffersEXT;
PFNGLRENDERBUFFERSTORAGEEXTPROC pGlRenderbufferStorageEXT;
PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC pGlFramebufferRenderbufferEXT;
PFNGLACTIVESTENCILFACEEXTPROC pGlActiveStencilFaceEXT;
PFNGLDRAWBUFFERSARBPROC pGlDrawBuffersARB;
PFNGLDRAWBUFFERSATIPROC pGlDrawBuffersATI;
PFNGLGENBUFFERSARBPROC pGlGenBuffersARB;
PFNGLBINDBUFFERARBPROC pGlBindBufferARB;
PFNGLBUFFERDATAARBPROC pGlBufferDataARB;
PFNGLDELETEBUFFERSARBPROC pGlDeleteBuffersARB;
PFNGLBUFFERSUBDATAARBPROC pGlBufferSubDataARB;
PFNGLGETBUFFERSUBDATAARBPROC pGlGetBufferSubDataARB;
PFNGLMAPBUFFERARBPROC pGlMapBufferARB;
PFNGLUNMAPBUFFERARBPROC pGlUnmapBufferARB;
PFNGLISBUFFERARBPROC pGlIsBufferARB;
PFNGLGETBUFFERPARAMETERIVARBPROC pGlGetBufferParameterivARB;
PFNGLGETBUFFERPOINTERVARBPROC pGlGetBufferPointervARB;
PFNGLPROVOKINGVERTEXPROC pGlProvokingVertexARB;
PFNGLPROVOKINGVERTEXEXTPROC pGlProvokingVertexEXT;
PFNGLCOLORMASKINDEXEDEXTPROC pGlColorMaskIndexedEXT;
PFNGLENABLEINDEXEDEXTPROC pGlEnableIndexedEXT;
PFNGLDISABLEINDEXEDEXTPROC pGlDisableIndexedEXT;
PFNGLBLENDFUNCINDEXEDAMDPROC pGlBlendFuncIndexedAMD;
PFNGLBLENDFUNCIPROC pGlBlendFunciARB;
PFNGLPROGRAMPARAMETERIARBPROC pGlProgramParameteriARB;
PFNGLPROGRAMPARAMETERIEXTPROC pGlProgramParameteriEXT;
#endif
};
inline void COpenGLExtensionHandler::extGlActiveTexture(GLenum texture)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (MultiTextureExtension && pGlActiveTextureARB)
pGlActiveTextureARB(texture);
#else
if (MultiTextureExtension)
#ifdef GL_ARB_multitexture
glActiveTextureARB(texture);
#else
glActiveTexture(texture);
#endif
#endif
}
inline void COpenGLExtensionHandler::extGlClientActiveTexture(GLenum texture)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (MultiTextureExtension && pGlClientActiveTextureARB)
pGlClientActiveTextureARB(texture);
#else
if (MultiTextureExtension)
glClientActiveTextureARB(texture);
#endif
}
inline void COpenGLExtensionHandler::extGlGenPrograms(GLsizei n, GLuint *programs)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGenProgramsARB)
pGlGenProgramsARB(n, programs);
else if (pGlGenProgramsNV)
pGlGenProgramsNV(n, programs);
#elif defined(GL_ARB_vertex_program) || defined(GL_ARB_fragment_program)
glGenProgramsARB(n,programs);
#elif defined(GL_NV_vertex_program) || defined(GL_NV_fragment_program)
glGenProgramsNV(n,programs);
#else
os::Printer::log("glGenPrograms not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBindProgram(GLenum target, GLuint program)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlBindProgramARB)
pGlBindProgramARB(target, program);
else if (pGlBindProgramNV)
pGlBindProgramNV(target, program);
#elif defined(GL_ARB_vertex_program) || defined(GL_ARB_fragment_program)
glBindProgramARB(target, program);
#elif defined(GL_NV_vertex_program) || defined(GL_NV_fragment_program)
glBindProgramNV(target, program);
#else
os::Printer::log("glBindProgram not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlProgramString(GLenum target, GLenum format, GLsizei len, const GLvoid *string)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlProgramStringARB)
pGlProgramStringARB(target, format, len, string);
#elif defined(GL_ARB_vertex_program) || defined(GL_ARB_fragment_program)
glProgramStringARB(target,format,len,string);
#else
os::Printer::log("glProgramString not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlLoadProgram(GLenum target, GLuint id, GLsizei len, const GLubyte *string)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlLoadProgramNV)
pGlLoadProgramNV(target, id, len, string);
#elif defined(GL_NV_vertex_program) || defined(GL_NV_fragment_program)
glLoadProgramNV(target,id,len,string);
#else
os::Printer::log("glLoadProgram not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlDeletePrograms(GLsizei n, const GLuint *programs)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlDeleteProgramsARB)
pGlDeleteProgramsARB(n, programs);
else if (pGlDeleteProgramsNV)
pGlDeleteProgramsNV(n, programs);
#elif defined(GL_ARB_vertex_program) || defined(GL_ARB_fragment_program)
glDeleteProgramsARB(n,programs);
#elif defined(GL_NV_vertex_program) || defined(GL_NV_fragment_program)
glDeleteProgramsNV(n,programs);
#else
os::Printer::log("glDeletePrograms not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlProgramLocalParameter4fv(GLenum n, GLuint i, const GLfloat * f)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlProgramLocalParameter4fvARB)
pGlProgramLocalParameter4fvARB(n,i,f);
#elif defined(GL_ARB_vertex_program) || defined(GL_ARB_fragment_program)
glProgramLocalParameter4fvARB(n,i,f);
#else
os::Printer::log("glProgramLocalParameter4fv not supported", ELL_ERROR);
#endif
}
inline GLhandleARB COpenGLExtensionHandler::extGlCreateShaderObject(GLenum shaderType)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlCreateShaderObjectARB)
return pGlCreateShaderObjectARB(shaderType);
#elif defined(GL_ARB_shader_objects)
return glCreateShaderObjectARB(shaderType);
#else
os::Printer::log("glCreateShaderObject not supported", ELL_ERROR);
#endif
return 0;
}
-inline void COpenGLExtensionHandler::extGlShaderSource(GLhandleARB shader, int numOfStrings, const char **strings, int *lenOfStrings)
+inline void COpenGLExtensionHandler::extGlShaderSourceARB(GLhandleARB shader, int numOfStrings, const char **strings, int *lenOfStrings)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlShaderSourceARB)
pGlShaderSourceARB(shader, numOfStrings, strings, lenOfStrings);
#elif defined(GL_ARB_shader_objects)
glShaderSourceARB(shader, numOfStrings, strings, (GLint *)lenOfStrings);
#else
os::Printer::log("glShaderSource not supported", ELL_ERROR);
#endif
}
-inline void COpenGLExtensionHandler::extGlCompileShader(GLhandleARB shader)
+inline void COpenGLExtensionHandler::extGlCompileShaderARB(GLhandleARB shader)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlCompileShaderARB)
pGlCompileShaderARB(shader);
#elif defined(GL_ARB_shader_objects)
glCompileShaderARB(shader);
#else
os::Printer::log("glCompileShader not supported", ELL_ERROR);
#endif
}
inline GLhandleARB COpenGLExtensionHandler::extGlCreateProgramObject(void)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlCreateProgramObjectARB)
return pGlCreateProgramObjectARB();
#elif defined(GL_ARB_shader_objects)
return glCreateProgramObjectARB();
#else
os::Printer::log("glCreateProgramObject not supported", ELL_ERROR);
#endif
return 0;
}
inline void COpenGLExtensionHandler::extGlAttachObject(GLhandleARB program, GLhandleARB shader)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlAttachObjectARB)
pGlAttachObjectARB(program, shader);
#elif defined(GL_ARB_shader_objects)
glAttachObjectARB(program, shader);
#else
os::Printer::log("glAttachObject not supported", ELL_ERROR);
#endif
}
-inline void COpenGLExtensionHandler::extGlLinkProgram(GLhandleARB program)
+inline void COpenGLExtensionHandler::extGlLinkProgramARB(GLhandleARB program)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlLinkProgramARB)
pGlLinkProgramARB(program);
#elif defined(GL_ARB_shader_objects)
glLinkProgramARB(program);
#else
os::Printer::log("glLinkProgram not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUseProgramObject(GLhandleARB prog)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUseProgramObjectARB)
pGlUseProgramObjectARB(prog);
#elif defined(GL_ARB_shader_objects)
glUseProgramObjectARB(prog);
#else
os::Printer::log("glUseProgramObject not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlDeleteObject(GLhandleARB object)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlDeleteObjectARB)
pGlDeleteObjectARB(object);
#elif defined(GL_ARB_shader_objects)
glDeleteObjectARB(object);
#else
- os::Printer::log("gldeleteObject not supported", ELL_ERROR);
+ os::Printer::log("glDeleteObject not supported", ELL_ERROR);
+#endif
+}
+
+inline void COpenGLExtensionHandler::extGlGetAttachedObjects(GLhandleARB program, GLsizei maxcount, GLsizei* count, GLhandleARB* shaders)
+{
+#ifdef _IRR_OPENGL_USE_EXTPOINTER_
+ if (pGlGetAttachedObjectsARB)
+ pGlGetAttachedObjectsARB(program, maxcount, count, shaders);
+#elif defined(GL_ARB_shader_objects)
+ glGetAttachedObjectsARB(program, maxcount, count, shaders);
+#else
+ os::Printer::log("glGetAttachedObjects not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGetInfoLog(GLhandleARB object, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetInfoLogARB)
pGlGetInfoLogARB(object, maxLength, length, infoLog);
#elif defined(GL_ARB_shader_objects)
glGetInfoLogARB(object, maxLength, length, infoLog);
#else
os::Printer::log("glGetInfoLog not supported", ELL_ERROR);
#endif
}
-inline void COpenGLExtensionHandler::extGlGetObjectParameteriv(GLhandleARB object, GLenum type, int *param)
+inline void COpenGLExtensionHandler::extGlGetObjectParameteriv(GLhandleARB object, GLenum type, GLint *param)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetObjectParameterivARB)
pGlGetObjectParameterivARB(object, type, param);
#elif defined(GL_ARB_shader_objects)
- glGetObjectParameterivARB(object, type, (GLint *)param);
+ glGetObjectParameterivARB(object, type, param);
#else
os::Printer::log("glGetObjectParameteriv not supported", ELL_ERROR);
#endif
}
-inline GLint COpenGLExtensionHandler::extGlGetUniformLocation(GLhandleARB program, const char *name)
+inline GLint COpenGLExtensionHandler::extGlGetUniformLocationARB(GLhandleARB program, const char *name)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetUniformLocationARB)
return pGlGetUniformLocationARB(program, name);
#elif defined(GL_ARB_shader_objects)
return glGetUniformLocationARB(program, name);
#else
os::Printer::log("glGetUniformLocation not supported", ELL_ERROR);
#endif
return 0;
}
inline void COpenGLExtensionHandler::extGlUniform4fv(GLint location, GLsizei count, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniform4fvARB)
pGlUniform4fvARB(location, count, v);
#elif defined(GL_ARB_shader_objects)
glUniform4fvARB(location, count, v);
#else
os::Printer::log("glUniform4fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniform1iv(GLint loc, GLsizei count, const GLint *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniform1ivARB)
pGlUniform1ivARB(loc, count, v);
#elif defined(GL_ARB_shader_objects)
glUniform1ivARB(loc, count, v);
#else
os::Printer::log("glUniform1iv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniform1fv(GLint loc, GLsizei count, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniform1fvARB)
pGlUniform1fvARB(loc, count, v);
#elif defined(GL_ARB_shader_objects)
glUniform1fvARB(loc, count, v);
#else
os::Printer::log("glUniform1fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniform2fv(GLint loc, GLsizei count, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniform2fvARB)
pGlUniform2fvARB(loc, count, v);
#elif defined(GL_ARB_shader_objects)
glUniform2fvARB(loc, count, v);
#else
os::Printer::log("glUniform2fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniform3fv(GLint loc, GLsizei count, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniform3fvARB)
pGlUniform3fvARB(loc, count, v);
#elif defined(GL_ARB_shader_objects)
glUniform3fvARB(loc, count, v);
#else
os::Printer::log("glUniform3fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniformMatrix2fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniformMatrix2fvARB)
pGlUniformMatrix2fvARB(loc, count, transpose, v);
#elif defined(GL_ARB_shader_objects)
glUniformMatrix2fvARB(loc, count, transpose, v);
#else
os::Printer::log("glUniformMatrix2fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniformMatrix3fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniformMatrix3fvARB)
pGlUniformMatrix3fvARB(loc, count, transpose, v);
#elif defined(GL_ARB_shader_objects)
glUniformMatrix3fvARB(loc, count, transpose, v);
#else
os::Printer::log("glUniformMatrix3fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniformMatrix4fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniformMatrix4fvARB)
pGlUniformMatrix4fvARB(loc, count, transpose, v);
#elif defined(GL_ARB_shader_objects)
glUniformMatrix4fvARB(loc, count, transpose, v);
#else
os::Printer::log("glUniformMatrix4fv not supported", ELL_ERROR);
#endif
}
-inline void COpenGLExtensionHandler::extGlGetActiveUniform(GLhandleARB program,
+inline void COpenGLExtensionHandler::extGlGetActiveUniformARB(GLhandleARB program,
GLuint index, GLsizei maxlength, GLsizei *length,
GLint *size, GLenum *type, GLcharARB *name)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetActiveUniformARB)
pGlGetActiveUniformARB(program, index, maxlength, length, size, type, name);
#elif defined(GL_ARB_shader_objects)
glGetActiveUniformARB(program, index, maxlength, length, size, type, name);
#else
os::Printer::log("glGetActiveUniform not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlPointParameterf(GLint loc, GLfloat f)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlPointParameterfARB)
pGlPointParameterfARB(loc, f);
#elif defined(GL_ARB_point_parameters)
glPointParameterfARB(loc, f);
#else
os::Printer::log("glPointParameterf not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlPointParameterfv(GLint loc, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlPointParameterfvARB)
pGlPointParameterfvARB(loc, v);
#elif defined(GL_ARB_point_parameters)
glPointParameterfvARB(loc, v);
#else
os::Printer::log("glPointParameterfv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlStencilFuncSeparate (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlStencilFuncSeparate)
pGlStencilFuncSeparate(frontfunc, backfunc, ref, mask);
else if (pGlStencilFuncSeparateATI)
pGlStencilFuncSeparateATI(frontfunc, backfunc, ref, mask);
#elif defined(GL_VERSION_2_0)
glStencilFuncSeparate(frontfunc, backfunc, ref, mask);
#elif defined(GL_ATI_separate_stencil)
glStencilFuncSeparateATI(frontfunc, backfunc, ref, mask);
#else
os::Printer::log("glStencilFuncSeparate not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlStencilOpSeparate (GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlStencilOpSeparate)
pGlStencilOpSeparate(face, fail, zfail, zpass);
else if (pGlStencilOpSeparateATI)
pGlStencilOpSeparateATI(face, fail, zfail, zpass);
#elif defined(GL_VERSION_2_0)
glStencilOpSeparate(face, fail, zfail, zpass);
#elif defined(GL_ATI_separate_stencil)
glStencilOpSeparateATI(face, fail, zfail, zpass);
#else
os::Printer::log("glStencilOpSeparate not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width,
GLsizei height, GLint border, GLsizei imageSize, const void* data)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlCompressedTexImage2D)
pGlCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data);
#elif defined(GL_ARB_texture_compression)
glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data);
#else
os::Printer::log("glCompressedTexImage2D not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBindFramebuffer(GLenum target, GLuint framebuffer)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlBindFramebufferEXT)
pGlBindFramebufferEXT(target, framebuffer);
#elif defined(GL_EXT_framebuffer_object)
glBindFramebufferEXT(target, framebuffer);
#else
os::Printer::log("glBindFramebuffer not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlDeleteFramebuffers(GLsizei n, const GLuint *framebuffers)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlDeleteFramebuffersEXT)
pGlDeleteFramebuffersEXT(n, framebuffers);
#elif defined(GL_EXT_framebuffer_object)
glDeleteFramebuffersEXT(n, framebuffers);
#else
os::Printer::log("glDeleteFramebuffers not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGenFramebuffers(GLsizei n, GLuint *framebuffers)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGenFramebuffersEXT)
pGlGenFramebuffersEXT(n, framebuffers);
#elif defined(GL_EXT_framebuffer_object)
glGenFramebuffersEXT(n, framebuffers);
#else
os::Printer::log("glGenFramebuffers not supported", ELL_ERROR);
#endif
}
inline GLenum COpenGLExtensionHandler::extGlCheckFramebufferStatus(GLenum target)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlCheckFramebufferStatusEXT)
return pGlCheckFramebufferStatusEXT(target);
else
return 0;
#elif defined(GL_EXT_framebuffer_object)
return glCheckFramebufferStatusEXT(target);
#else
os::Printer::log("glCheckFramebufferStatus not supported", ELL_ERROR);
return 0;
#endif
}
inline void COpenGLExtensionHandler::extGlFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlFramebufferTexture2DEXT)
pGlFramebufferTexture2DEXT(target, attachment, textarget, texture, level);
#elif defined(GL_EXT_framebuffer_object)
glFramebufferTexture2DEXT(target, attachment, textarget, texture, level);
#else
os::Printer::log("glFramebufferTexture2D not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBindRenderbuffer(GLenum target, GLuint renderbuffer)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlBindRenderbufferEXT)
pGlBindRenderbufferEXT(target, renderbuffer);
#elif defined(GL_EXT_framebuffer_object)
glBindRenderbufferEXT(target, renderbuffer);
#else
os::Printer::log("glBindRenderbuffer not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlDeleteRenderbuffers(GLsizei n, const GLuint *renderbuffers)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlDeleteRenderbuffersEXT)
pGlDeleteRenderbuffersEXT(n, renderbuffers);
#elif defined(GL_EXT_framebuffer_object)
glDeleteRenderbuffersEXT(n, renderbuffers);
#else
os::Printer::log("glDeleteRenderbuffers not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGenRenderbuffers(GLsizei n, GLuint *renderbuffers)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGenRenderbuffersEXT)
pGlGenRenderbuffersEXT(n, renderbuffers);
#elif defined(GL_EXT_framebuffer_object)
glGenRenderbuffersEXT(n, renderbuffers);
#else
os::Printer::log("glGenRenderbuffers not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlRenderbufferStorageEXT)
pGlRenderbufferStorageEXT(target, internalformat, width, height);
#elif defined(GL_EXT_framebuffer_object)
glRenderbufferStorageEXT(target, internalformat, width, height);
#else
os::Printer::log("glRenderbufferStorage not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlFramebufferRenderbufferEXT)
pGlFramebufferRenderbufferEXT(target, attachment, renderbuffertarget, renderbuffer);
#elif defined(GL_EXT_framebuffer_object)
glFramebufferRenderbufferEXT(target, attachment, renderbuffertarget, renderbuffer);
#else
os::Printer::log("glFramebufferRenderbuffer not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlActiveStencilFace(GLenum face)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlActiveStencilFaceEXT)
pGlActiveStencilFaceEXT(face);
#elif defined(GL_EXT_stencil_two_side)
glActiveStencilFaceEXT(face);
#else
os::Printer::log("glActiveStencilFace not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlDrawBuffers(GLsizei n, const GLenum *bufs)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlDrawBuffersARB)
pGlDrawBuffersARB(n, bufs);
else if (pGlDrawBuffersATI)
pGlDrawBuffersATI(n, bufs);
#elif defined(GL_ARB_draw_buffers)
glDrawBuffersARB(n, bufs);
#elif defined(GL_ATI_draw_buffers)
glDrawBuffersATI(n, bufs);
#else
os::Printer::log("glDrawBuffers not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGenBuffers(GLsizei n, GLuint *buffers)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGenBuffersARB)
pGlGenBuffersARB(n, buffers);
#elif defined(GL_ARB_vertex_buffer_object)
glGenBuffers(n, buffers);
#else
os::Printer::log("glGenBuffers not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBindBuffer(GLenum target, GLuint buffer)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlBindBufferARB)
pGlBindBufferARB(target, buffer);
#elif defined(GL_ARB_vertex_buffer_object)
glBindBuffer(target, buffer);
#else
os::Printer::log("glBindBuffer not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBufferData(GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlBufferDataARB)
pGlBufferDataARB(target, size, data, usage);
#elif defined(GL_ARB_vertex_buffer_object)
glBufferData(target, size, data, usage);
#else
os::Printer::log("glBufferData not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlDeleteBuffers(GLsizei n, const GLuint *buffers)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlDeleteBuffersARB)
pGlDeleteBuffersARB(n, buffers);
#elif defined(GL_ARB_vertex_buffer_object)
glDeleteBuffers(n, buffers);
#else
os::Printer::log("glDeleteBuffers not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBufferSubData(GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlBufferSubDataARB)
pGlBufferSubDataARB(target, offset, size, data);
#elif defined(GL_ARB_vertex_buffer_object)
glBufferSubData(target, offset, size, data);
#else
os::Printer::log("glBufferSubData not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGetBufferSubData(GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetBufferSubDataARB)
pGlGetBufferSubDataARB(target, offset, size, data);
#elif defined(GL_ARB_vertex_buffer_object)
glGetBufferSubData(target, offset, size, data);
#else
os::Printer::log("glGetBufferSubData not supported", ELL_ERROR);
#endif
}
inline void *COpenGLExtensionHandler::extGlMapBuffer(GLenum target, GLenum access)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlMapBufferARB)
return pGlMapBufferARB(target, access);
return 0;
#elif defined(GL_ARB_vertex_buffer_object)
return glMapBuffer(target, access);
#else
os::Printer::log("glMapBuffer not supported", ELL_ERROR);
return 0;
#endif
}
inline GLboolean COpenGLExtensionHandler::extGlUnmapBuffer (GLenum target)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUnmapBufferARB)
return pGlUnmapBufferARB(target);
return false;
#elif defined(GL_ARB_vertex_buffer_object)
return glUnmapBuffer(target);
#else
os::Printer::log("glUnmapBuffer not supported", ELL_ERROR);
return false;
#endif
}
inline GLboolean COpenGLExtensionHandler::extGlIsBuffer (GLuint buffer)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlIsBufferARB)
return pGlIsBufferARB(buffer);
return false;
#elif defined(GL_ARB_vertex_buffer_object)
return glIsBuffer(buffer);
#else
os::Printer::log("glDeleteBuffers not supported", ELL_ERROR);
return false;
#endif
}
inline void COpenGLExtensionHandler::extGlGetBufferParameteriv (GLenum target, GLenum pname, GLint *params)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetBufferParameterivARB)
pGlGetBufferParameterivARB(target, pname, params);
#elif defined(GL_ARB_vertex_buffer_object)
glGetBufferParameteriv(target, pname, params);
#else
os::Printer::log("glGetBufferParameteriv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGetBufferPointerv (GLenum target, GLenum pname, GLvoid **params)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetBufferPointervARB)
pGlGetBufferPointervARB(target, pname, params);
#elif defined(GL_ARB_vertex_buffer_object)
glGetBufferPointerv(target, pname, params);
#else
os::Printer::log("glGetBufferPointerv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlProvokingVertex(GLenum mode)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (FeatureAvailable[IRR_ARB_provoking_vertex] && pGlProvokingVertexARB)
pGlProvokingVertexARB(mode);
else if (FeatureAvailable[IRR_EXT_provoking_vertex] && pGlProvokingVertexEXT)
pGlProvokingVertexEXT(mode);
#elif defined(GL_ARB_provoking_vertex)
glProvokingVertex(mode);
#elif defined(GL_EXT_provoking_vertex)
glProvokingVertexEXT(mode);
#else
os::Printer::log("glProvokingVertex not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlColorMaskIndexed(GLuint buf, GLboolean r, GLboolean g, GLboolean b, GLboolean a)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (FeatureAvailable[IRR_EXT_draw_buffers2] && pGlColorMaskIndexedEXT)
pGlColorMaskIndexedEXT(buf, r, g, b, a);
#elif defined(GL_EXT_draw_buffers2)
glColorMaskIndexedEXT(buf, r, g, b, a);
#else
os::Printer::log("glColorMaskIndexed not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlEnableIndexed(GLenum target, GLuint index)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (FeatureAvailable[IRR_EXT_draw_buffers2] && pGlEnableIndexedEXT)
pGlEnableIndexedEXT(target, index);
#elif defined(GL_EXT_draw_buffers2)
glEnableIndexedEXT(target, index);
#else
os::Printer::log("glEnableIndexed not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlDisableIndexed(GLenum target, GLuint index)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (FeatureAvailable[IRR_EXT_draw_buffers2] && pGlDisableIndexedEXT)
pGlDisableIndexedEXT(target, index);
#elif defined(GL_EXT_draw_buffers2)
glDisableIndexedEXT(target, index);
#else
os::Printer::log("glDisableIndexed not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBlendFuncIndexed(GLuint buf, GLenum src, GLenum dst)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (FeatureAvailable[IRR_ARB_draw_buffers_blend] && pGlBlendFunciARB)
pGlBlendFunciARB(buf, src, dst);
if (FeatureAvailable[IRR_AMD_draw_buffers_blend] && pGlBlendFuncIndexedAMD)
pGlBlendFuncIndexedAMD(buf, src, dst);
#elif defined(GL_ARB_draw_buffers_blend)
glBlendFunciARB(buf, src, dst);
#elif defined(GL_AMD_draw_buffers_blend)
glBlendFuncIndexedAMD(buf, src, dst);
#else
os::Printer::log("glBlendFuncIndexed not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlProgramParameteri(GLuint program, GLenum pname, GLint value)
{
#if defined(_IRR_OPENGL_USE_EXTPOINTER_)
if (queryFeature(EVDF_GEOMETRY_SHADER))
{
if (pGlProgramParameteriARB)
pGlProgramParameteriARB(program, pname, value);
else if (pGlProgramParameteriEXT)
pGlProgramParameteriEXT(program, pname, value);
}
#elif defined(GL_ARB_geometry_shader4)
glProgramParameteriARB(program, pname, value);
#elif defined(GL_EXT_geometry_shader4)
glProgramParameteriEXT(program, pname, value);
#elif defined(GL_NV_geometry_program4) || defined(GL_NV_geometry_shader4)
glProgramParameteriNV(program, pname, value);
#else
os::Printer::log("glProgramParameteri not supported", ELL_ERROR);
#endif
}
}
}
#endif
#endif
diff --git a/source/Irrlicht/COpenGLSLMaterialRenderer.cpp b/source/Irrlicht/COpenGLSLMaterialRenderer.cpp
index a97e681..873d895 100644
--- a/source/Irrlicht/COpenGLSLMaterialRenderer.cpp
+++ b/source/Irrlicht/COpenGLSLMaterialRenderer.cpp
@@ -1,411 +1,420 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
// This file was originally written by William Finlayson. I (Nikolaus
// Gebhardt) did some minor modifications and changes to it and integrated it
// into Irrlicht. Thanks a lot to William for his work on this and that he gave
// me his permission to add it into Irrlicht using the zlib license.
// After Irrlicht 0.12, Michael Zoech did some improvements to this renderer, I
// merged this into Irrlicht 0.14, thanks to him for his work.
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_OPENGL_
#include "COpenGLSLMaterialRenderer.h"
#include "IGPUProgrammingServices.h"
#include "IShaderConstantSetCallBack.h"
#include "IMaterialRendererServices.h"
#include "IVideoDriver.h"
#include "os.h"
#include "COpenGLDriver.h"
namespace irr
{
namespace video
{
//! Constructor
COpenGLSLMaterialRenderer::COpenGLSLMaterialRenderer(video::COpenGLDriver* driver,
s32& outMaterialTypeNr, const c8* vertexShaderProgram,
const c8* vertexShaderEntryPointName,
E_VERTEX_SHADER_TYPE vsCompileTarget,
const c8* pixelShaderProgram,
const c8* pixelShaderEntryPointName,
E_PIXEL_SHADER_TYPE psCompileTarget,
const c8* geometryShaderProgram,
const c8* geometryShaderEntryPointName,
E_GEOMETRY_SHADER_TYPE gsCompileTarget,
scene::E_PRIMITIVE_TYPE inType, scene::E_PRIMITIVE_TYPE outType,
u32 verticesOut,
IShaderConstantSetCallBack* callback,
video::IMaterialRenderer* baseMaterial,
s32 userData)
: Driver(driver), CallBack(callback), BaseMaterial(baseMaterial),
Program(0), UserData(userData)
{
#ifdef _DEBUG
setDebugName("COpenGLSLMaterialRenderer");
#endif
//entry points must always be main, and the compile target isn't selectable
//it is fine to ignore what has been asked for, as the compiler should spot anything wrong
//just check that GLSL is available
if (BaseMaterial)
BaseMaterial->grab();
if (CallBack)
CallBack->grab();
if (!Driver->queryFeature(EVDF_ARB_GLSL))
return;
init(outMaterialTypeNr, vertexShaderProgram, pixelShaderProgram, geometryShaderProgram);
}
//! constructor only for use by derived classes who want to
//! create a fall back material for example.
COpenGLSLMaterialRenderer::COpenGLSLMaterialRenderer(COpenGLDriver* driver,
IShaderConstantSetCallBack* callback,
IMaterialRenderer* baseMaterial, s32 userData)
: Driver(driver), CallBack(callback), BaseMaterial(baseMaterial),
Program(0), UserData(userData)
{
if (BaseMaterial)
BaseMaterial->grab();
if (CallBack)
CallBack->grab();
}
//! Destructor
COpenGLSLMaterialRenderer::~COpenGLSLMaterialRenderer()
{
if (CallBack)
CallBack->drop();
- if(Program)
+ if (Program)
{
+ GLhandleARB shaders[8];
+ GLint count;
+ Driver->extGlGetAttachedObjects(Program, 8, &count, shaders);
+ for (GLint i=0; i<count; ++i)
+ Driver->extGlDeleteObject(shaders[i]);
Driver->extGlDeleteObject(Program);
Program = 0;
}
UniformInfo.clear();
if (BaseMaterial)
BaseMaterial->drop();
}
void COpenGLSLMaterialRenderer::init(s32& outMaterialTypeNr,
const c8* vertexShaderProgram,
const c8* pixelShaderProgram,
const c8* geometryShaderProgram,
scene::E_PRIMITIVE_TYPE inType, scene::E_PRIMITIVE_TYPE outType,
u32 verticesOut)
{
outMaterialTypeNr = -1;
if (!createProgram())
return;
#if defined(GL_ARB_vertex_shader) && defined (GL_ARB_fragment_shader)
if (vertexShaderProgram)
if (!createShader(GL_VERTEX_SHADER_ARB, vertexShaderProgram))
return;
if (pixelShaderProgram)
if (!createShader(GL_FRAGMENT_SHADER_ARB, pixelShaderProgram))
return;
#endif
#if defined(GL_ARB_geometry_shader4) || defined(GL_EXT_geometry_shader4) || defined(GL_NV_geometry_program4) || defined(GL_NV_geometry_shader4)
if (geometryShaderProgram && Driver->queryFeature(EVDF_GEOMETRY_SHADER))
{
if (!createShader(GL_GEOMETRY_SHADER_EXT, geometryShaderProgram))
return;
#if defined(GL_ARB_geometry_shader4) || defined(GL_EXT_geometry_shader4) || defined(GL_NV_geometry_shader4)
- Driver->extGlProgramParameteri(Program, GL_GEOMETRY_INPUT_TYPE_EXT, Driver->primitiveTypeToGL(inType));
- Driver->extGlProgramParameteri(Program, GL_GEOMETRY_OUTPUT_TYPE_EXT, Driver->primitiveTypeToGL(outType));
+ Driver->extGlProgramParameteri((GLuint)Program, GL_GEOMETRY_INPUT_TYPE_EXT, Driver->primitiveTypeToGL(inType));
+ Driver->extGlProgramParameteri((GLuint)Program, GL_GEOMETRY_OUTPUT_TYPE_EXT, Driver->primitiveTypeToGL(outType));
if (verticesOut==0)
- Driver->extGlProgramParameteri(Program, GL_GEOMETRY_VERTICES_OUT_EXT, Driver->MaxGeometryVerticesOut);
+ Driver->extGlProgramParameteri((GLuint)Program, GL_GEOMETRY_VERTICES_OUT_EXT, Driver->MaxGeometryVerticesOut);
else
- Driver->extGlProgramParameteri(Program, GL_GEOMETRY_VERTICES_OUT_EXT, core::min_(verticesOut, Driver->MaxGeometryVerticesOut));
+ Driver->extGlProgramParameteri((GLuint)Program, GL_GEOMETRY_VERTICES_OUT_EXT, core::min_(verticesOut, Driver->MaxGeometryVerticesOut));
#elif defined(GL_NV_geometry_program4)
if (verticesOut==0)
Driver->extGlProgramVertexLimit(GL_GEOMETRY_PROGRAM_NV, Driver->MaxGeometryVerticesOut);
else
Driver->extGlProgramVertexLimit(GL_GEOMETRY_PROGRAM_NV, core::min_(verticesOut, Driver->MaxGeometryVerticesOut));
#endif
}
#endif
if (!linkProgram())
return;
// register myself as new material
outMaterialTypeNr = Driver->addMaterialRenderer(this);
}
bool COpenGLSLMaterialRenderer::OnRender(IMaterialRendererServices* service,
E_VERTEX_TYPE vtxtype)
{
// call callback to set shader constants
if (CallBack && Program)
CallBack->OnSetConstants(this, UserData);
return true;
}
void COpenGLSLMaterialRenderer::OnSetMaterial(const video::SMaterial& material,
const video::SMaterial& lastMaterial,
bool resetAllRenderstates,
video::IMaterialRendererServices* services)
{
if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates)
{
if (Program)
Driver->extGlUseProgramObject(Program);
if (BaseMaterial)
BaseMaterial->OnSetMaterial(material, material, true, this);
}
//let callback know used material
if (CallBack)
CallBack->OnSetMaterial(material);
for (u32 i=0; i<MATERIAL_MAX_TEXTURES; ++i)
Driver->setActiveTexture(i, material.getTexture(i));
Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
void COpenGLSLMaterialRenderer::OnUnsetMaterial()
{
Driver->extGlUseProgramObject(0);
if (BaseMaterial)
BaseMaterial->OnUnsetMaterial();
}
//! Returns if the material is transparent.
bool COpenGLSLMaterialRenderer::isTransparent() const
{
return BaseMaterial ? BaseMaterial->isTransparent() : false;
}
bool COpenGLSLMaterialRenderer::createProgram()
{
Program = Driver->extGlCreateProgramObject();
return true;
}
bool COpenGLSLMaterialRenderer::createShader(GLenum shaderType, const char* shader)
{
GLhandleARB shaderHandle = Driver->extGlCreateShaderObject(shaderType);
- Driver->extGlShaderSource(shaderHandle, 1, &shader, NULL);
- Driver->extGlCompileShader(shaderHandle);
+ Driver->extGlShaderSourceARB(shaderHandle, 1, &shader, NULL);
+ Driver->extGlCompileShaderARB(shaderHandle);
- int status = 0;
+ GLint status = 0;
#ifdef GL_ARB_shader_objects
Driver->extGlGetObjectParameteriv(shaderHandle, GL_OBJECT_COMPILE_STATUS_ARB, &status);
#endif
if (!status)
{
os::Printer::log("GLSL shader failed to compile", ELL_ERROR);
// check error message and log it
- int maxLength=0;
+ GLint maxLength=0;
GLsizei length;
#ifdef GL_ARB_shader_objects
Driver->extGlGetObjectParameteriv(shaderHandle,
GL_OBJECT_INFO_LOG_LENGTH_ARB, &maxLength);
#endif
- GLcharARB *pInfoLog = new GLcharARB[maxLength];
- Driver->extGlGetInfoLog(shaderHandle, maxLength, &length, pInfoLog);
- os::Printer::log(reinterpret_cast<const c8*>(pInfoLog), ELL_ERROR);
- delete [] pInfoLog;
+ GLcharARB *infoLog = new GLcharARB[maxLength];
+ Driver->extGlGetInfoLog(shaderHandle, maxLength, &length, infoLog);
+ os::Printer::log(reinterpret_cast<const c8*>(infoLog), ELL_ERROR);
+ delete [] infoLog;
return false;
}
Driver->extGlAttachObject(Program, shaderHandle);
return true;
}
bool COpenGLSLMaterialRenderer::linkProgram()
{
- Driver->extGlLinkProgram(Program);
+ Driver->extGlLinkProgramARB(Program);
- int status = 0;
+ GLint status = 0;
#ifdef GL_ARB_shader_objects
Driver->extGlGetObjectParameteriv(Program, GL_OBJECT_LINK_STATUS_ARB, &status);
#endif
if (!status)
{
os::Printer::log("GLSL shader program failed to link", ELL_ERROR);
// check error message and log it
- int maxLength=0;
+ GLint maxLength=0;
GLsizei length;
#ifdef GL_ARB_shader_objects
Driver->extGlGetObjectParameteriv(Program,
GL_OBJECT_INFO_LOG_LENGTH_ARB, &maxLength);
#endif
- GLcharARB *pInfoLog = new GLcharARB[maxLength];
- Driver->extGlGetInfoLog(Program, maxLength, &length, pInfoLog);
- os::Printer::log(reinterpret_cast<const c8*>(pInfoLog), ELL_ERROR);
- delete [] pInfoLog;
+ GLcharARB *infoLog = new GLcharARB[maxLength];
+ Driver->extGlGetInfoLog(Program, maxLength, &length, infoLog);
+ os::Printer::log(reinterpret_cast<const c8*>(infoLog), ELL_ERROR);
+ delete [] infoLog;
return false;
}
// get uniforms information
- int num = 0;
+ GLint num = 0;
#ifdef GL_ARB_shader_objects
Driver->extGlGetObjectParameteriv(Program, GL_OBJECT_ACTIVE_UNIFORMS_ARB, &num);
#endif
if (num == 0)
{
// no uniforms
return true;
}
- int maxlen = 0;
+ GLint maxlen = 0;
#ifdef GL_ARB_shader_objects
Driver->extGlGetObjectParameteriv(Program, GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB, &maxlen);
#endif
if (maxlen == 0)
{
os::Printer::log("GLSL: failed to retrieve uniform information", ELL_ERROR);
return false;
}
// seems that some implementations use an extra null terminator
++maxlen;
c8 *buf = new c8[maxlen];
UniformInfo.clear();
UniformInfo.reallocate(num);
for (int i=0; i < num; ++i)
{
SUniformInfo ui;
memset(buf, 0, maxlen);
GLint size;
- Driver->extGlGetActiveUniform(Program, i, maxlen, 0, &size, &ui.type, reinterpret_cast<GLcharARB*>(buf));
+ Driver->extGlGetActiveUniformARB(Program, i, maxlen, 0, &size, &ui.type, reinterpret_cast<GLcharARB*>(buf));
ui.name = buf;
UniformInfo.push_back(ui);
}
delete [] buf;
return true;
}
void COpenGLSLMaterialRenderer::setBasicRenderStates(const SMaterial& material,
const SMaterial& lastMaterial,
bool resetAllRenderstates)
{
// forward
Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates);
}
bool COpenGLSLMaterialRenderer::setVertexShaderConstant(const c8* name, const f32* floats, int count)
{
return setPixelShaderConstant(name, floats, count);
}
void COpenGLSLMaterialRenderer::setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
{
os::Printer::log("Cannot set constant, please use high level shader call instead.", ELL_WARNING);
}
bool COpenGLSLMaterialRenderer::setPixelShaderConstant(const c8* name, const f32* floats, int count)
{
- int i, num = static_cast<int>(UniformInfo.size());
+ u32 i;
+ const u32 num = UniformInfo.size();
for (i=0; i < num; ++i)
{
if (UniformInfo[i].name == name)
break;
}
if (i == num)
return false;
#ifdef GL_ARB_shader_objects
- GLint Location=Driver->extGlGetUniformLocation(Program,name);
+ GLint Location=Driver->extGlGetUniformLocationARB(Program,name);
switch (UniformInfo[i].type)
{
case GL_FLOAT:
Driver->extGlUniform1fv(Location, count, floats);
break;
case GL_FLOAT_VEC2_ARB:
Driver->extGlUniform2fv(Location, count/2, floats);
break;
case GL_FLOAT_VEC3_ARB:
Driver->extGlUniform3fv(Location, count/3, floats);
break;
case GL_FLOAT_VEC4_ARB:
Driver->extGlUniform4fv(Location, count/4, floats);
break;
case GL_FLOAT_MAT2_ARB:
Driver->extGlUniformMatrix2fv(Location, count/4, false, floats);
break;
case GL_FLOAT_MAT3_ARB:
Driver->extGlUniformMatrix3fv(Location, count/9, false, floats);
break;
case GL_FLOAT_MAT4_ARB:
Driver->extGlUniformMatrix4fv(Location, count/16, false, floats);
break;
default:
Driver->extGlUniform1iv(Location, count, reinterpret_cast<const GLint*>(floats));
break;
}
+ return true;
+#else
+ return false;
#endif
- return true;
}
+
void COpenGLSLMaterialRenderer::setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
{
os::Printer::log("Cannot set constant, use high level shader call.", ELL_WARNING);
}
IVideoDriver* COpenGLSLMaterialRenderer::getVideoDriver()
{
return Driver;
}
} // end namespace video
} // end namespace irr
#endif
|
paupawsan/Irrlicht
|
c20ffac6029611325e488151d45fc5a607a30b04
|
Make sure we only use and free the Atom when it's really set. Bug reported by tryum
|
diff --git a/source/Irrlicht/CIrrDeviceLinux.cpp b/source/Irrlicht/CIrrDeviceLinux.cpp
index 7f867ea..dff1a29 100644
--- a/source/Irrlicht/CIrrDeviceLinux.cpp
+++ b/source/Irrlicht/CIrrDeviceLinux.cpp
@@ -616,1028 +616,1031 @@ bool CIrrDeviceLinux::createWindow()
if (!CreationParams.WindowId)
{
// create new Window
// Remove window manager decoration in fullscreen
attributes.override_redirect = CreationParams.Fullscreen;
window = XCreateWindow(display,
RootWindow(display, visual->screen),
0, 0, Width, Height, 0, visual->depth,
InputOutput, visual->visual,
CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect,
&attributes);
XMapRaised(display, window);
CreationParams.WindowId = (void*)window;
Atom wmDelete;
wmDelete = XInternAtom(display, wmDeleteWindow, True);
XSetWMProtocols(display, window, &wmDelete, 1);
if (CreationParams.Fullscreen)
{
XSetInputFocus(display, window, RevertToParent, CurrentTime);
int grabKb = XGrabKeyboard(display, window, True, GrabModeAsync,
GrabModeAsync, CurrentTime);
IrrPrintXGrabError(grabKb, "XGrabKeyboard");
int grabPointer = XGrabPointer(display, window, True, ButtonPressMask,
GrabModeAsync, GrabModeAsync, window, None, CurrentTime);
IrrPrintXGrabError(grabPointer, "XGrabPointer");
XWarpPointer(display, None, window, 0, 0, 0, 0, 0, 0);
}
}
else
{
// attach external window
window = (Window)CreationParams.WindowId;
if (!CreationParams.IgnoreInput)
{
XCreateWindow(display,
window,
0, 0, Width, Height, 0, visual->depth,
InputOutput, visual->visual,
CWBorderPixel | CWColormap | CWEventMask,
&attributes);
}
XWindowAttributes wa;
XGetWindowAttributes(display, window, &wa);
CreationParams.WindowSize.Width = wa.width;
CreationParams.WindowSize.Height = wa.height;
CreationParams.Fullscreen = false;
ExternalWindow = true;
}
WindowMinimized=false;
// Currently broken in X, see Bug ID 2795321
// XkbSetDetectableAutoRepeat(display, True, &AutorepeatSupport);
#ifdef _IRR_COMPILE_WITH_OPENGL_
// connect glx context to window
Context=0;
if (isAvailableGLX && CreationParams.DriverType==video::EDT_OPENGL)
{
if (UseGLXWindow)
{
glxWin=glXCreateWindow(display,glxFBConfig,window,NULL);
if (glxWin)
{
// create glx context
Context = glXCreateNewContext(display, glxFBConfig, GLX_RGBA_TYPE, NULL, True);
if (Context)
{
if (!glXMakeContextCurrent(display, glxWin, glxWin, Context))
{
os::Printer::log("Could not make context current.", ELL_WARNING);
glXDestroyContext(display, Context);
}
}
else
{
os::Printer::log("Could not create GLX rendering context.", ELL_WARNING);
}
}
else
{
os::Printer::log("Could not create GLX window.", ELL_WARNING);
}
}
else
{
Context = glXCreateContext(display, visual, NULL, True);
if (Context)
{
if (!glXMakeCurrent(display, window, Context))
{
os::Printer::log("Could not make context current.", ELL_WARNING);
glXDestroyContext(display, Context);
}
}
else
{
os::Printer::log("Could not create GLX rendering context.", ELL_WARNING);
}
}
}
#endif // _IRR_COMPILE_WITH_OPENGL_
Window tmp;
u32 borderWidth;
int x,y;
unsigned int bits;
XGetGeometry(display, window, &tmp, &x, &y, &Width, &Height, &borderWidth, &bits);
CreationParams.Bits = bits;
CreationParams.WindowSize.Width = Width;
CreationParams.WindowSize.Height = Height;
StdHints = XAllocSizeHints();
long num;
XGetWMNormalHints(display, window, StdHints, &num);
// create an XImage for the software renderer
//(thx to Nadav for some clues on how to do that!)
if (CreationParams.DriverType == video::EDT_SOFTWARE || CreationParams.DriverType == video::EDT_BURNINGSVIDEO)
{
SoftwareImage = XCreateImage(display,
visual->visual, visual->depth,
ZPixmap, 0, 0, Width, Height,
BitmapPad(display), 0);
// use malloc because X will free it later on
if (SoftwareImage)
SoftwareImage->data = (char*) malloc(SoftwareImage->bytes_per_line * SoftwareImage->height * sizeof(char));
}
initXAtoms();
#endif // #ifdef _IRR_COMPILE_WITH_X11_
return true;
}
//! create the driver
void CIrrDeviceLinux::createDriver()
{
switch(CreationParams.DriverType)
{
#ifdef _IRR_COMPILE_WITH_X11_
case video::EDT_SOFTWARE:
#ifdef _IRR_COMPILE_WITH_SOFTWARE_
VideoDriver = video::createSoftwareDriver(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this);
#else
os::Printer::log("No Software driver support compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_BURNINGSVIDEO:
#ifdef _IRR_COMPILE_WITH_BURNINGSVIDEO_
VideoDriver = video::createSoftwareDriver2(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this);
#else
os::Printer::log("Burning's video driver was not compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_OPENGL:
#ifdef _IRR_COMPILE_WITH_OPENGL_
if (Context)
VideoDriver = video::createOpenGLDriver(CreationParams, FileSystem, this);
#else
os::Printer::log("No OpenGL support compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_DIRECT3D8:
case video::EDT_DIRECT3D9:
os::Printer::log("This driver is not available in Linux. Try OpenGL or Software renderer.",
ELL_ERROR);
break;
case video::EDT_NULL:
VideoDriver = video::createNullDriver(FileSystem, CreationParams.WindowSize);
break;
default:
os::Printer::log("Unable to create video driver of unknown type.", ELL_ERROR);
break;
#else
case video::EDT_NULL:
VideoDriver = video::createNullDriver(FileSystem, CreationParams.WindowSize);
break;
default:
os::Printer::log("No X11 support compiled in. Only Null driver available.", ELL_ERROR);
break;
#endif
}
}
//! runs the device. Returns false if device wants to be deleted
bool CIrrDeviceLinux::run()
{
os::Timer::tick();
#ifdef _IRR_COMPILE_WITH_X11_
if ((CreationParams.DriverType != video::EDT_NULL) && display)
{
SEvent irrevent;
irrevent.MouseInput.ButtonStates = 0xffffffff;
while (XPending(display) > 0 && !Close)
{
XEvent event;
XNextEvent(display, &event);
switch (event.type)
{
case ConfigureNotify:
// check for changed window size
if ((event.xconfigure.width != (int) Width) ||
(event.xconfigure.height != (int) Height))
{
Width = event.xconfigure.width;
Height = event.xconfigure.height;
// resize image data
if (SoftwareImage)
{
XDestroyImage(SoftwareImage);
SoftwareImage = XCreateImage(display,
visual->visual, visual->depth,
ZPixmap, 0, 0, Width, Height,
BitmapPad(display), 0);
// use malloc because X will free it later on
if (SoftwareImage)
SoftwareImage->data = (char*) malloc(SoftwareImage->bytes_per_line * SoftwareImage->height * sizeof(char));
}
if (VideoDriver)
VideoDriver->OnResize(core::dimension2d<u32>(Width, Height));
}
break;
case MapNotify:
WindowMinimized=false;
break;
case UnmapNotify:
WindowMinimized=true;
break;
case FocusIn:
WindowHasFocus=true;
break;
case FocusOut:
WindowHasFocus=false;
break;
case MotionNotify:
irrevent.EventType = irr::EET_MOUSE_INPUT_EVENT;
irrevent.MouseInput.Event = irr::EMIE_MOUSE_MOVED;
irrevent.MouseInput.X = event.xbutton.x;
irrevent.MouseInput.Y = event.xbutton.y;
irrevent.MouseInput.Control = (event.xkey.state & ControlMask) != 0;
irrevent.MouseInput.Shift = (event.xkey.state & ShiftMask) != 0;
// mouse button states
irrevent.MouseInput.ButtonStates = (event.xbutton.state & Button1Mask) ? irr::EMBSM_LEFT : 0;
irrevent.MouseInput.ButtonStates |= (event.xbutton.state & Button3Mask) ? irr::EMBSM_RIGHT : 0;
irrevent.MouseInput.ButtonStates |= (event.xbutton.state & Button2Mask) ? irr::EMBSM_MIDDLE : 0;
postEventFromUser(irrevent);
break;
case ButtonPress:
case ButtonRelease:
irrevent.EventType = irr::EET_MOUSE_INPUT_EVENT;
irrevent.MouseInput.X = event.xbutton.x;
irrevent.MouseInput.Y = event.xbutton.y;
irrevent.MouseInput.Control = (event.xkey.state & ControlMask) != 0;
irrevent.MouseInput.Shift = (event.xkey.state & ShiftMask) != 0;
// mouse button states
// This sets the state which the buttons had _prior_ to the event.
// So unlike on Windows the button which just got changed has still the old state here.
// We handle that below by flipping the corresponding bit later.
irrevent.MouseInput.ButtonStates = (event.xbutton.state & Button1Mask) ? irr::EMBSM_LEFT : 0;
irrevent.MouseInput.ButtonStates |= (event.xbutton.state & Button3Mask) ? irr::EMBSM_RIGHT : 0;
irrevent.MouseInput.ButtonStates |= (event.xbutton.state & Button2Mask) ? irr::EMBSM_MIDDLE : 0;
irrevent.MouseInput.Event = irr::EMIE_COUNT;
switch(event.xbutton.button)
{
case Button1:
irrevent.MouseInput.Event =
(event.type == ButtonPress) ? irr::EMIE_LMOUSE_PRESSED_DOWN : irr::EMIE_LMOUSE_LEFT_UP;
irrevent.MouseInput.ButtonStates ^= irr::EMBSM_LEFT;
break;
case Button3:
irrevent.MouseInput.Event =
(event.type == ButtonPress) ? irr::EMIE_RMOUSE_PRESSED_DOWN : irr::EMIE_RMOUSE_LEFT_UP;
irrevent.MouseInput.ButtonStates ^= irr::EMBSM_RIGHT;
break;
case Button2:
irrevent.MouseInput.Event =
(event.type == ButtonPress) ? irr::EMIE_MMOUSE_PRESSED_DOWN : irr::EMIE_MMOUSE_LEFT_UP;
irrevent.MouseInput.ButtonStates ^= irr::EMBSM_MIDDLE;
break;
case Button4:
if (event.type == ButtonPress)
{
irrevent.MouseInput.Event = EMIE_MOUSE_WHEEL;
irrevent.MouseInput.Wheel = 1.0f;
}
break;
case Button5:
if (event.type == ButtonPress)
{
irrevent.MouseInput.Event = EMIE_MOUSE_WHEEL;
irrevent.MouseInput.Wheel = -1.0f;
}
break;
}
if (irrevent.MouseInput.Event != irr::EMIE_COUNT)
{
postEventFromUser(irrevent);
if ( irrevent.MouseInput.Event >= EMIE_LMOUSE_PRESSED_DOWN && irrevent.MouseInput.Event <= EMIE_MMOUSE_PRESSED_DOWN )
{
u32 clicks = checkSuccessiveClicks(irrevent.MouseInput.X, irrevent.MouseInput.Y, irrevent.MouseInput.Event);
if ( clicks == 2 )
{
irrevent.MouseInput.Event = (EMOUSE_INPUT_EVENT)(EMIE_LMOUSE_DOUBLE_CLICK + irrevent.MouseInput.Event-EMIE_LMOUSE_PRESSED_DOWN);
postEventFromUser(irrevent);
}
else if ( clicks == 3 )
{
irrevent.MouseInput.Event = (EMOUSE_INPUT_EVENT)(EMIE_LMOUSE_TRIPLE_CLICK + irrevent.MouseInput.Event-EMIE_LMOUSE_PRESSED_DOWN);
postEventFromUser(irrevent);
}
}
}
break;
case MappingNotify:
XRefreshKeyboardMapping (&event.xmapping) ;
break;
case KeyRelease:
if (0 == AutorepeatSupport && (XPending( display ) > 0) )
{
// check for Autorepeat manually
// We'll do the same as Windows does: Only send KeyPressed
// So every KeyRelease is a real release
XEvent next_event;
XPeekEvent (event.xkey.display, &next_event);
if ((next_event.type == KeyPress) &&
(next_event.xkey.keycode == event.xkey.keycode) &&
(next_event.xkey.time - event.xkey.time) < 2) // usually same time, but on some systems a difference of 1 is possible
{
/* Ignore the key release event */
break;
}
}
// fall-through in case the release should be handled
case KeyPress:
{
SKeyMap mp;
char buf[8]={0};
XLookupString(&event.xkey, buf, sizeof(buf), &mp.X11Key, NULL);
const s32 idx = KeyMap.binary_search(mp);
if (idx != -1)
irrevent.KeyInput.Key = (EKEY_CODE)KeyMap[idx].Win32Key;
else
{
irrevent.KeyInput.Key = (EKEY_CODE)0;
os::Printer::log("Could not find win32 key for x11 key.", core::stringc((int)mp.X11Key).c_str(), ELL_WARNING);
}
irrevent.EventType = irr::EET_KEY_INPUT_EVENT;
irrevent.KeyInput.PressedDown = (event.type == KeyPress);
// mbtowc(&irrevent.KeyInput.Char, buf, sizeof(buf));
irrevent.KeyInput.Char = ((wchar_t*)(buf))[0];
irrevent.KeyInput.Control = (event.xkey.state & ControlMask) != 0;
irrevent.KeyInput.Shift = (event.xkey.state & ShiftMask) != 0;
postEventFromUser(irrevent);
}
break;
case ClientMessage:
{
char *atom = XGetAtomName(display, event.xclient.message_type);
if (*atom == *wmDeleteWindow)
{
os::Printer::log("Quit message received.", ELL_INFORMATION);
Close = true;
}
else
{
// we assume it's a user message
irrevent.EventType = irr::EET_USER_EVENT;
irrevent.UserEvent.UserData1 = (s32)event.xclient.data.l[0];
irrevent.UserEvent.UserData2 = (s32)event.xclient.data.l[1];
postEventFromUser(irrevent);
}
XFree(atom);
}
break;
case SelectionRequest:
{
XEvent respond;
XSelectionRequestEvent *req = &(event.xselectionrequest);
if ( req->target == XA_STRING)
{
XChangeProperty (display,
req->requestor,
req->property, req->target,
8, // format
PropModeReplace,
(unsigned char*) Clipboard.c_str(),
Clipboard.size());
respond.xselection.property = req->property;
}
else if ( req->target == X_ATOM_TARGETS )
{
long data[2];
data[0] = X_ATOM_TEXT;
data[1] = XA_STRING;
XChangeProperty (display, req->requestor,
req->property, req->target,
8, PropModeReplace,
(unsigned char *) &data,
sizeof (data));
respond.xselection.property = req->property;
}
else
{
respond.xselection.property= None;
}
respond.xselection.type= SelectionNotify;
respond.xselection.display= req->display;
respond.xselection.requestor= req->requestor;
respond.xselection.selection=req->selection;
respond.xselection.target= req->target;
respond.xselection.time = req->time;
XSendEvent (display, req->requestor,0,0,&respond);
XFlush (display);
}
break;
default:
break;
} // end switch
} // end while
}
#endif //_IRR_COMPILE_WITH_X11_
if(!Close)
pollJoysticks();
return !Close;
}
//! Pause the current process for the minimum time allowed only to allow other processes to execute
void CIrrDeviceLinux::yield()
{
struct timespec ts = {0,0};
nanosleep(&ts, NULL);
}
//! Pause execution and let other processes to run for a specified amount of time.
void CIrrDeviceLinux::sleep(u32 timeMs, bool pauseTimer=false)
{
const bool wasStopped = Timer ? Timer->isStopped() : true;
struct timespec ts;
ts.tv_sec = (time_t) (timeMs / 1000);
ts.tv_nsec = (long) (timeMs % 1000) * 1000000;
if (pauseTimer && !wasStopped)
Timer->stop();
nanosleep(&ts, NULL);
if (pauseTimer && !wasStopped)
Timer->start();
}
//! sets the caption of the window
void CIrrDeviceLinux::setWindowCaption(const wchar_t* text)
{
#ifdef _IRR_COMPILE_WITH_X11_
if (CreationParams.DriverType == video::EDT_NULL)
return;
XTextProperty txt;
- XwcTextListToTextProperty(display, const_cast<wchar_t**>(&text), 1, XStdICCTextStyle, &txt);
- XSetWMName(display, window, &txt);
- XSetWMIconName(display, window, &txt);
- XFree(txt.value);
+ if (Success==XwcTextListToTextProperty(display, const_cast<wchar_t**>(&text),
+ 1, XStdICCTextStyle, &txt))
+ {
+ XSetWMName(display, window, &txt);
+ XSetWMIconName(display, window, &txt);
+ XFree(txt.value);
+ }
#endif
}
//! presents a surface in the client area
bool CIrrDeviceLinux::present(video::IImage* image, void* windowId, core::rect<s32>* srcRect)
{
#ifdef _IRR_COMPILE_WITH_X11_
// this is only necessary for software drivers.
if (!SoftwareImage)
return true;
// thx to Nadav, who send me some clues of how to display the image
// to the X Server.
const u32 destwidth = SoftwareImage->width;
const u32 minWidth = core::min_(image->getDimension().Width, destwidth);
const u32 destPitch = SoftwareImage->bytes_per_line;
video::ECOLOR_FORMAT destColor;
switch (SoftwareImage->bits_per_pixel)
{
case 16:
if (SoftwareImage->depth==16)
destColor = video::ECF_R5G6B5;
else
destColor = video::ECF_A1R5G5B5;
break;
case 24: destColor = video::ECF_R8G8B8; break;
case 32: destColor = video::ECF_A8R8G8B8; break;
default:
os::Printer::log("Unsupported screen depth.");
return false;
}
u8* srcdata = reinterpret_cast<u8*>(image->lock());
u8* destData = reinterpret_cast<u8*>(SoftwareImage->data);
const u32 destheight = SoftwareImage->height;
const u32 srcheight = core::min_(image->getDimension().Height, destheight);
const u32 srcPitch = image->getPitch();
for (u32 y=0; y!=srcheight; ++y)
{
video::CColorConverter::convert_viaFormat(srcdata,image->getColorFormat(), minWidth, destData, destColor);
srcdata+=srcPitch;
destData+=destPitch;
}
image->unlock();
GC gc = DefaultGC(display, DefaultScreen(display));
Window myWindow=window;
if (windowId)
myWindow = reinterpret_cast<Window>(windowId);
XPutImage(display, myWindow, gc, SoftwareImage, 0, 0, 0, 0, destwidth, destheight);
#endif
return true;
}
//! notifies the device that it should close itself
void CIrrDeviceLinux::closeDevice()
{
Close = true;
}
//! returns if window is active. if not, nothing need to be drawn
bool CIrrDeviceLinux::isWindowActive() const
{
return (WindowHasFocus && !WindowMinimized);
}
//! returns if window has focus.
bool CIrrDeviceLinux::isWindowFocused() const
{
return WindowHasFocus;
}
//! returns if window is minimized.
bool CIrrDeviceLinux::isWindowMinimized() const
{
return WindowMinimized;
}
//! returns color format of the window.
video::ECOLOR_FORMAT CIrrDeviceLinux::getColorFormat() const
{
#ifdef _IRR_COMPILE_WITH_X11_
if (visual && (visual->depth != 16))
return video::ECF_R8G8B8;
else
#endif
return video::ECF_R5G6B5;
}
//! Sets if the window should be resizable in windowed mode.
void CIrrDeviceLinux::setResizable(bool resize)
{
#ifdef _IRR_COMPILE_WITH_X11_
if (CreationParams.DriverType == video::EDT_NULL)
return;
XUnmapWindow(display, window);
if ( !resize )
{
// Must be heap memory because data size depends on X Server
XSizeHints *hints = XAllocSizeHints();
hints->flags=PSize|PMinSize|PMaxSize;
hints->min_width=hints->max_width=hints->base_width=Width;
hints->min_height=hints->max_height=hints->base_height=Height;
XSetWMNormalHints(display, window, hints);
XFree(hints);
}
else
{
XSetWMNormalHints(display, window, StdHints);
}
XMapWindow(display, window);
XFlush(display);
#endif // #ifdef _IRR_COMPILE_WITH_X11_
}
//! Return pointer to a list with all video modes supported by the gfx adapter.
video::IVideoModeList* CIrrDeviceLinux::getVideoModeList()
{
#ifdef _IRR_COMPILE_WITH_X11_
if (!VideoModeList.getVideoModeCount())
{
bool temporaryDisplay = false;
if (!display)
{
display = XOpenDisplay(0);
temporaryDisplay=true;
}
if (display)
{
#if defined(_IRR_LINUX_X11_VIDMODE_) || defined(_IRR_LINUX_X11_RANDR_)
s32 eventbase, errorbase;
s32 defaultDepth=DefaultDepth(display,screennr);
#endif
#ifdef _IRR_LINUX_X11_VIDMODE_
if (XF86VidModeQueryExtension(display, &eventbase, &errorbase))
{
// enumerate video modes
int modeCount;
XF86VidModeModeInfo** modes;
XF86VidModeGetAllModeLines(display, screennr, &modeCount, &modes);
// save current video mode
oldVideoMode = *modes[0];
// find fitting mode
VideoModeList.setDesktop(defaultDepth, core::dimension2d<u32>(
modes[0]->hdisplay, modes[0]->vdisplay));
for (int i = 0; i<modeCount; ++i)
{
VideoModeList.addMode(core::dimension2d<u32>(
modes[i]->hdisplay, modes[i]->vdisplay), defaultDepth);
}
XFree(modes);
}
else
#endif
#ifdef _IRR_LINUX_X11_RANDR_
if (XRRQueryExtension(display, &eventbase, &errorbase))
{
int modeCount;
XRRScreenConfiguration *config=XRRGetScreenInfo(display,DefaultRootWindow(display));
oldRandrMode=XRRConfigCurrentConfiguration(config,&oldRandrRotation);
XRRScreenSize *modes=XRRConfigSizes(config,&modeCount);
VideoModeList.setDesktop(defaultDepth, core::dimension2d<u32>(
modes[oldRandrMode].width, modes[oldRandrMode].height));
for (int i = 0; i<modeCount; ++i)
{
VideoModeList.addMode(core::dimension2d<u32>(
modes[i].width, modes[i].height), defaultDepth);
}
XRRFreeScreenConfigInfo(config);
}
else
#endif
{
os::Printer::log("VidMode or RandR X11 extension requireed for VideoModeList." , ELL_WARNING);
}
}
if (display && temporaryDisplay)
{
XCloseDisplay(display);
display=0;
}
}
#endif
return &VideoModeList;
}
//! Minimize window
void CIrrDeviceLinux::minimizeWindow()
{
#ifdef _IRR_COMPILE_WITH_X11_
XIconifyWindow(display, window, screennr);
#endif
}
//! Maximize window
void CIrrDeviceLinux::maximizeWindow()
{
#ifdef _IRR_COMPILE_WITH_X11_
XMapWindow(display, window);
#endif
}
//! Restore original window size
void CIrrDeviceLinux::restoreWindow()
{
#ifdef _IRR_COMPILE_WITH_X11_
XMapWindow(display, window);
#endif
}
void CIrrDeviceLinux::createKeyMap()
{
// I don't know if this is the best method to create
// the lookuptable, but I'll leave it like that until
// I find a better version.
#ifdef _IRR_COMPILE_WITH_X11_
KeyMap.reallocate(84);
KeyMap.push_back(SKeyMap(XK_BackSpace, KEY_BACK));
KeyMap.push_back(SKeyMap(XK_Tab, KEY_TAB));
KeyMap.push_back(SKeyMap(XK_Linefeed, 0)); // ???
KeyMap.push_back(SKeyMap(XK_Clear, KEY_CLEAR));
KeyMap.push_back(SKeyMap(XK_Return, KEY_RETURN));
KeyMap.push_back(SKeyMap(XK_Pause, KEY_PAUSE));
KeyMap.push_back(SKeyMap(XK_Scroll_Lock, KEY_SCROLL));
KeyMap.push_back(SKeyMap(XK_Sys_Req, 0)); // ???
KeyMap.push_back(SKeyMap(XK_Escape, KEY_ESCAPE));
KeyMap.push_back(SKeyMap(XK_Insert, KEY_INSERT));
KeyMap.push_back(SKeyMap(XK_Delete, KEY_DELETE));
KeyMap.push_back(SKeyMap(XK_Home, KEY_HOME));
KeyMap.push_back(SKeyMap(XK_Left, KEY_LEFT));
KeyMap.push_back(SKeyMap(XK_Up, KEY_UP));
KeyMap.push_back(SKeyMap(XK_Right, KEY_RIGHT));
KeyMap.push_back(SKeyMap(XK_Down, KEY_DOWN));
KeyMap.push_back(SKeyMap(XK_Prior, KEY_PRIOR));
KeyMap.push_back(SKeyMap(XK_Page_Up, KEY_PRIOR));
KeyMap.push_back(SKeyMap(XK_Next, KEY_NEXT));
KeyMap.push_back(SKeyMap(XK_Page_Down, KEY_NEXT));
KeyMap.push_back(SKeyMap(XK_End, KEY_END));
KeyMap.push_back(SKeyMap(XK_Begin, KEY_HOME));
KeyMap.push_back(SKeyMap(XK_Num_Lock, KEY_NUMLOCK));
KeyMap.push_back(SKeyMap(XK_KP_Space, KEY_SPACE));
KeyMap.push_back(SKeyMap(XK_KP_Tab, KEY_TAB));
KeyMap.push_back(SKeyMap(XK_KP_Enter, KEY_RETURN));
KeyMap.push_back(SKeyMap(XK_KP_F1, KEY_F1));
KeyMap.push_back(SKeyMap(XK_KP_F2, KEY_F2));
KeyMap.push_back(SKeyMap(XK_KP_F3, KEY_F3));
KeyMap.push_back(SKeyMap(XK_KP_F4, KEY_F4));
KeyMap.push_back(SKeyMap(XK_KP_Home, KEY_HOME));
KeyMap.push_back(SKeyMap(XK_KP_Left, KEY_LEFT));
KeyMap.push_back(SKeyMap(XK_KP_Up, KEY_UP));
KeyMap.push_back(SKeyMap(XK_KP_Right, KEY_RIGHT));
KeyMap.push_back(SKeyMap(XK_KP_Down, KEY_DOWN));
KeyMap.push_back(SKeyMap(XK_Print, KEY_PRINT));
KeyMap.push_back(SKeyMap(XK_KP_Prior, KEY_PRIOR));
KeyMap.push_back(SKeyMap(XK_KP_Page_Up, KEY_PRIOR));
KeyMap.push_back(SKeyMap(XK_KP_Next, KEY_NEXT));
KeyMap.push_back(SKeyMap(XK_KP_Page_Down, KEY_NEXT));
KeyMap.push_back(SKeyMap(XK_KP_End, KEY_END));
KeyMap.push_back(SKeyMap(XK_KP_Begin, KEY_HOME));
KeyMap.push_back(SKeyMap(XK_KP_Insert, KEY_INSERT));
KeyMap.push_back(SKeyMap(XK_KP_Delete, KEY_DELETE));
KeyMap.push_back(SKeyMap(XK_KP_Equal, 0)); // ???
KeyMap.push_back(SKeyMap(XK_KP_Multiply, KEY_MULTIPLY));
KeyMap.push_back(SKeyMap(XK_KP_Add, KEY_ADD));
KeyMap.push_back(SKeyMap(XK_KP_Separator, KEY_SEPARATOR));
KeyMap.push_back(SKeyMap(XK_KP_Subtract, KEY_SUBTRACT));
KeyMap.push_back(SKeyMap(XK_KP_Decimal, KEY_DECIMAL));
KeyMap.push_back(SKeyMap(XK_KP_Divide, KEY_DIVIDE));
KeyMap.push_back(SKeyMap(XK_KP_0, KEY_KEY_0));
KeyMap.push_back(SKeyMap(XK_KP_1, KEY_KEY_1));
KeyMap.push_back(SKeyMap(XK_KP_2, KEY_KEY_2));
KeyMap.push_back(SKeyMap(XK_KP_3, KEY_KEY_3));
KeyMap.push_back(SKeyMap(XK_KP_4, KEY_KEY_4));
KeyMap.push_back(SKeyMap(XK_KP_5, KEY_KEY_5));
KeyMap.push_back(SKeyMap(XK_KP_6, KEY_KEY_6));
KeyMap.push_back(SKeyMap(XK_KP_7, KEY_KEY_7));
KeyMap.push_back(SKeyMap(XK_KP_8, KEY_KEY_8));
KeyMap.push_back(SKeyMap(XK_KP_9, KEY_KEY_9));
KeyMap.push_back(SKeyMap(XK_F1, KEY_F1));
KeyMap.push_back(SKeyMap(XK_F2, KEY_F2));
KeyMap.push_back(SKeyMap(XK_F3, KEY_F3));
KeyMap.push_back(SKeyMap(XK_F4, KEY_F4));
KeyMap.push_back(SKeyMap(XK_F5, KEY_F5));
KeyMap.push_back(SKeyMap(XK_F6, KEY_F6));
KeyMap.push_back(SKeyMap(XK_F7, KEY_F7));
KeyMap.push_back(SKeyMap(XK_F8, KEY_F8));
KeyMap.push_back(SKeyMap(XK_F9, KEY_F9));
KeyMap.push_back(SKeyMap(XK_F10, KEY_F10));
KeyMap.push_back(SKeyMap(XK_F11, KEY_F11));
KeyMap.push_back(SKeyMap(XK_F12, KEY_F12));
KeyMap.push_back(SKeyMap(XK_Shift_L, KEY_LSHIFT));
KeyMap.push_back(SKeyMap(XK_Shift_R, KEY_RSHIFT));
KeyMap.push_back(SKeyMap(XK_Control_L, KEY_LCONTROL));
KeyMap.push_back(SKeyMap(XK_Control_R, KEY_RCONTROL));
KeyMap.push_back(SKeyMap(XK_Caps_Lock, KEY_CAPITAL));
KeyMap.push_back(SKeyMap(XK_Shift_Lock, KEY_CAPITAL));
KeyMap.push_back(SKeyMap(XK_Meta_L, KEY_LWIN));
KeyMap.push_back(SKeyMap(XK_Meta_R, KEY_RWIN));
KeyMap.push_back(SKeyMap(XK_Alt_L, KEY_LMENU));
KeyMap.push_back(SKeyMap(XK_Alt_R, KEY_RMENU));
KeyMap.push_back(SKeyMap(XK_ISO_Level3_Shift, KEY_RMENU));
KeyMap.push_back(SKeyMap(XK_Menu, KEY_MENU));
KeyMap.push_back(SKeyMap(XK_space, KEY_SPACE));
KeyMap.push_back(SKeyMap(XK_exclam, 0)); //?
KeyMap.push_back(SKeyMap(XK_quotedbl, 0)); //?
KeyMap.push_back(SKeyMap(XK_section, 0)); //?
KeyMap.push_back(SKeyMap(XK_numbersign, 0)); //?
KeyMap.push_back(SKeyMap(XK_dollar, 0)); //?
KeyMap.push_back(SKeyMap(XK_percent, 0)); //?
KeyMap.push_back(SKeyMap(XK_ampersand, 0)); //?
KeyMap.push_back(SKeyMap(XK_apostrophe, 0)); //?
KeyMap.push_back(SKeyMap(XK_parenleft, 0)); //?
KeyMap.push_back(SKeyMap(XK_parenright, 0)); //?
KeyMap.push_back(SKeyMap(XK_asterisk, 0)); //?
KeyMap.push_back(SKeyMap(XK_plus, KEY_PLUS)); //?
KeyMap.push_back(SKeyMap(XK_comma, KEY_COMMA)); //?
KeyMap.push_back(SKeyMap(XK_minus, KEY_MINUS)); //?
KeyMap.push_back(SKeyMap(XK_period, KEY_PERIOD)); //?
KeyMap.push_back(SKeyMap(XK_slash, 0)); //?
KeyMap.push_back(SKeyMap(XK_0, KEY_KEY_0));
KeyMap.push_back(SKeyMap(XK_1, KEY_KEY_1));
KeyMap.push_back(SKeyMap(XK_2, KEY_KEY_2));
KeyMap.push_back(SKeyMap(XK_3, KEY_KEY_3));
KeyMap.push_back(SKeyMap(XK_4, KEY_KEY_4));
KeyMap.push_back(SKeyMap(XK_5, KEY_KEY_5));
KeyMap.push_back(SKeyMap(XK_6, KEY_KEY_6));
KeyMap.push_back(SKeyMap(XK_7, KEY_KEY_7));
KeyMap.push_back(SKeyMap(XK_8, KEY_KEY_8));
KeyMap.push_back(SKeyMap(XK_9, KEY_KEY_9));
KeyMap.push_back(SKeyMap(XK_colon, 0)); //?
KeyMap.push_back(SKeyMap(XK_semicolon, 0)); //?
KeyMap.push_back(SKeyMap(XK_less, 0)); //?
KeyMap.push_back(SKeyMap(XK_equal, 0)); //?
KeyMap.push_back(SKeyMap(XK_greater, 0)); //?
KeyMap.push_back(SKeyMap(XK_question, 0)); //?
KeyMap.push_back(SKeyMap(XK_at, 0)); //?
KeyMap.push_back(SKeyMap(XK_mu, 0)); //?
KeyMap.push_back(SKeyMap(XK_EuroSign, 0)); //?
KeyMap.push_back(SKeyMap(XK_A, KEY_KEY_A));
KeyMap.push_back(SKeyMap(XK_B, KEY_KEY_B));
KeyMap.push_back(SKeyMap(XK_C, KEY_KEY_C));
KeyMap.push_back(SKeyMap(XK_D, KEY_KEY_D));
KeyMap.push_back(SKeyMap(XK_E, KEY_KEY_E));
KeyMap.push_back(SKeyMap(XK_F, KEY_KEY_F));
KeyMap.push_back(SKeyMap(XK_G, KEY_KEY_G));
KeyMap.push_back(SKeyMap(XK_H, KEY_KEY_H));
KeyMap.push_back(SKeyMap(XK_I, KEY_KEY_I));
KeyMap.push_back(SKeyMap(XK_J, KEY_KEY_J));
KeyMap.push_back(SKeyMap(XK_K, KEY_KEY_K));
KeyMap.push_back(SKeyMap(XK_L, KEY_KEY_L));
KeyMap.push_back(SKeyMap(XK_M, KEY_KEY_M));
KeyMap.push_back(SKeyMap(XK_N, KEY_KEY_N));
KeyMap.push_back(SKeyMap(XK_O, KEY_KEY_O));
KeyMap.push_back(SKeyMap(XK_P, KEY_KEY_P));
KeyMap.push_back(SKeyMap(XK_Q, KEY_KEY_Q));
KeyMap.push_back(SKeyMap(XK_R, KEY_KEY_R));
KeyMap.push_back(SKeyMap(XK_S, KEY_KEY_S));
KeyMap.push_back(SKeyMap(XK_T, KEY_KEY_T));
KeyMap.push_back(SKeyMap(XK_U, KEY_KEY_U));
KeyMap.push_back(SKeyMap(XK_V, KEY_KEY_V));
KeyMap.push_back(SKeyMap(XK_W, KEY_KEY_W));
KeyMap.push_back(SKeyMap(XK_X, KEY_KEY_X));
KeyMap.push_back(SKeyMap(XK_Y, KEY_KEY_Y));
KeyMap.push_back(SKeyMap(XK_Z, KEY_KEY_Z));
KeyMap.push_back(SKeyMap(XK_Adiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_Odiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_Udiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_bracketleft, 0)); //?
KeyMap.push_back(SKeyMap(XK_backslash, 0)); //?
KeyMap.push_back(SKeyMap(XK_bracketright, 0)); //?
KeyMap.push_back(SKeyMap(XK_asciicircum, 0)); //?
KeyMap.push_back(SKeyMap(XK_degree, 0)); //?
KeyMap.push_back(SKeyMap(XK_underscore, 0)); //?
KeyMap.push_back(SKeyMap(XK_grave, 0)); //?
KeyMap.push_back(SKeyMap(XK_acute, 0)); //?
KeyMap.push_back(SKeyMap(XK_quoteleft, 0)); //?
KeyMap.push_back(SKeyMap(XK_a, KEY_KEY_A));
KeyMap.push_back(SKeyMap(XK_b, KEY_KEY_B));
KeyMap.push_back(SKeyMap(XK_c, KEY_KEY_C));
KeyMap.push_back(SKeyMap(XK_d, KEY_KEY_D));
KeyMap.push_back(SKeyMap(XK_e, KEY_KEY_E));
KeyMap.push_back(SKeyMap(XK_f, KEY_KEY_F));
KeyMap.push_back(SKeyMap(XK_g, KEY_KEY_G));
KeyMap.push_back(SKeyMap(XK_h, KEY_KEY_H));
KeyMap.push_back(SKeyMap(XK_i, KEY_KEY_I));
KeyMap.push_back(SKeyMap(XK_j, KEY_KEY_J));
KeyMap.push_back(SKeyMap(XK_k, KEY_KEY_K));
KeyMap.push_back(SKeyMap(XK_l, KEY_KEY_L));
KeyMap.push_back(SKeyMap(XK_m, KEY_KEY_M));
KeyMap.push_back(SKeyMap(XK_n, KEY_KEY_N));
KeyMap.push_back(SKeyMap(XK_o, KEY_KEY_O));
KeyMap.push_back(SKeyMap(XK_p, KEY_KEY_P));
KeyMap.push_back(SKeyMap(XK_q, KEY_KEY_Q));
KeyMap.push_back(SKeyMap(XK_r, KEY_KEY_R));
KeyMap.push_back(SKeyMap(XK_s, KEY_KEY_S));
KeyMap.push_back(SKeyMap(XK_t, KEY_KEY_T));
KeyMap.push_back(SKeyMap(XK_u, KEY_KEY_U));
KeyMap.push_back(SKeyMap(XK_v, KEY_KEY_V));
KeyMap.push_back(SKeyMap(XK_w, KEY_KEY_W));
KeyMap.push_back(SKeyMap(XK_x, KEY_KEY_X));
KeyMap.push_back(SKeyMap(XK_y, KEY_KEY_Y));
KeyMap.push_back(SKeyMap(XK_z, KEY_KEY_Z));
KeyMap.push_back(SKeyMap(XK_ssharp, 0)); //?
KeyMap.push_back(SKeyMap(XK_adiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_odiaeresis, 0)); //?
KeyMap.push_back(SKeyMap(XK_udiaeresis, 0)); //?
KeyMap.sort();
#endif
}
bool CIrrDeviceLinux::activateJoysticks(core::array<SJoystickInfo> & joystickInfo)
{
#if defined (_IRR_COMPILE_WITH_JOYSTICK_EVENTS_)
joystickInfo.clear();
u32 joystick;
for(joystick = 0; joystick < 32; ++joystick)
{
// The joystick device could be here...
core::stringc devName = "/dev/js";
devName += joystick;
SJoystickInfo returnInfo;
JoystickInfo info;
info.fd = open(devName.c_str(), O_RDONLY);
if(-1 == info.fd)
{
// ...but Ubuntu and possibly other distros
// create the devices in /dev/input
devName = "/dev/input/js";
devName += joystick;
info.fd = open(devName.c_str(), O_RDONLY);
if(-1 == info.fd)
{
// and BSD here
devName = "/dev/joy";
devName += joystick;
info.fd = open(devName.c_str(), O_RDONLY);
}
}
if(-1 == info.fd)
continue;
#ifdef __FREE_BSD_
info.axes=2;
info.buttons=2;
#else
ioctl( info.fd, JSIOCGAXES, &(info.axes) );
ioctl( info.fd, JSIOCGBUTTONS, &(info.buttons) );
fcntl( info.fd, F_SETFL, O_NONBLOCK );
#endif
(void)memset(&info.persistentData, 0, sizeof(info.persistentData));
info.persistentData.EventType = irr::EET_JOYSTICK_INPUT_EVENT;
info.persistentData.JoystickEvent.Joystick = ActiveJoysticks.size();
// There's no obvious way to determine which (if any) axes represent a POV
// hat, so we'll just set it to "not used" and forget about it.
info.persistentData.JoystickEvent.POV = 65535;
ActiveJoysticks.push_back(info);
returnInfo.Joystick = joystick;
returnInfo.PovHat = SJoystickInfo::POV_HAT_UNKNOWN;
returnInfo.Axes = info.axes;
returnInfo.Buttons = info.buttons;
#ifndef __FREE_BSD_
char name[80];
ioctl( info.fd, JSIOCGNAME(80), name);
returnInfo.Name = name;
#endif
joystickInfo.push_back(returnInfo);
}
for(joystick = 0; joystick < joystickInfo.size(); ++joystick)
{
char logString[256];
(void)sprintf(logString, "Found joystick %u, %u axes, %u buttons '%s'",
joystick, joystickInfo[joystick].Axes,
joystickInfo[joystick].Buttons, joystickInfo[joystick].Name.c_str());
os::Printer::log(logString, ELL_INFORMATION);
}
|
paupawsan/Irrlicht
|
14b44662446f399f0a387643871189cb20a14fd7
|
Adapt declaration to method signature.
|
diff --git a/source/Irrlicht/COpenGLExtensionHandler.h b/source/Irrlicht/COpenGLExtensionHandler.h
index 01c827e..d8083fa 100644
--- a/source/Irrlicht/COpenGLExtensionHandler.h
+++ b/source/Irrlicht/COpenGLExtensionHandler.h
@@ -398,1025 +398,1025 @@ static const char* const OpenGLFeatureStrings[] = {
"GL_SGIX_resample",
"GL_SGIX_scalebias_hint",
"GL_SGIX_shadow",
"GL_SGIX_shadow_ambient",
"GL_SGIX_sprite",
"GL_SGIX_subsample",
"GL_SGIX_tag_sample_buffer",
"GL_SGIX_texture_add_env",
"GL_SGIX_texture_coordinate_clamp",
"GL_SGIX_texture_lod_bias",
"GL_SGIX_texture_multi_buffer",
"GL_SGIX_texture_scale_bias",
"GL_SGIX_texture_select",
"GL_SGIX_vertex_preclip",
"GL_SGIX_ycrcb",
"GL_SGIX_ycrcba",
"GL_SGIX_ycrcb_subsample",
"GL_SUN_convolution_border_modes",
"GL_SUN_global_alpha",
"GL_SUN_mesh_array",
"GL_SUN_slice_accum",
"GL_SUN_triangle_list",
"GL_SUN_vertex",
"GL_SUNX_constant_data",
"GL_WIN_phong_shading",
"GL_WIN_specular_fog"
};
class COpenGLExtensionHandler
{
public:
enum EOpenGLFeatures {
IRR_3DFX_multisample = 0,
IRR_3DFX_tbuffer,
IRR_3DFX_texture_compression_FXT1,
IRR_AMD_draw_buffers_blend,
IRR_AMD_performance_monitor,
IRR_AMD_texture_texture4,
IRR_AMD_vertex_shader_tesselator,
IRR_APPLE_aux_depth_stencil,
IRR_APPLE_client_storage,
IRR_APPLE_element_array,
IRR_APPLE_fence,
IRR_APPLE_float_pixels,
IRR_APPLE_flush_buffer_range,
IRR_APPLE_object_purgeable,
IRR_APPLE_rgb_422,
IRR_APPLE_row_bytes,
IRR_APPLE_specular_vector,
IRR_APPLE_texture_range,
IRR_APPLE_transform_hint,
IRR_APPLE_vertex_array_object,
IRR_APPLE_vertex_array_range,
IRR_APPLE_vertex_program_evaluators,
IRR_APPLE_ycbcr_422,
IRR_ARB_color_buffer_float,
IRR_ARB_compatibility,
IRR_ARB_copy_buffer,
IRR_ARB_depth_buffer_float,
IRR_ARB_depth_clamp,
IRR_ARB_depth_texture,
IRR_ARB_draw_buffers,
IRR_ARB_draw_buffers_blend,
IRR_ARB_draw_elements_base_vertex,
IRR_ARB_draw_instanced,
IRR_ARB_fragment_coord_conventions,
IRR_ARB_fragment_program,
IRR_ARB_fragment_program_shadow,
IRR_ARB_fragment_shader,
IRR_ARB_framebuffer_object,
IRR_ARB_framebuffer_sRGB,
IRR_ARB_geometry_shader4,
IRR_ARB_half_float_pixel,
IRR_ARB_half_float_vertex,
IRR_ARB_imaging,
IRR_ARB_instanced_arrays,
IRR_ARB_map_buffer_range,
IRR_ARB_matrix_palette,
IRR_ARB_multisample,
IRR_ARB_multitexture,
IRR_ARB_occlusion_query,
IRR_ARB_pixel_buffer_object,
IRR_ARB_point_parameters,
IRR_ARB_point_sprite,
IRR_ARB_provoking_vertex,
IRR_ARB_sample_shading,
IRR_ARB_seamless_cube_map,
IRR_ARB_shader_objects,
IRR_ARB_shader_texture_lod,
IRR_ARB_shading_language_100,
IRR_ARB_shadow,
IRR_ARB_shadow_ambient,
IRR_ARB_sync,
IRR_ARB_texture_border_clamp,
IRR_ARB_texture_buffer_object,
IRR_ARB_texture_compression,
IRR_ARB_texture_compression_rgtc,
IRR_ARB_texture_cube_map,
IRR_ARB_texture_cube_map_array,
IRR_ARB_texture_env_add,
IRR_ARB_texture_env_combine,
IRR_ARB_texture_env_crossbar,
IRR_ARB_texture_env_dot3,
IRR_ARB_texture_float,
IRR_ARB_texture_gather,
IRR_ARB_texture_mirrored_repeat,
IRR_ARB_texture_multisample,
IRR_ARB_texture_non_power_of_two,
IRR_ARB_texture_query_lod,
IRR_ARB_texture_rectangle,
IRR_ARB_texture_rg,
IRR_ARB_transpose_matrix,
IRR_ARB_uniform_buffer_object,
IRR_ARB_vertex_array_bgra,
IRR_ARB_vertex_array_object,
IRR_ARB_vertex_blend,
IRR_ARB_vertex_buffer_object,
IRR_ARB_vertex_program,
IRR_ARB_vertex_shader,
IRR_ARB_window_pos,
IRR_ATI_draw_buffers,
IRR_ATI_element_array,
IRR_ATI_envmap_bumpmap,
IRR_ATI_fragment_shader,
IRR_ATI_map_object_buffer,
IRR_ATI_meminfo,
IRR_ATI_pixel_format_float,
IRR_ATI_pn_triangles,
IRR_ATI_separate_stencil,
IRR_ATI_text_fragment_shader,
IRR_ATI_texture_env_combine3,
IRR_ATI_texture_float,
IRR_ATI_texture_mirror_once,
IRR_ATI_vertex_array_object,
IRR_ATI_vertex_attrib_array_object,
IRR_ATI_vertex_streams,
IRR_EXT_422_pixels,
IRR_EXT_abgr,
IRR_EXT_bgra,
IRR_EXT_bindable_uniform,
IRR_EXT_blend_color,
IRR_EXT_blend_equation_separate,
IRR_EXT_blend_func_separate,
IRR_EXT_blend_logic_op,
IRR_EXT_blend_minmax,
IRR_EXT_blend_subtract,
IRR_EXT_clip_volume_hint,
IRR_EXT_cmyka,
IRR_EXT_color_subtable,
IRR_EXT_compiled_vertex_array,
IRR_EXT_convolution,
IRR_EXT_coordinate_frame,
IRR_EXT_copy_texture,
IRR_EXT_cull_vertex,
IRR_EXT_depth_bounds_test,
IRR_EXT_direct_state_access,
IRR_EXT_draw_buffers2,
IRR_EXT_draw_instanced,
IRR_EXT_draw_range_elements,
IRR_EXT_fog_coord,
IRR_EXT_framebuffer_blit,
IRR_EXT_framebuffer_multisample,
IRR_EXT_framebuffer_object,
IRR_EXT_framebuffer_sRGB,
IRR_EXT_geometry_shader4,
IRR_EXT_gpu_program_parameters,
IRR_EXT_gpu_shader4,
IRR_EXT_histogram,
IRR_EXT_index_array_formats,
IRR_EXT_index_func,
IRR_EXT_index_material,
IRR_EXT_index_texture,
IRR_EXT_light_texture,
IRR_EXT_misc_attribute,
IRR_EXT_multi_draw_arrays,
IRR_EXT_multisample,
IRR_EXT_packed_depth_stencil,
IRR_EXT_packed_float,
IRR_EXT_packed_pixels,
IRR_EXT_paletted_texture,
IRR_EXT_pixel_buffer_object,
IRR_EXT_pixel_transform,
IRR_EXT_pixel_transform_color_table,
IRR_EXT_point_parameters,
IRR_EXT_polygon_offset,
IRR_EXT_provoking_vertex,
IRR_EXT_rescale_normal,
IRR_EXT_secondary_color,
IRR_EXT_separate_shader_objects,
IRR_EXT_separate_specular_color,
IRR_EXT_shadow_funcs,
IRR_EXT_shared_texture_palette,
IRR_EXT_stencil_clear_tag,
IRR_EXT_stencil_two_side,
IRR_EXT_stencil_wrap,
IRR_EXT_subtexture,
IRR_EXT_texture,
IRR_EXT_texture3D,
IRR_EXT_texture_array,
IRR_EXT_texture_buffer_object,
IRR_EXT_texture_compression_latc,
IRR_EXT_texture_compression_rgtc,
IRR_EXT_texture_compression_s3tc,
IRR_EXT_texture_cube_map,
IRR_EXT_texture_env_add,
IRR_EXT_texture_env_combine,
IRR_EXT_texture_env_dot3,
IRR_EXT_texture_filter_anisotropic,
IRR_EXT_texture_integer,
IRR_EXT_texture_lod_bias,
IRR_EXT_texture_mirror_clamp,
IRR_EXT_texture_object,
IRR_EXT_texture_perturb_normal,
IRR_EXT_texture_shared_exponent,
IRR_EXT_texture_snorm,
IRR_EXT_texture_sRGB,
IRR_EXT_texture_swizzle,
IRR_EXT_timer_query,
IRR_EXT_transform_feedback,
IRR_EXT_vertex_array,
IRR_EXT_vertex_array_bgra,
IRR_EXT_vertex_shader,
IRR_EXT_vertex_weighting,
IRR_FfdMaskSGIX,
IRR_GREMEDY_frame_terminator,
IRR_GREMEDY_string_marker,
IRR_HP_convolution_border_modes,
IRR_HP_image_transform,
IRR_HP_occlusion_test,
IRR_HP_texture_lighting,
IRR_IBM_cull_vertex,
IRR_IBM_multimode_draw_arrays,
IRR_IBM_rasterpos_clip,
IRR_IBM_texture_mirrored_repeat,
IRR_IBM_vertex_array_lists,
IRR_INGR_blend_func_separate,
IRR_INGR_color_clamp,
IRR_INGR_interlace_read,
IRR_INGR_palette_buffer,
IRR_INTEL_parallel_arrays,
IRR_INTEL_texture_scissor,
IRR_MESA_pack_invert,
IRR_MESA_resize_buffers,
IRR_MESA_window_pos,
IRR_MESAX_texture_stack,
IRR_MESA_ycbcr_texture,
IRR_NV_blend_square,
IRR_NV_conditional_render,
IRR_NV_copy_depth_to_color,
IRR_NV_copy_image,
IRR_NV_depth_buffer_float,
IRR_NV_depth_clamp,
IRR_NV_evaluators,
IRR_NV_explicit_multisample,
IRR_NV_fence,
IRR_NV_float_buffer,
IRR_NV_fog_distance,
IRR_NV_fragment_program,
IRR_NV_fragment_program2,
IRR_NV_fragment_program4,
IRR_NV_fragment_program_option,
IRR_NV_framebuffer_multisample_coverage,
IRR_NV_geometry_program4,
IRR_NV_geometry_shader4,
IRR_NV_gpu_program4,
IRR_NV_half_float,
IRR_NV_light_max_exponent,
IRR_NV_multisample_filter_hint,
IRR_NV_occlusion_query,
IRR_NV_packed_depth_stencil,
IRR_NV_parameter_buffer_object,
IRR_NV_parameter_buffer_object2,
IRR_NV_pixel_data_range,
IRR_NV_point_sprite,
IRR_NV_present_video,
IRR_NV_primitive_restart,
IRR_NV_register_combiners,
IRR_NV_register_combiners2,
IRR_NV_shader_buffer_load,
IRR_NV_texgen_emboss,
IRR_NV_texgen_reflection,
IRR_NV_texture_barrier,
IRR_NV_texture_compression_vtc,
IRR_NV_texture_env_combine4,
IRR_NV_texture_expand_normal,
IRR_NV_texture_rectangle,
IRR_NV_texture_shader,
IRR_NV_texture_shader2,
IRR_NV_texture_shader3,
IRR_NV_transform_feedback,
IRR_NV_transform_feedback2,
IRR_NV_vertex_array_range,
IRR_NV_vertex_array_range2,
IRR_NV_vertex_buffer_unified_memory,
IRR_NV_vertex_program,
IRR_NV_vertex_program1_1,
IRR_NV_vertex_program2,
IRR_NV_vertex_program2_option,
IRR_NV_vertex_program3,
IRR_NV_vertex_program4,
IRR_NV_video_capture,
IRR_OES_read_format,
IRR_OML_interlace,
IRR_OML_resample,
IRR_OML_subsample,
IRR_PGI_misc_hints,
IRR_PGI_vertex_hints,
IRR_REND_screen_coordinates,
IRR_S3_s3tc,
IRR_SGI_color_matrix,
IRR_SGI_color_table,
IRR_SGI_depth_pass_instrument,
IRR_SGIS_detail_texture,
IRR_SGIS_fog_function,
IRR_SGIS_generate_mipmap,
IRR_SGIS_multisample,
IRR_SGIS_pixel_texture,
IRR_SGIS_point_line_texgen,
IRR_SGIS_point_parameters,
IRR_SGIS_sharpen_texture,
IRR_SGIS_texture4D,
IRR_SGIS_texture_border_clamp,
IRR_SGIS_texture_color_mask,
IRR_SGIS_texture_edge_clamp,
IRR_SGIS_texture_filter4,
IRR_SGIS_texture_lod,
IRR_SGIS_texture_select,
IRR_SGI_texture_color_table,
IRR_SGIX_async,
IRR_SGIX_async_histogram,
IRR_SGIX_async_pixel,
IRR_SGIX_blend_alpha_minmax,
IRR_SGIX_calligraphic_fragment,
IRR_SGIX_clipmap,
IRR_SGIX_convolution_accuracy,
IRR_SGIX_depth_pass_instrument,
IRR_SGIX_depth_texture,
IRR_SGIX_flush_raster,
IRR_SGIX_fog_offset,
IRR_SGIX_fog_scale,
IRR_SGIX_fragment_lighting,
IRR_SGIX_framezoom,
IRR_SGIX_igloo_interface,
IRR_SGIX_impact_pixel_texture,
IRR_SGIX_instruments,
IRR_SGIX_interlace,
IRR_SGIX_ir_instrument1,
IRR_SGIX_list_priority,
IRR_SGIX_pixel_texture,
IRR_SGIX_pixel_tiles,
IRR_SGIX_polynomial_ffd,
IRR_SGIX_reference_plane,
IRR_SGIX_resample,
IRR_SGIX_scalebias_hint,
IRR_SGIX_shadow,
IRR_SGIX_shadow_ambient,
IRR_SGIX_sprite,
IRR_SGIX_subsample,
IRR_SGIX_tag_sample_buffer,
IRR_SGIX_texture_add_env,
IRR_SGIX_texture_coordinate_clamp,
IRR_SGIX_texture_lod_bias,
IRR_SGIX_texture_multi_buffer,
IRR_SGIX_texture_scale_bias,
IRR_SGIX_texture_select,
IRR_SGIX_vertex_preclip,
IRR_SGIX_ycrcb,
IRR_SGIX_ycrcba,
IRR_SGIX_ycrcb_subsample,
IRR_SUN_convolution_border_modes,
IRR_SUN_global_alpha,
IRR_SUN_mesh_array,
IRR_SUN_slice_accum,
IRR_SUN_triangle_list,
IRR_SUN_vertex,
IRR_SUNX_constant_data,
IRR_WIN_phong_shading,
IRR_WIN_specular_fog,
IRR_OpenGL_Feature_Count
};
// constructor
COpenGLExtensionHandler();
// deferred initialization
void initExtensions(bool stencilBuffer);
//! queries the features of the driver, returns true if feature is available
bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const;
//! queries the features of the driver, returns true if feature is available
bool queryOpenGLFeature(EOpenGLFeatures feature) const
{
return FeatureAvailable[feature];
}
//! show all features with availablity
void dump() const;
// Some variables for properties
bool StencilBuffer;
bool MultiTextureExtension;
bool TextureCompressionExtension;
// Some non-boolean properties
//! Maxmimum texture layers supported by the fixed pipeline
u8 MaxTextureUnits;
//! Maximum hardware lights supported
u8 MaxLights;
//! Maximal Anisotropy
u8 MaxAnisotropy;
//! Number of user clipplanes
u8 MaxUserClipPlanes;
//! Number of auxiliary buffers
u8 MaxAuxBuffers;
//! Number of rendertargets available as MRTs
u8 MaxMultipleRenderTargets;
//! Optimal number of indices per meshbuffer
u32 MaxIndices;
//! Maximal texture dimension
u32 MaxTextureSize;
//! Maximal vertices handled by geometry shaders
u32 MaxGeometryVerticesOut;
//! Maximal LOD Bias
f32 MaxTextureLODBias;
//! Minimal and maximal supported thickness for lines without smoothing
GLfloat DimAliasedLine[2];
//! Minimal and maximal supported thickness for points without smoothing
GLfloat DimAliasedPoint[2];
//! Minimal and maximal supported thickness for lines with smoothing
GLfloat DimSmoothedLine[2];
//! Minimal and maximal supported thickness for points with smoothing
GLfloat DimSmoothedPoint[2];
//! OpenGL version as Integer: 100*Major+Minor, i.e. 2.1 becomes 201
u16 Version;
//! GLSL version as Integer: 100*Major+Minor
u16 ShaderLanguageVersion;
// public access to the (loaded) extensions.
// general functions
void extGlActiveTexture(GLenum texture);
void extGlClientActiveTexture(GLenum texture);
void extGlPointParameterf(GLint loc, GLfloat f);
void extGlPointParameterfv(GLint loc, const GLfloat *v);
void extGlStencilFuncSeparate (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);
void extGlStencilOpSeparate (GLenum face, GLenum fail, GLenum zfail, GLenum zpass);
void extGlCompressedTexImage2D(GLenum target, GLint level,
GLenum internalformat, GLsizei width, GLsizei height,
GLint border, GLsizei imageSize, const void* data);
// shader programming
void extGlGenPrograms(GLsizei n, GLuint *programs);
void extGlBindProgram(GLenum target, GLuint program);
void extGlProgramString(GLenum target, GLenum format, GLsizei len, const GLvoid *string);
void extGlLoadProgram(GLenum target, GLuint id, GLsizei len, const GLubyte *string);
void extGlDeletePrograms(GLsizei n, const GLuint *programs);
void extGlProgramLocalParameter4fv(GLenum, GLuint, const GLfloat *);
GLhandleARB extGlCreateShaderObject(GLenum shaderType);
void extGlShaderSource(GLhandleARB shader, int numOfStrings, const char **strings, int *lenOfStrings);
void extGlCompileShader(GLhandleARB shader);
GLhandleARB extGlCreateProgramObject(void);
void extGlAttachObject(GLhandleARB program, GLhandleARB shader);
void extGlLinkProgram(GLhandleARB program);
void extGlUseProgramObject(GLhandleARB prog);
void extGlDeleteObject(GLhandleARB object);
void extGlGetInfoLog(GLhandleARB object, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);
void extGlGetObjectParameteriv(GLhandleARB object, GLenum type, int *param);
GLint extGlGetUniformLocation(GLhandleARB program, const char *name);
void extGlUniform4fv(GLint location, GLsizei count, const GLfloat *v);
void extGlUniform1iv(GLint loc, GLsizei count, const GLint *v);
void extGlUniform1fv(GLint loc, GLsizei count, const GLfloat *v);
void extGlUniform2fv(GLint loc, GLsizei count, const GLfloat *v);
void extGlUniform3fv(GLint loc, GLsizei count, const GLfloat *v);
void extGlUniformMatrix2fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v);
void extGlUniformMatrix3fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v);
void extGlUniformMatrix4fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v);
void extGlGetActiveUniform(GLhandleARB program, GLuint index, GLsizei maxlength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
// framebuffer objects
void extGlBindFramebuffer(GLenum target, GLuint framebuffer);
void extGlDeleteFramebuffers(GLsizei n, const GLuint *framebuffers);
void extGlGenFramebuffers(GLsizei n, GLuint *framebuffers);
GLenum extGlCheckFramebufferStatus(GLenum target);
void extGlFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
void extGlBindRenderbuffer(GLenum target, GLuint renderbuffer);
void extGlDeleteRenderbuffers(GLsizei n, const GLuint *renderbuffers);
void extGlGenRenderbuffers(GLsizei n, GLuint *renderbuffers);
void extGlRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
void extGlFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
void extGlActiveStencilFace(GLenum face);
void extGlDrawBuffers(GLsizei n, const GLenum *bufs);
// vertex buffer object
void extGlGenBuffers(GLsizei n, GLuint *buffers);
void extGlBindBuffer(GLenum target, GLuint buffer);
void extGlBufferData(GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage);
void extGlDeleteBuffers(GLsizei n, const GLuint *buffers);
void extGlBufferSubData (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data);
void extGlGetBufferSubData (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data);
void *extGlMapBuffer (GLenum target, GLenum access);
GLboolean extGlUnmapBuffer (GLenum target);
GLboolean extGlIsBuffer (GLuint buffer);
void extGlGetBufferParameteriv (GLenum target, GLenum pname, GLint *params);
void extGlGetBufferPointerv (GLenum target, GLenum pname, GLvoid **params);
void extGlProvokingVertex(GLenum mode);
void extGlColorMaskIndexed(GLuint buf, GLboolean r, GLboolean g, GLboolean b, GLboolean a);
void extGlEnableIndexed(GLenum target, GLuint index);
void extGlDisableIndexed(GLenum target, GLuint index);
void extGlBlendFuncIndexed(GLuint buf, GLenum src, GLenum dst);
- void extGlProgramParameteri(GLhandleARB program, GLenum pname, GLint value);
+ void extGlProgramParameteri(GLuint program, GLenum pname, GLint value);
protected:
// the global feature array
bool FeatureAvailable[IRR_OpenGL_Feature_Count];
#if defined(_IRR_OPENGL_USE_EXTPOINTER_)
PFNGLACTIVETEXTUREARBPROC pGlActiveTextureARB;
PFNGLCLIENTACTIVETEXTUREARBPROC pGlClientActiveTextureARB;
PFNGLGENPROGRAMSARBPROC pGlGenProgramsARB;
PFNGLGENPROGRAMSNVPROC pGlGenProgramsNV;
PFNGLBINDPROGRAMARBPROC pGlBindProgramARB;
PFNGLBINDPROGRAMNVPROC pGlBindProgramNV;
PFNGLDELETEPROGRAMSARBPROC pGlDeleteProgramsARB;
PFNGLDELETEPROGRAMSNVPROC pGlDeleteProgramsNV;
PFNGLPROGRAMSTRINGARBPROC pGlProgramStringARB;
PFNGLLOADPROGRAMNVPROC pGlLoadProgramNV;
PFNGLPROGRAMLOCALPARAMETER4FVARBPROC pGlProgramLocalParameter4fvARB;
PFNGLCREATESHADEROBJECTARBPROC pGlCreateShaderObjectARB;
PFNGLSHADERSOURCEARBPROC pGlShaderSourceARB;
PFNGLCOMPILESHADERARBPROC pGlCompileShaderARB;
PFNGLCREATEPROGRAMOBJECTARBPROC pGlCreateProgramObjectARB;
PFNGLATTACHOBJECTARBPROC pGlAttachObjectARB;
PFNGLLINKPROGRAMARBPROC pGlLinkProgramARB;
PFNGLUSEPROGRAMOBJECTARBPROC pGlUseProgramObjectARB;
PFNGLDELETEOBJECTARBPROC pGlDeleteObjectARB;
PFNGLGETINFOLOGARBPROC pGlGetInfoLogARB;
PFNGLGETOBJECTPARAMETERIVARBPROC pGlGetObjectParameterivARB;
PFNGLGETUNIFORMLOCATIONARBPROC pGlGetUniformLocationARB;
PFNGLUNIFORM1IVARBPROC pGlUniform1ivARB;
PFNGLUNIFORM1FVARBPROC pGlUniform1fvARB;
PFNGLUNIFORM2FVARBPROC pGlUniform2fvARB;
PFNGLUNIFORM3FVARBPROC pGlUniform3fvARB;
PFNGLUNIFORM4FVARBPROC pGlUniform4fvARB;
PFNGLUNIFORMMATRIX2FVARBPROC pGlUniformMatrix2fvARB;
PFNGLUNIFORMMATRIX3FVARBPROC pGlUniformMatrix3fvARB;
PFNGLUNIFORMMATRIX4FVARBPROC pGlUniformMatrix4fvARB;
PFNGLGETACTIVEUNIFORMARBPROC pGlGetActiveUniformARB;
PFNGLPOINTPARAMETERFARBPROC pGlPointParameterfARB;
PFNGLPOINTPARAMETERFVARBPROC pGlPointParameterfvARB;
PFNGLSTENCILFUNCSEPARATEPROC pGlStencilFuncSeparate;
PFNGLSTENCILOPSEPARATEPROC pGlStencilOpSeparate;
PFNGLSTENCILFUNCSEPARATEATIPROC pGlStencilFuncSeparateATI;
PFNGLSTENCILOPSEPARATEATIPROC pGlStencilOpSeparateATI;
PFNGLCOMPRESSEDTEXIMAGE2DPROC pGlCompressedTexImage2D;
#if defined(_IRR_LINUX_PLATFORM_) && defined(GLX_SGI_swap_control)
PFNGLXSWAPINTERVALSGIPROC glxSwapIntervalSGI;
#endif
PFNGLBINDFRAMEBUFFEREXTPROC pGlBindFramebufferEXT;
PFNGLDELETEFRAMEBUFFERSEXTPROC pGlDeleteFramebuffersEXT;
PFNGLGENFRAMEBUFFERSEXTPROC pGlGenFramebuffersEXT;
PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC pGlCheckFramebufferStatusEXT;
PFNGLFRAMEBUFFERTEXTURE2DEXTPROC pGlFramebufferTexture2DEXT;
PFNGLBINDRENDERBUFFEREXTPROC pGlBindRenderbufferEXT;
PFNGLDELETERENDERBUFFERSEXTPROC pGlDeleteRenderbuffersEXT;
PFNGLGENRENDERBUFFERSEXTPROC pGlGenRenderbuffersEXT;
PFNGLRENDERBUFFERSTORAGEEXTPROC pGlRenderbufferStorageEXT;
PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC pGlFramebufferRenderbufferEXT;
PFNGLACTIVESTENCILFACEEXTPROC pGlActiveStencilFaceEXT;
PFNGLDRAWBUFFERSARBPROC pGlDrawBuffersARB;
PFNGLDRAWBUFFERSATIPROC pGlDrawBuffersATI;
PFNGLGENBUFFERSARBPROC pGlGenBuffersARB;
PFNGLBINDBUFFERARBPROC pGlBindBufferARB;
PFNGLBUFFERDATAARBPROC pGlBufferDataARB;
PFNGLDELETEBUFFERSARBPROC pGlDeleteBuffersARB;
PFNGLBUFFERSUBDATAARBPROC pGlBufferSubDataARB;
PFNGLGETBUFFERSUBDATAARBPROC pGlGetBufferSubDataARB;
PFNGLMAPBUFFERARBPROC pGlMapBufferARB;
PFNGLUNMAPBUFFERARBPROC pGlUnmapBufferARB;
PFNGLISBUFFERARBPROC pGlIsBufferARB;
PFNGLGETBUFFERPARAMETERIVARBPROC pGlGetBufferParameterivARB;
PFNGLGETBUFFERPOINTERVARBPROC pGlGetBufferPointervARB;
PFNGLPROVOKINGVERTEXPROC pGlProvokingVertexARB;
PFNGLPROVOKINGVERTEXEXTPROC pGlProvokingVertexEXT;
PFNGLCOLORMASKINDEXEDEXTPROC pGlColorMaskIndexedEXT;
PFNGLENABLEINDEXEDEXTPROC pGlEnableIndexedEXT;
PFNGLDISABLEINDEXEDEXTPROC pGlDisableIndexedEXT;
PFNGLBLENDFUNCINDEXEDAMDPROC pGlBlendFuncIndexedAMD;
PFNGLBLENDFUNCIPROC pGlBlendFunciARB;
PFNGLPROGRAMPARAMETERIARBPROC pGlProgramParameteriARB;
PFNGLPROGRAMPARAMETERIEXTPROC pGlProgramParameteriEXT;
#endif
};
inline void COpenGLExtensionHandler::extGlActiveTexture(GLenum texture)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (MultiTextureExtension && pGlActiveTextureARB)
pGlActiveTextureARB(texture);
#else
if (MultiTextureExtension)
#ifdef GL_ARB_multitexture
glActiveTextureARB(texture);
#else
glActiveTexture(texture);
#endif
#endif
}
inline void COpenGLExtensionHandler::extGlClientActiveTexture(GLenum texture)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (MultiTextureExtension && pGlClientActiveTextureARB)
pGlClientActiveTextureARB(texture);
#else
if (MultiTextureExtension)
glClientActiveTextureARB(texture);
#endif
}
inline void COpenGLExtensionHandler::extGlGenPrograms(GLsizei n, GLuint *programs)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGenProgramsARB)
pGlGenProgramsARB(n, programs);
else if (pGlGenProgramsNV)
pGlGenProgramsNV(n, programs);
#elif defined(GL_ARB_vertex_program) || defined(GL_ARB_fragment_program)
glGenProgramsARB(n,programs);
#elif defined(GL_NV_vertex_program) || defined(GL_NV_fragment_program)
glGenProgramsNV(n,programs);
#else
os::Printer::log("glGenPrograms not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBindProgram(GLenum target, GLuint program)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlBindProgramARB)
pGlBindProgramARB(target, program);
else if (pGlBindProgramNV)
pGlBindProgramNV(target, program);
#elif defined(GL_ARB_vertex_program) || defined(GL_ARB_fragment_program)
glBindProgramARB(target, program);
#elif defined(GL_NV_vertex_program) || defined(GL_NV_fragment_program)
glBindProgramNV(target, program);
#else
os::Printer::log("glBindProgram not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlProgramString(GLenum target, GLenum format, GLsizei len, const GLvoid *string)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlProgramStringARB)
pGlProgramStringARB(target, format, len, string);
#elif defined(GL_ARB_vertex_program) || defined(GL_ARB_fragment_program)
glProgramStringARB(target,format,len,string);
#else
os::Printer::log("glProgramString not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlLoadProgram(GLenum target, GLuint id, GLsizei len, const GLubyte *string)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlLoadProgramNV)
pGlLoadProgramNV(target, id, len, string);
#elif defined(GL_NV_vertex_program) || defined(GL_NV_fragment_program)
glLoadProgramNV(target,id,len,string);
#else
os::Printer::log("glLoadProgram not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlDeletePrograms(GLsizei n, const GLuint *programs)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlDeleteProgramsARB)
pGlDeleteProgramsARB(n, programs);
else if (pGlDeleteProgramsNV)
pGlDeleteProgramsNV(n, programs);
#elif defined(GL_ARB_vertex_program) || defined(GL_ARB_fragment_program)
glDeleteProgramsARB(n,programs);
#elif defined(GL_NV_vertex_program) || defined(GL_NV_fragment_program)
glDeleteProgramsNV(n,programs);
#else
os::Printer::log("glDeletePrograms not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlProgramLocalParameter4fv(GLenum n, GLuint i, const GLfloat * f)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlProgramLocalParameter4fvARB)
pGlProgramLocalParameter4fvARB(n,i,f);
#elif defined(GL_ARB_vertex_program) || defined(GL_ARB_fragment_program)
glProgramLocalParameter4fvARB(n,i,f);
#else
os::Printer::log("glProgramLocalParameter4fv not supported", ELL_ERROR);
#endif
}
inline GLhandleARB COpenGLExtensionHandler::extGlCreateShaderObject(GLenum shaderType)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlCreateShaderObjectARB)
return pGlCreateShaderObjectARB(shaderType);
#elif defined(GL_ARB_shader_objects)
return glCreateShaderObjectARB(shaderType);
#else
os::Printer::log("glCreateShaderObject not supported", ELL_ERROR);
#endif
return 0;
}
inline void COpenGLExtensionHandler::extGlShaderSource(GLhandleARB shader, int numOfStrings, const char **strings, int *lenOfStrings)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlShaderSourceARB)
pGlShaderSourceARB(shader, numOfStrings, strings, lenOfStrings);
#elif defined(GL_ARB_shader_objects)
glShaderSourceARB(shader, numOfStrings, strings, (GLint *)lenOfStrings);
#else
os::Printer::log("glShaderSource not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlCompileShader(GLhandleARB shader)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlCompileShaderARB)
pGlCompileShaderARB(shader);
#elif defined(GL_ARB_shader_objects)
glCompileShaderARB(shader);
#else
os::Printer::log("glCompileShader not supported", ELL_ERROR);
#endif
}
inline GLhandleARB COpenGLExtensionHandler::extGlCreateProgramObject(void)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlCreateProgramObjectARB)
return pGlCreateProgramObjectARB();
#elif defined(GL_ARB_shader_objects)
return glCreateProgramObjectARB();
#else
os::Printer::log("glCreateProgramObject not supported", ELL_ERROR);
#endif
return 0;
}
inline void COpenGLExtensionHandler::extGlAttachObject(GLhandleARB program, GLhandleARB shader)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlAttachObjectARB)
pGlAttachObjectARB(program, shader);
#elif defined(GL_ARB_shader_objects)
glAttachObjectARB(program, shader);
#else
os::Printer::log("glAttachObject not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlLinkProgram(GLhandleARB program)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlLinkProgramARB)
pGlLinkProgramARB(program);
#elif defined(GL_ARB_shader_objects)
glLinkProgramARB(program);
#else
os::Printer::log("glLinkProgram not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUseProgramObject(GLhandleARB prog)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUseProgramObjectARB)
pGlUseProgramObjectARB(prog);
#elif defined(GL_ARB_shader_objects)
glUseProgramObjectARB(prog);
#else
os::Printer::log("glUseProgramObject not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlDeleteObject(GLhandleARB object)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlDeleteObjectARB)
pGlDeleteObjectARB(object);
#elif defined(GL_ARB_shader_objects)
glDeleteObjectARB(object);
#else
os::Printer::log("gldeleteObject not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGetInfoLog(GLhandleARB object, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetInfoLogARB)
pGlGetInfoLogARB(object, maxLength, length, infoLog);
#elif defined(GL_ARB_shader_objects)
glGetInfoLogARB(object, maxLength, length, infoLog);
#else
os::Printer::log("glGetInfoLog not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGetObjectParameteriv(GLhandleARB object, GLenum type, int *param)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetObjectParameterivARB)
pGlGetObjectParameterivARB(object, type, param);
#elif defined(GL_ARB_shader_objects)
glGetObjectParameterivARB(object, type, (GLint *)param);
#else
os::Printer::log("glGetObjectParameteriv not supported", ELL_ERROR);
#endif
}
inline GLint COpenGLExtensionHandler::extGlGetUniformLocation(GLhandleARB program, const char *name)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetUniformLocationARB)
return pGlGetUniformLocationARB(program, name);
#elif defined(GL_ARB_shader_objects)
return glGetUniformLocationARB(program, name);
#else
os::Printer::log("glGetUniformLocation not supported", ELL_ERROR);
#endif
return 0;
}
inline void COpenGLExtensionHandler::extGlUniform4fv(GLint location, GLsizei count, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniform4fvARB)
pGlUniform4fvARB(location, count, v);
#elif defined(GL_ARB_shader_objects)
glUniform4fvARB(location, count, v);
#else
os::Printer::log("glUniform4fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniform1iv(GLint loc, GLsizei count, const GLint *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniform1ivARB)
pGlUniform1ivARB(loc, count, v);
#elif defined(GL_ARB_shader_objects)
glUniform1ivARB(loc, count, v);
#else
os::Printer::log("glUniform1iv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniform1fv(GLint loc, GLsizei count, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniform1fvARB)
pGlUniform1fvARB(loc, count, v);
#elif defined(GL_ARB_shader_objects)
glUniform1fvARB(loc, count, v);
#else
os::Printer::log("glUniform1fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniform2fv(GLint loc, GLsizei count, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniform2fvARB)
pGlUniform2fvARB(loc, count, v);
#elif defined(GL_ARB_shader_objects)
glUniform2fvARB(loc, count, v);
#else
os::Printer::log("glUniform2fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniform3fv(GLint loc, GLsizei count, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniform3fvARB)
pGlUniform3fvARB(loc, count, v);
#elif defined(GL_ARB_shader_objects)
glUniform3fvARB(loc, count, v);
#else
os::Printer::log("glUniform3fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniformMatrix2fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniformMatrix2fvARB)
pGlUniformMatrix2fvARB(loc, count, transpose, v);
#elif defined(GL_ARB_shader_objects)
glUniformMatrix2fvARB(loc, count, transpose, v);
#else
os::Printer::log("glUniformMatrix2fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniformMatrix3fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniformMatrix3fvARB)
pGlUniformMatrix3fvARB(loc, count, transpose, v);
#elif defined(GL_ARB_shader_objects)
glUniformMatrix3fvARB(loc, count, transpose, v);
#else
os::Printer::log("glUniformMatrix3fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniformMatrix4fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniformMatrix4fvARB)
pGlUniformMatrix4fvARB(loc, count, transpose, v);
#elif defined(GL_ARB_shader_objects)
glUniformMatrix4fvARB(loc, count, transpose, v);
#else
os::Printer::log("glUniformMatrix4fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGetActiveUniform(GLhandleARB program,
GLuint index, GLsizei maxlength, GLsizei *length,
GLint *size, GLenum *type, GLcharARB *name)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetActiveUniformARB)
pGlGetActiveUniformARB(program, index, maxlength, length, size, type, name);
#elif defined(GL_ARB_shader_objects)
glGetActiveUniformARB(program, index, maxlength, length, size, type, name);
#else
os::Printer::log("glGetActiveUniform not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlPointParameterf(GLint loc, GLfloat f)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlPointParameterfARB)
pGlPointParameterfARB(loc, f);
#elif defined(GL_ARB_point_parameters)
glPointParameterfARB(loc, f);
#else
os::Printer::log("glPointParameterf not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlPointParameterfv(GLint loc, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlPointParameterfvARB)
pGlPointParameterfvARB(loc, v);
#elif defined(GL_ARB_point_parameters)
glPointParameterfvARB(loc, v);
#else
os::Printer::log("glPointParameterfv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlStencilFuncSeparate (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlStencilFuncSeparate)
pGlStencilFuncSeparate(frontfunc, backfunc, ref, mask);
else if (pGlStencilFuncSeparateATI)
pGlStencilFuncSeparateATI(frontfunc, backfunc, ref, mask);
#elif defined(GL_VERSION_2_0)
glStencilFuncSeparate(frontfunc, backfunc, ref, mask);
#elif defined(GL_ATI_separate_stencil)
glStencilFuncSeparateATI(frontfunc, backfunc, ref, mask);
#else
os::Printer::log("glStencilFuncSeparate not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlStencilOpSeparate (GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlStencilOpSeparate)
pGlStencilOpSeparate(face, fail, zfail, zpass);
else if (pGlStencilOpSeparateATI)
pGlStencilOpSeparateATI(face, fail, zfail, zpass);
#elif defined(GL_VERSION_2_0)
glStencilOpSeparate(face, fail, zfail, zpass);
#elif defined(GL_ATI_separate_stencil)
glStencilOpSeparateATI(face, fail, zfail, zpass);
#else
os::Printer::log("glStencilOpSeparate not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width,
GLsizei height, GLint border, GLsizei imageSize, const void* data)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlCompressedTexImage2D)
pGlCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data);
#elif defined(GL_ARB_texture_compression)
glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data);
#else
os::Printer::log("glCompressedTexImage2D not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBindFramebuffer(GLenum target, GLuint framebuffer)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlBindFramebufferEXT)
|
paupawsan/Irrlicht
|
6d14502cd644241d6eaa1eb612615e438aba6370
|
Add and fix another aabbox intersectsWithBox test.
|
diff --git a/include/aabbox3d.h b/include/aabbox3d.h
index 2005f74..5e9b18d 100644
--- a/include/aabbox3d.h
+++ b/include/aabbox3d.h
@@ -1,330 +1,332 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __IRR_AABBOX_3D_H_INCLUDED__
#define __IRR_AABBOX_3D_H_INCLUDED__
#include "irrMath.h"
#include "plane3d.h"
#include "line3d.h"
namespace irr
{
namespace core
{
//! Axis aligned bounding box in 3d dimensional space.
/** Has some useful methods used with occlusion culling or clipping.
*/
template <class T>
class aabbox3d
{
public:
//! Default Constructor.
aabbox3d(): MinEdge(-1,-1,-1), MaxEdge(1,1,1) {}
//! Constructor with min edge and max edge.
aabbox3d(const vector3d<T>& min, const vector3d<T>& max): MinEdge(min), MaxEdge(max) {}
//! Constructor with only one point.
aabbox3d(const vector3d<T>& init): MinEdge(init), MaxEdge(init) {}
//! Constructor with min edge and max edge as single values, not vectors.
aabbox3d(T minx, T miny, T minz, T maxx, T maxy, T maxz): MinEdge(minx, miny, minz), MaxEdge(maxx, maxy, maxz) {}
// operators
//! Equality operator
/** \param other box to compare with.
\return True if both boxes are equal, else false. */
inline bool operator==(const aabbox3d<T>& other) const { return (MinEdge == other.MinEdge && other.MaxEdge == MaxEdge);}
//! Inequality operator
/** \param other box to compare with.
\return True if both boxes are different, else false. */
inline bool operator!=(const aabbox3d<T>& other) const { return !(MinEdge == other.MinEdge && other.MaxEdge == MaxEdge);}
// functions
//! Resets the bounding box to a one-point box.
/** \param x X coord of the point.
\param y Y coord of the point.
\param z Z coord of the point. */
void reset(T x, T y, T z)
{
MaxEdge.set(x,y,z);
MinEdge = MaxEdge;
}
//! Resets the bounding box.
/** \param initValue New box to set this one to. */
void reset(const aabbox3d<T>& initValue)
{
*this = initValue;
}
//! Resets the bounding box to a one-point box.
/** \param initValue New point. */
void reset(const vector3d<T>& initValue)
{
MaxEdge = initValue;
MinEdge = initValue;
}
//! Adds a point to the bounding box
/** The box grows bigger, if point was outside of the box.
\param p: Point to add into the box. */
void addInternalPoint(const vector3d<T>& p)
{
addInternalPoint(p.X, p.Y, p.Z);
}
//! Adds another bounding box
/** The box grows bigger, if the new box was outside of the box.
\param b: Other bounding box to add into this box. */
void addInternalBox(const aabbox3d<T>& b)
{
addInternalPoint(b.MaxEdge);
addInternalPoint(b.MinEdge);
}
//! Adds a point to the bounding box
/** The box grows bigger, if point is outside of the box.
\param x X coordinate of the point to add to this box.
\param y Y coordinate of the point to add to this box.
\param z Z coordinate of the point to add to this box. */
void addInternalPoint(T x, T y, T z)
{
if (x>MaxEdge.X) MaxEdge.X = x;
if (y>MaxEdge.Y) MaxEdge.Y = y;
if (z>MaxEdge.Z) MaxEdge.Z = z;
if (x<MinEdge.X) MinEdge.X = x;
if (y<MinEdge.Y) MinEdge.Y = y;
if (z<MinEdge.Z) MinEdge.Z = z;
}
//! Get center of the bounding box
/** \return Center of the bounding box. */
vector3d<T> getCenter() const
{
return (MinEdge + MaxEdge) / 2;
}
//! Get extent of the box (maximal distance of two points in the box)
/** \return Extent of the bounding box. */
vector3d<T> getExtent() const
{
return MaxEdge - MinEdge;
}
//! Check if the box is empty.
/** This means that there is no space between the min and max edge.
\return True if box is empty, else false. */
bool isEmpty() const
{
return MinEdge.equals ( MaxEdge );
}
//! Get the volume enclosed by the box in cubed units
T getVolume() const
{
const vector3d<T> e = getExtent();
return e.X * e.Y * e.Z;
}
//! Get the surface area of the box in squared units
T getArea() const
{
const vector3d<T> e = getExtent();
return 2*(e.X*e.Y + e.X*e.Z + e.Y*e.Z);
}
//! Stores all 8 edges of the box into an array
/** \param edges: Pointer to array of 8 edges. */
void getEdges(vector3d<T> *edges) const
{
const core::vector3d<T> middle = getCenter();
const core::vector3d<T> diag = middle - MaxEdge;
/*
Edges are stored in this way:
Hey, am I an ascii artist, or what? :) niko.
/3--------/7
/ | / |
/ | / |
1---------5 |
| /2- - -|- -6
| / | /
|/ | /
0---------4/
*/
edges[0].set(middle.X + diag.X, middle.Y + diag.Y, middle.Z + diag.Z);
edges[1].set(middle.X + diag.X, middle.Y - diag.Y, middle.Z + diag.Z);
edges[2].set(middle.X + diag.X, middle.Y + diag.Y, middle.Z - diag.Z);
edges[3].set(middle.X + diag.X, middle.Y - diag.Y, middle.Z - diag.Z);
edges[4].set(middle.X - diag.X, middle.Y + diag.Y, middle.Z + diag.Z);
edges[5].set(middle.X - diag.X, middle.Y - diag.Y, middle.Z + diag.Z);
edges[6].set(middle.X - diag.X, middle.Y + diag.Y, middle.Z - diag.Z);
edges[7].set(middle.X - diag.X, middle.Y - diag.Y, middle.Z - diag.Z);
}
//! Repairs the box.
/** Necessary if for example MinEdge and MaxEdge are swapped. */
void repair()
{
T t;
if (MinEdge.X > MaxEdge.X)
{ t=MinEdge.X; MinEdge.X = MaxEdge.X; MaxEdge.X=t; }
if (MinEdge.Y > MaxEdge.Y)
{ t=MinEdge.Y; MinEdge.Y = MaxEdge.Y; MaxEdge.Y=t; }
if (MinEdge.Z > MaxEdge.Z)
{ t=MinEdge.Z; MinEdge.Z = MaxEdge.Z; MaxEdge.Z=t; }
}
//! Calculates a new interpolated bounding box.
/** d=0 returns other, d=1 returns this, all other values blend between
the two boxes.
\param other Other box to interpolate between
\param d Value between 0.0f and 1.0f.
\return Interpolated box. */
aabbox3d<T> getInterpolated(const aabbox3d<T>& other, f32 d) const
{
f32 inv = 1.0f - d;
return aabbox3d<T>((other.MinEdge*inv) + (MinEdge*d),
(other.MaxEdge*inv) + (MaxEdge*d));
}
//! Determines if a point is within this box.
/** Border is included (IS part of the box)!
\param p: Point to check.
\return True if the point is within the box and false if not */
bool isPointInside(const vector3d<T>& p) const
{
return (p.X >= MinEdge.X && p.X <= MaxEdge.X &&
p.Y >= MinEdge.Y && p.Y <= MaxEdge.Y &&
p.Z >= MinEdge.Z && p.Z <= MaxEdge.Z);
}
//! Determines if a point is within this box and not its borders.
/** Border is excluded (NOT part of the box)!
\param p: Point to check.
\return True if the point is within the box and false if not. */
bool isPointTotalInside(const vector3d<T>& p) const
{
return (p.X > MinEdge.X && p.X < MaxEdge.X &&
p.Y > MinEdge.Y && p.Y < MaxEdge.Y &&
p.Z > MinEdge.Z && p.Z < MaxEdge.Z);
}
//! Check if this box is completely inside the 'other' box.
/** \param other: Other box to check against.
\return True if this box is completly inside the other box,
otherwise false. */
bool isFullInside(const aabbox3d<T>& other) const
{
- return MinEdge >= other.MinEdge && MaxEdge <= other.MaxEdge;
+ return (MinEdge.X >= other.MinEdge.X && MinEdge.Y >= other.MinEdge.Y && MinEdge.Z >= other.MinEdge.Z &&
+ MaxEdge.X <= other.MaxEdge.X && MaxEdge.Y <= other.MaxEdge.Y && MaxEdge.Z <= other.MaxEdge.Z);
}
- //! Determines if the box intersects with another box.
+ //! Determines if the axis-aligned box intersects with another axis-aligned box.
/** \param other: Other box to check a intersection with.
\return True if there is an intersection with the other box,
otherwise false. */
bool intersectsWithBox(const aabbox3d<T>& other) const
{
- return (MinEdge <= other.MaxEdge && MaxEdge >= other.MinEdge);
+ return (MinEdge.X <= other.MaxEdge.X && MinEdge.Y <= other.MaxEdge.Y && MinEdge.Z <= other.MaxEdge.Z &&
+ MaxEdge.X >= other.MinEdge.X && MaxEdge.Y >= other.MinEdge.Y && MaxEdge.Z >= other.MinEdge.Z);
}
//! Tests if the box intersects with a line
/** \param line: Line to test intersection with.
\return True if there is an intersection , else false. */
bool intersectsWithLine(const line3d<T>& line) const
{
return intersectsWithLine(line.getMiddle(), line.getVector().normalize(),
(T)(line.getLength() * 0.5));
}
//! Tests if the box intersects with a line
/** \param linemiddle Center of the line.
\param linevect Vector of the line.
\param halflength Half length of the line.
\return True if there is an intersection, else false. */
bool intersectsWithLine(const vector3d<T>& linemiddle,
const vector3d<T>& linevect, T halflength) const
{
const vector3d<T> e = getExtent() * (T)0.5;
const vector3d<T> t = getCenter() - linemiddle;
if ((fabs(t.X) > e.X + halflength * fabs(linevect.X)) ||
(fabs(t.Y) > e.Y + halflength * fabs(linevect.Y)) ||
(fabs(t.Z) > e.Z + halflength * fabs(linevect.Z)) )
return false;
T r = e.Y * (T)fabs(linevect.Z) + e.Z * (T)fabs(linevect.Y);
if (fabs(t.Y*linevect.Z - t.Z*linevect.Y) > r )
return false;
r = e.X * (T)fabs(linevect.Z) + e.Z * (T)fabs(linevect.X);
if (fabs(t.Z*linevect.X - t.X*linevect.Z) > r )
return false;
r = e.X * (T)fabs(linevect.Y) + e.Y * (T)fabs(linevect.X);
if (fabs(t.X*linevect.Y - t.Y*linevect.X) > r)
return false;
return true;
}
//! Classifies a relation with a plane.
/** \param plane Plane to classify relation to.
\return Returns ISREL3D_FRONT if the box is in front of the plane,
ISREL3D_BACK if the box is behind the plane, and
ISREL3D_CLIPPED if it is on both sides of the plane. */
EIntersectionRelation3D classifyPlaneRelation(const plane3d<T>& plane) const
{
vector3d<T> nearPoint(MaxEdge);
vector3d<T> farPoint(MinEdge);
if (plane.Normal.X > (T)0)
{
nearPoint.X = MinEdge.X;
farPoint.X = MaxEdge.X;
}
if (plane.Normal.Y > (T)0)
{
nearPoint.Y = MinEdge.Y;
farPoint.Y = MaxEdge.Y;
}
if (plane.Normal.Z > (T)0)
{
nearPoint.Z = MinEdge.Z;
farPoint.Z = MaxEdge.Z;
}
if (plane.Normal.dotProduct(nearPoint) + plane.D > (T)0)
return ISREL3D_FRONT;
if (plane.Normal.dotProduct(farPoint) + plane.D > (T)0)
return ISREL3D_CLIPPED;
return ISREL3D_BACK;
}
//! The near edge
vector3d<T> MinEdge;
//! The far edge
vector3d<T> MaxEdge;
};
//! Typedef for a f32 3d bounding box.
typedef aabbox3d<f32> aabbox3df;
//! Typedef for an integer 3d bounding box.
typedef aabbox3d<s32> aabbox3di;
} // end namespace core
} // end namespace irr
#endif
diff --git a/tests/sceneCollisionManager.cpp b/tests/sceneCollisionManager.cpp
index d3793cb..314601e 100644
--- a/tests/sceneCollisionManager.cpp
+++ b/tests/sceneCollisionManager.cpp
@@ -1,460 +1,483 @@
// Copyright (C) 2008-2009 Colin MacDonald
// No rights reserved: this software is in the public domain.
#include "testUtils.h"
using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
static bool testGetCollisionResultPosition(IrrlichtDevice * device,
ISceneManager * smgr,
ISceneCollisionManager * collMgr)
{
IMeshSceneNode * cubeNode = smgr->addCubeSceneNode(10.f);
ITriangleSelector * cubeSelector = smgr->createTriangleSelectorFromBoundingBox(cubeNode);
triangle3df triOut;
vector3df hitPosition;
bool falling;
const ISceneNode* hitNode;
vector3df resultPosition =
collMgr->getCollisionResultPosition(cubeSelector,
vector3df(0, 50, 0),
vector3df(10, 20, 10),
vector3df(0, -100, 0),
triOut,
hitPosition,
falling,
hitNode);
bool result = true;
if(hitNode != cubeNode)
{
logTestString("Unexpected collision node\n");
result = false;
}
if(!equals(resultPosition.Y, 25.f, 0.01f))
{
logTestString("Unexpected collision response position\n");
result = false;
}
if(!equals(hitPosition.Y, 5.f, 0.01f))
{
logTestString("Unexpected collision position\n");
result = false;
}
resultPosition =
collMgr->getCollisionResultPosition(cubeSelector,
vector3df(-20, 0, 0),
vector3df(10, 20, 10),
vector3df(100, 0, 0),
triOut,
hitPosition,
falling,
hitNode);
if(hitNode != cubeNode)
{
logTestString("Unexpected collision node\n");
result = false;
}
if(!equals(resultPosition.X, -15.f, 0.01f))
{
logTestString("Unexpected collision response position\n");
result = false;
}
if(!equals(hitPosition.X, -5.f, 0.01f))
{
logTestString("Unexpected collision position\n");
result = false;
}
assert(result);
cubeSelector->drop();
smgr->clear();
return result;
}
// Test that getCollisionPoint() actually uses the closest point, not the closest triangle.
static bool getCollisionPoint_ignoreTriangleVertices(IrrlichtDevice * device,
ISceneManager * smgr,
ISceneCollisionManager * collMgr)
{
// Create a cube with a Z face at 5, but corners close to 0
ISceneNode * farSmallCube = smgr->addCubeSceneNode(10, 0, -1, vector3df(0, 0, 10));
// Create a cube with a Z face at 0, but corners far from 0
ISceneNode * nearBigCube = smgr->addCubeSceneNode(100, 0, -1, vector3df(0, 0, 50));
IMetaTriangleSelector * meta = smgr->createMetaTriangleSelector();
ITriangleSelector * selector = smgr->createTriangleSelectorFromBoundingBox(farSmallCube);
meta->addTriangleSelector(selector);
selector->drop();
// We should expect a hit on this cube
selector = smgr->createTriangleSelectorFromBoundingBox(nearBigCube);
meta->addTriangleSelector(selector);
selector->drop();
line3df ray(0, 0, -5, 0, 0, 100);
vector3df hitPosition;
triangle3df hitTriangle;
const ISceneNode* hitNode;
bool collision = collMgr->getCollisionPoint(ray, meta, hitPosition, hitTriangle, hitNode);
meta->drop();
if(hitNode != nearBigCube)
{
logTestString("getCollisionPoint_ignoreTriangleVertices: hit the wrong node.\n");
return false;
}
if(!collision)
{
logTestString("getCollisionPoint_ignoreTriangleVertices: didn't get a hit.\n");
return false;
}
if(hitPosition != vector3df(0, 0, 0))
{
logTestString("getCollisionPoint_ignoreTriangleVertices: unexpected hit position %f %f %f.\n",
hitPosition.X, hitPosition.Y, hitPosition.Z );
return false;
}
smgr->clear();
return true;
}
static bool testGetSceneNodeFromScreenCoordinatesBB(IrrlichtDevice * device,
ISceneManager * smgr,
ISceneCollisionManager * collMgr)
{
// Create 3 nodes. The nearest node actually contains the camera.
IMeshSceneNode * cubeNode1 = smgr->addCubeSceneNode(10.f, 0, -1, vector3df(0, 0, 4));
IMeshSceneNode * cubeNode2 = smgr->addCubeSceneNode(10.f, 0, -1, vector3df(0, 0, 30));
cubeNode2->setRotation(vector3df(90.f, 90.f, 90.f)); // Just check that rotation doesn't stop us hitting it.
IMeshSceneNode * cubeNode3 = smgr->addCubeSceneNode(10.f, 0, -1, vector3df(0, 0, 40));
cubeNode3->setRotation(vector3df(180.f, 180.f, 180.f)); // Just check that rotation doesn't stop us hitting it.
ICameraSceneNode * camera = smgr->addCameraSceneNode();
device->run();
smgr->drawAll(); // Get the camera in a good state
ISceneNode * hitNode = collMgr->getSceneNodeFromScreenCoordinatesBB(position2d<s32>(80, 60));
// Expect the first node to be hit, since we're starting the check from inside it.
bool result = true;
if(hitNode != cubeNode1)
{
logTestString("Unexpected node hit. Expected cubeNode1.\n");
result = false;
}
// Now make cubeNode1 invisible and check that cubeNode2 is hit.
cubeNode1->setVisible(false);
hitNode = collMgr->getSceneNodeFromScreenCoordinatesBB(position2d<s32>(80, 60));
if(hitNode != cubeNode2)
{
logTestString("Unexpected node hit. Expected cubeNode2.\n");
result = false;
}
// Make cubeNode1 the parent of cubeNode2.
cubeNode2->setParent(cubeNode1);
// Check visibility.
bool visible = cubeNode2->isVisible();
if(!visible)
{
logTestString("cubeNode2 should think that it (in isolation) is visible.\n");
result = false;
}
visible = cubeNode2->isTrulyVisible();
if(visible)
{
logTestString("cubeNode2 should know that it (recursively) is invisible.\n");
result = false;
}
// cubeNode2 should now be an invalid target as well, and so the final cube node should be hit.
hitNode = collMgr->getSceneNodeFromScreenCoordinatesBB(position2d<s32>(80, 60));
if(hitNode != cubeNode3)
{
logTestString("Unexpected node hit. Expected cubeNode3.\n");
result = false;
}
// Make cubeNode3 invisible and check that the camera node is hit (since it has a valid bounding box).
cubeNode3->setVisible(false);
hitNode = collMgr->getSceneNodeFromScreenCoordinatesBB(position2d<s32>(80, 60));
if(hitNode != camera)
{
logTestString("Unexpected node hit. Expected the camera node.\n");
result = false;
}
// Now verify bitmasking
camera->setID(0xAAAAAAAA); // == 101010101010101010101010101010
hitNode = collMgr->getSceneNodeFromScreenCoordinatesBB(position2d<s32>(80, 60), 0x02);
if(hitNode != camera)
{
logTestString("Unexpected node hit. Expected the camera node.\n");
result = false;
}
// Test the 01010101010101010101010101010101 bitmask (0x55555555)
hitNode = collMgr->getSceneNodeFromScreenCoordinatesBB(position2d<s32>(80, 60), 0x55555555);
if(hitNode != 0)
{
logTestString("A node was hit when none was expected.\n");
result = false;
}
assert(result);
smgr->clear();
return result;
}
static bool getScaledPickedNodeBB(IrrlichtDevice * device,
ISceneManager * smgr,
ISceneCollisionManager * collMgr)
{
ISceneNode* farTarget = smgr->addCubeSceneNode(1.f);
farTarget->setScale(vector3df(100.f, 100.f, 10.f));
farTarget->setPosition(vector3df(0.f, 0.f, 500.f));
farTarget->updateAbsolutePosition();
// Create a node that's slightly further away than the closest node,
// but thinner. Its furthest corner is closer, but the collision
// position is further, so it should not be selected.
ISceneNode* middleTarget = smgr->addCubeSceneNode(10.f);
middleTarget->setPosition(vector3df(0.f, 0.f, 101.f));
middleTarget->setScale(vector3df(1.f, 1.f, 0.5f));
middleTarget->updateAbsolutePosition();
ISceneNode* nearTarget = smgr->addCubeSceneNode(10.f);
nearTarget->setPosition(vector3df(0.f, 0.f, 100.f));
nearTarget->updateAbsolutePosition();
// We'll rotate this node 90 degrees to show that we can hit its side.
nearTarget->setRotation(vector3df(0.f, 90.f, 0.f));
line3df ray(0.f, 0.f, 0.f, 0.f, 0.f, 500.f);
const ISceneNode * const hit = collMgr->getSceneNodeFromRayBB(ray);
bool result = (hit == nearTarget);
if(hit == 0)
logTestString("getSceneNodeFromRayBB() didn't hit anything.\n");
else if(hit == farTarget)
logTestString("getSceneNodeFromRayBB() hit the far (scaled) target.\n");
else if(hit == middleTarget)
logTestString("getSceneNodeFromRayBB() hit the middle (scaled) target.\n");
assert(result);
smgr->clear();
return result;
}
// box intersection according to Kay et al., code from gamedev.net
static bool IntersectBox(const core::vector3df& origin, const core::vector3df& dir, const core::aabbox3df& box)
{
core::vector3df minDist = (box.MinEdge - origin)/dir;
core::vector3df maxDist = (box.MaxEdge - origin)/dir;
core::vector3df realMin(core::min_(minDist.X, maxDist.X),core::min_(minDist.Y, maxDist.Y),core::min_(minDist.Z, maxDist.Z));
core::vector3df realMax(core::max_(minDist.X, maxDist.X),core::max_(minDist.Y, maxDist.Y),core::max_(minDist.Z, maxDist.Z));
f32 minmax = core::min_(realMax.X, realMax.Y, realMax.Z);
// nearest distance to intersection
f32 maxmin = core::max_(realMin.X, realMin.Y, realMin.Z);
return (maxmin >=0 && minmax >= maxmin);
}
static bool checkBBoxIntersection(IrrlichtDevice * device,
ISceneManager * smgr)
{
video::IVideoDriver* driver = device->getVideoDriver();
// add camera
- scene::ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS();
+ scene::ICameraSceneNode* camera = smgr->addCameraSceneNode();
camera->setPosition(core::vector3df(30, 30, 30));
camera->setTarget(core::vector3df(8.f, 8.f, 8.f));
camera->setID(0);
// add a cube to pick
scene::ISceneNode* cube = smgr->addCubeSceneNode(30, 0, -1, core::vector3df(0,0,0),core::vector3df(30,40,50));
bool result=true;
for (u32 round=0; round<2; ++round)
{
driver->beginScene(true, true, video::SColor(100, 50, 50, 100));
smgr->drawAll();
driver->endScene();
core::matrix4 invMat = cube->getAbsoluteTransformation();
invMat.makeInverse();
s32 hits=0;
u32 start = device->getTimer()->getRealTime();
for (u32 i=10; i<150; ++i)
{
for (u32 j=10; j<110; ++j)
{
const core::position2di pos(i, j);
// get the line used for picking
core::line3df ray = smgr->getSceneCollisionManager()->getRayFromScreenCoordinates(pos, camera);
invMat.transformVect(ray.start);
invMat.transformVect(ray.end);
hits += (cube->getBoundingBox().intersectsWithLine(ray)?1:0);
}
}
u32 duration = device->getTimer()->getRealTime()-start;
logTestString("bbox intersection checks %d hits (of 14000).\n", hits);
hits = -hits;
start = device->getTimer()->getRealTime();
for (u32 i=10; i<150; ++i)
{
for (u32 j=10; j<110; ++j)
{
const core::position2di pos(i, j);
// get the line used for picking
core::line3df ray = smgr->getSceneCollisionManager()->getRayFromScreenCoordinates(pos, camera);
invMat.transformVect(ray.start);
invMat.transformVect(ray.end);
hits += (IntersectBox(ray.start, (ray.end-ray.start).normalize(), cube->getBoundingBox())?1:0);
}
}
u32 duration2 = device->getTimer()->getRealTime()-start;
logTestString("bbox intersection resulted in %d misses at a speed of %d (old) compared to %d (new).\n", abs(hits), duration, duration2);
if (duration>(duration2*1.2f))
logTestString("Consider replacement of bbox intersection test.\n");
result &= (hits==0);
assert(result);
// second round without any hits, so check opposite direction
camera->setTarget(core::vector3df(80.f, 80.f, 80.f));
}
+ ISceneNode* node = smgr->addSphereSceneNode(5.f, 16, 0, -1, core::vector3df(0, 0, 1), core::vector3df(), core::vector3df(0.3f, 0.3f, 0.3f));
+ cube->remove();
+ cube = smgr->addCubeSceneNode(10.f, 0, -1, core::vector3df(0, 6.5f, 1), core::vector3df(), core::vector3df(10, 0.1f, 1.f));
+ camera->setPosition(core::vector3df(0, 0, 10));
+ camera->setTarget(core::vector3df());
+
+ u32 count=0;
+ for (u32 i=0; i<30; ++i)
+ {
+ driver->beginScene(true, true, video::SColor(100, 50, 50, 100));
+ smgr->drawAll();
+ driver->endScene();
+
+ count += node->getTransformedBoundingBox().intersectsWithBox(cube->getTransformedBoundingBox())?1:0;
+ node->setPosition(node->getPosition()+core::vector3df(.5f,.5f,0));
+ if (i==8 && count != 0)
+ result=false;
+ if (i==17 && count != 9)
+ result=false;
+ }
+ if (count != 9)
+ result=false;
+
smgr->clear();
- return (result);
+ return result;
}
static bool compareGetSceneNodeFromRayBBWithBBIntersectsWithLine(IrrlichtDevice * device,
ISceneManager * smgr,
ISceneCollisionManager * collMgr)
{
video::IVideoDriver* driver = device->getVideoDriver();
// add camera
scene::ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS();
camera->setPosition(core::vector3df(30, 30, 30));
camera->setTarget(core::vector3df(-8.f, 8.f, -8.f));
camera->setID(0);
// add a dynamic light (this causes weirdness)
smgr->addLightSceneNode(0, core::vector3df(4, 4, 4), video::SColorf(.2f, .3f, .2f));
// add a cube to pick
scene::ISceneNode* cube = smgr->addCubeSceneNode(15);
driver->beginScene(true, true, video::SColor(100, 50, 50, 100));
smgr->drawAll();
driver->endScene();
core::matrix4 invMat = cube->getAbsoluteTransformation();
invMat.makeInverse();
bool result = true;
for (u32 i=76; i<82; ++i)
{
for (u32 j=56; j<64; ++j)
{
const core::position2di pos(i, j);
// get the line used for picking
core::line3df ray = smgr->getSceneCollisionManager()->getRayFromScreenCoordinates(pos, camera);
// find a selected node
scene::ISceneNode* pick = smgr->getSceneCollisionManager()->getSceneNodeFromRayBB(ray, 1);
invMat.transformVect(ray.start);
invMat.transformVect(ray.end);
const int a_hit = (pick == cube);
const int b_hit = cube->getBoundingBox().intersectsWithLine(ray);
result = (a_hit==b_hit);
}
}
assert(result);
smgr->clear();
return result;
}
/** Test functionality of the sceneCollisionManager */
bool sceneCollisionManager(void)
{
- IrrlichtDevice * device = irr::createDevice(video::EDT_NULL, dimension2d<u32>(160, 120));
+ IrrlichtDevice * device = irr::createDevice(video::EDT_OPENGL, dimension2d<u32>(160, 120));
assert(device);
if(!device)
return false;
ISceneManager * smgr = device->getSceneManager();
ISceneCollisionManager * collMgr = smgr->getSceneCollisionManager();
bool result = testGetCollisionResultPosition(device, smgr, collMgr);
smgr->clear();
result &= testGetSceneNodeFromScreenCoordinatesBB(device, smgr, collMgr);
result &= getScaledPickedNodeBB(device, smgr, collMgr);
result &= getCollisionPoint_ignoreTriangleVertices(device, smgr, collMgr);
result &= checkBBoxIntersection(device, smgr);
result &= compareGetSceneNodeFromRayBBWithBBIntersectsWithLine(device, smgr, collMgr);
device->drop();
return result;
}
diff --git a/tests/tests-last-passed-at.txt b/tests/tests-last-passed-at.txt
index 9578463..045f2a5 100644
--- a/tests/tests-last-passed-at.txt
+++ b/tests/tests-last-passed-at.txt
@@ -1,4 +1,4 @@
Tests finished. 51 tests of 51 passed.
Compiled as DEBUG
-Test suite pass at GMT Wed Feb 03 19:37:45 2010
+Test suite pass at GMT Fri Feb 05 14:28:53 2010
|
paupawsan/Irrlicht
|
04102b27bbb61041cc25523aa3db241097cc24e5
|
Fix signature of glProgramParameteri function. Might still raise compilation problems on some platforms, which need to be figured out later.
|
diff --git a/source/Irrlicht/COpenGLExtensionHandler.h b/source/Irrlicht/COpenGLExtensionHandler.h
index aabbeeb..01c827e 100644
--- a/source/Irrlicht/COpenGLExtensionHandler.h
+++ b/source/Irrlicht/COpenGLExtensionHandler.h
@@ -1271,541 +1271,541 @@ inline void COpenGLExtensionHandler::extGlUniform1fv(GLint loc, GLsizei count, c
#else
os::Printer::log("glUniform1fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniform2fv(GLint loc, GLsizei count, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniform2fvARB)
pGlUniform2fvARB(loc, count, v);
#elif defined(GL_ARB_shader_objects)
glUniform2fvARB(loc, count, v);
#else
os::Printer::log("glUniform2fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniform3fv(GLint loc, GLsizei count, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniform3fvARB)
pGlUniform3fvARB(loc, count, v);
#elif defined(GL_ARB_shader_objects)
glUniform3fvARB(loc, count, v);
#else
os::Printer::log("glUniform3fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniformMatrix2fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniformMatrix2fvARB)
pGlUniformMatrix2fvARB(loc, count, transpose, v);
#elif defined(GL_ARB_shader_objects)
glUniformMatrix2fvARB(loc, count, transpose, v);
#else
os::Printer::log("glUniformMatrix2fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniformMatrix3fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniformMatrix3fvARB)
pGlUniformMatrix3fvARB(loc, count, transpose, v);
#elif defined(GL_ARB_shader_objects)
glUniformMatrix3fvARB(loc, count, transpose, v);
#else
os::Printer::log("glUniformMatrix3fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlUniformMatrix4fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUniformMatrix4fvARB)
pGlUniformMatrix4fvARB(loc, count, transpose, v);
#elif defined(GL_ARB_shader_objects)
glUniformMatrix4fvARB(loc, count, transpose, v);
#else
os::Printer::log("glUniformMatrix4fv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGetActiveUniform(GLhandleARB program,
GLuint index, GLsizei maxlength, GLsizei *length,
GLint *size, GLenum *type, GLcharARB *name)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetActiveUniformARB)
pGlGetActiveUniformARB(program, index, maxlength, length, size, type, name);
#elif defined(GL_ARB_shader_objects)
glGetActiveUniformARB(program, index, maxlength, length, size, type, name);
#else
os::Printer::log("glGetActiveUniform not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlPointParameterf(GLint loc, GLfloat f)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlPointParameterfARB)
pGlPointParameterfARB(loc, f);
#elif defined(GL_ARB_point_parameters)
glPointParameterfARB(loc, f);
#else
os::Printer::log("glPointParameterf not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlPointParameterfv(GLint loc, const GLfloat *v)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlPointParameterfvARB)
pGlPointParameterfvARB(loc, v);
#elif defined(GL_ARB_point_parameters)
glPointParameterfvARB(loc, v);
#else
os::Printer::log("glPointParameterfv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlStencilFuncSeparate (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlStencilFuncSeparate)
pGlStencilFuncSeparate(frontfunc, backfunc, ref, mask);
else if (pGlStencilFuncSeparateATI)
pGlStencilFuncSeparateATI(frontfunc, backfunc, ref, mask);
#elif defined(GL_VERSION_2_0)
glStencilFuncSeparate(frontfunc, backfunc, ref, mask);
#elif defined(GL_ATI_separate_stencil)
glStencilFuncSeparateATI(frontfunc, backfunc, ref, mask);
#else
os::Printer::log("glStencilFuncSeparate not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlStencilOpSeparate (GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlStencilOpSeparate)
pGlStencilOpSeparate(face, fail, zfail, zpass);
else if (pGlStencilOpSeparateATI)
pGlStencilOpSeparateATI(face, fail, zfail, zpass);
#elif defined(GL_VERSION_2_0)
glStencilOpSeparate(face, fail, zfail, zpass);
#elif defined(GL_ATI_separate_stencil)
glStencilOpSeparateATI(face, fail, zfail, zpass);
#else
os::Printer::log("glStencilOpSeparate not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width,
GLsizei height, GLint border, GLsizei imageSize, const void* data)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlCompressedTexImage2D)
pGlCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data);
#elif defined(GL_ARB_texture_compression)
glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data);
#else
os::Printer::log("glCompressedTexImage2D not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBindFramebuffer(GLenum target, GLuint framebuffer)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlBindFramebufferEXT)
pGlBindFramebufferEXT(target, framebuffer);
#elif defined(GL_EXT_framebuffer_object)
glBindFramebufferEXT(target, framebuffer);
#else
os::Printer::log("glBindFramebuffer not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlDeleteFramebuffers(GLsizei n, const GLuint *framebuffers)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlDeleteFramebuffersEXT)
pGlDeleteFramebuffersEXT(n, framebuffers);
#elif defined(GL_EXT_framebuffer_object)
glDeleteFramebuffersEXT(n, framebuffers);
#else
os::Printer::log("glDeleteFramebuffers not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGenFramebuffers(GLsizei n, GLuint *framebuffers)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGenFramebuffersEXT)
pGlGenFramebuffersEXT(n, framebuffers);
#elif defined(GL_EXT_framebuffer_object)
glGenFramebuffersEXT(n, framebuffers);
#else
os::Printer::log("glGenFramebuffers not supported", ELL_ERROR);
#endif
}
inline GLenum COpenGLExtensionHandler::extGlCheckFramebufferStatus(GLenum target)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlCheckFramebufferStatusEXT)
return pGlCheckFramebufferStatusEXT(target);
else
return 0;
#elif defined(GL_EXT_framebuffer_object)
return glCheckFramebufferStatusEXT(target);
#else
os::Printer::log("glCheckFramebufferStatus not supported", ELL_ERROR);
return 0;
#endif
}
inline void COpenGLExtensionHandler::extGlFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlFramebufferTexture2DEXT)
pGlFramebufferTexture2DEXT(target, attachment, textarget, texture, level);
#elif defined(GL_EXT_framebuffer_object)
glFramebufferTexture2DEXT(target, attachment, textarget, texture, level);
#else
os::Printer::log("glFramebufferTexture2D not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBindRenderbuffer(GLenum target, GLuint renderbuffer)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlBindRenderbufferEXT)
pGlBindRenderbufferEXT(target, renderbuffer);
#elif defined(GL_EXT_framebuffer_object)
glBindRenderbufferEXT(target, renderbuffer);
#else
os::Printer::log("glBindRenderbuffer not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlDeleteRenderbuffers(GLsizei n, const GLuint *renderbuffers)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlDeleteRenderbuffersEXT)
pGlDeleteRenderbuffersEXT(n, renderbuffers);
#elif defined(GL_EXT_framebuffer_object)
glDeleteRenderbuffersEXT(n, renderbuffers);
#else
os::Printer::log("glDeleteRenderbuffers not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGenRenderbuffers(GLsizei n, GLuint *renderbuffers)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGenRenderbuffersEXT)
pGlGenRenderbuffersEXT(n, renderbuffers);
#elif defined(GL_EXT_framebuffer_object)
glGenRenderbuffersEXT(n, renderbuffers);
#else
os::Printer::log("glGenRenderbuffers not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlRenderbufferStorageEXT)
pGlRenderbufferStorageEXT(target, internalformat, width, height);
#elif defined(GL_EXT_framebuffer_object)
glRenderbufferStorageEXT(target, internalformat, width, height);
#else
os::Printer::log("glRenderbufferStorage not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlFramebufferRenderbufferEXT)
pGlFramebufferRenderbufferEXT(target, attachment, renderbuffertarget, renderbuffer);
#elif defined(GL_EXT_framebuffer_object)
glFramebufferRenderbufferEXT(target, attachment, renderbuffertarget, renderbuffer);
#else
os::Printer::log("glFramebufferRenderbuffer not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlActiveStencilFace(GLenum face)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlActiveStencilFaceEXT)
pGlActiveStencilFaceEXT(face);
#elif defined(GL_EXT_stencil_two_side)
glActiveStencilFaceEXT(face);
#else
os::Printer::log("glActiveStencilFace not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlDrawBuffers(GLsizei n, const GLenum *bufs)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlDrawBuffersARB)
pGlDrawBuffersARB(n, bufs);
else if (pGlDrawBuffersATI)
pGlDrawBuffersATI(n, bufs);
#elif defined(GL_ARB_draw_buffers)
glDrawBuffersARB(n, bufs);
#elif defined(GL_ATI_draw_buffers)
glDrawBuffersATI(n, bufs);
#else
os::Printer::log("glDrawBuffers not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGenBuffers(GLsizei n, GLuint *buffers)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGenBuffersARB)
pGlGenBuffersARB(n, buffers);
#elif defined(GL_ARB_vertex_buffer_object)
glGenBuffers(n, buffers);
#else
os::Printer::log("glGenBuffers not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBindBuffer(GLenum target, GLuint buffer)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlBindBufferARB)
pGlBindBufferARB(target, buffer);
#elif defined(GL_ARB_vertex_buffer_object)
glBindBuffer(target, buffer);
#else
os::Printer::log("glBindBuffer not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBufferData(GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlBufferDataARB)
pGlBufferDataARB(target, size, data, usage);
#elif defined(GL_ARB_vertex_buffer_object)
glBufferData(target, size, data, usage);
#else
os::Printer::log("glBufferData not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlDeleteBuffers(GLsizei n, const GLuint *buffers)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlDeleteBuffersARB)
pGlDeleteBuffersARB(n, buffers);
#elif defined(GL_ARB_vertex_buffer_object)
glDeleteBuffers(n, buffers);
#else
os::Printer::log("glDeleteBuffers not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBufferSubData(GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlBufferSubDataARB)
pGlBufferSubDataARB(target, offset, size, data);
#elif defined(GL_ARB_vertex_buffer_object)
glBufferSubData(target, offset, size, data);
#else
os::Printer::log("glBufferSubData not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGetBufferSubData(GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetBufferSubDataARB)
pGlGetBufferSubDataARB(target, offset, size, data);
#elif defined(GL_ARB_vertex_buffer_object)
glGetBufferSubData(target, offset, size, data);
#else
os::Printer::log("glGetBufferSubData not supported", ELL_ERROR);
#endif
}
inline void *COpenGLExtensionHandler::extGlMapBuffer(GLenum target, GLenum access)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlMapBufferARB)
return pGlMapBufferARB(target, access);
return 0;
#elif defined(GL_ARB_vertex_buffer_object)
return glMapBuffer(target, access);
#else
os::Printer::log("glMapBuffer not supported", ELL_ERROR);
return 0;
#endif
}
inline GLboolean COpenGLExtensionHandler::extGlUnmapBuffer (GLenum target)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlUnmapBufferARB)
return pGlUnmapBufferARB(target);
return false;
#elif defined(GL_ARB_vertex_buffer_object)
return glUnmapBuffer(target);
#else
os::Printer::log("glUnmapBuffer not supported", ELL_ERROR);
return false;
#endif
}
inline GLboolean COpenGLExtensionHandler::extGlIsBuffer (GLuint buffer)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlIsBufferARB)
return pGlIsBufferARB(buffer);
return false;
#elif defined(GL_ARB_vertex_buffer_object)
return glIsBuffer(buffer);
#else
os::Printer::log("glDeleteBuffers not supported", ELL_ERROR);
return false;
#endif
}
inline void COpenGLExtensionHandler::extGlGetBufferParameteriv (GLenum target, GLenum pname, GLint *params)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetBufferParameterivARB)
pGlGetBufferParameterivARB(target, pname, params);
#elif defined(GL_ARB_vertex_buffer_object)
glGetBufferParameteriv(target, pname, params);
#else
os::Printer::log("glGetBufferParameteriv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlGetBufferPointerv (GLenum target, GLenum pname, GLvoid **params)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (pGlGetBufferPointervARB)
pGlGetBufferPointervARB(target, pname, params);
#elif defined(GL_ARB_vertex_buffer_object)
glGetBufferPointerv(target, pname, params);
#else
os::Printer::log("glGetBufferPointerv not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlProvokingVertex(GLenum mode)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (FeatureAvailable[IRR_ARB_provoking_vertex] && pGlProvokingVertexARB)
pGlProvokingVertexARB(mode);
else if (FeatureAvailable[IRR_EXT_provoking_vertex] && pGlProvokingVertexEXT)
pGlProvokingVertexEXT(mode);
#elif defined(GL_ARB_provoking_vertex)
glProvokingVertex(mode);
#elif defined(GL_EXT_provoking_vertex)
glProvokingVertexEXT(mode);
#else
os::Printer::log("glProvokingVertex not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlColorMaskIndexed(GLuint buf, GLboolean r, GLboolean g, GLboolean b, GLboolean a)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (FeatureAvailable[IRR_EXT_draw_buffers2] && pGlColorMaskIndexedEXT)
pGlColorMaskIndexedEXT(buf, r, g, b, a);
#elif defined(GL_EXT_draw_buffers2)
glColorMaskIndexedEXT(buf, r, g, b, a);
#else
os::Printer::log("glColorMaskIndexed not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlEnableIndexed(GLenum target, GLuint index)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (FeatureAvailable[IRR_EXT_draw_buffers2] && pGlEnableIndexedEXT)
pGlEnableIndexedEXT(target, index);
#elif defined(GL_EXT_draw_buffers2)
glEnableIndexedEXT(target, index);
#else
os::Printer::log("glEnableIndexed not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlDisableIndexed(GLenum target, GLuint index)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (FeatureAvailable[IRR_EXT_draw_buffers2] && pGlDisableIndexedEXT)
pGlDisableIndexedEXT(target, index);
#elif defined(GL_EXT_draw_buffers2)
glDisableIndexedEXT(target, index);
#else
os::Printer::log("glDisableIndexed not supported", ELL_ERROR);
#endif
}
inline void COpenGLExtensionHandler::extGlBlendFuncIndexed(GLuint buf, GLenum src, GLenum dst)
{
#ifdef _IRR_OPENGL_USE_EXTPOINTER_
if (FeatureAvailable[IRR_ARB_draw_buffers_blend] && pGlBlendFunciARB)
pGlBlendFunciARB(buf, src, dst);
if (FeatureAvailable[IRR_AMD_draw_buffers_blend] && pGlBlendFuncIndexedAMD)
pGlBlendFuncIndexedAMD(buf, src, dst);
#elif defined(GL_ARB_draw_buffers_blend)
glBlendFunciARB(buf, src, dst);
#elif defined(GL_AMD_draw_buffers_blend)
glBlendFuncIndexedAMD(buf, src, dst);
#else
os::Printer::log("glBlendFuncIndexed not supported", ELL_ERROR);
#endif
}
-inline void COpenGLExtensionHandler::extGlProgramParameteri(GLhandleARB program, GLenum pname, GLint value)
+inline void COpenGLExtensionHandler::extGlProgramParameteri(GLuint program, GLenum pname, GLint value)
{
#if defined(_IRR_OPENGL_USE_EXTPOINTER_)
if (queryFeature(EVDF_GEOMETRY_SHADER))
{
if (pGlProgramParameteriARB)
pGlProgramParameteriARB(program, pname, value);
else if (pGlProgramParameteriEXT)
pGlProgramParameteriEXT(program, pname, value);
}
#elif defined(GL_ARB_geometry_shader4)
glProgramParameteriARB(program, pname, value);
#elif defined(GL_EXT_geometry_shader4)
glProgramParameteriEXT(program, pname, value);
#elif defined(GL_NV_geometry_program4) || defined(GL_NV_geometry_shader4)
glProgramParameteriNV(program, pname, value);
#else
os::Printer::log("glProgramParameteri not supported", ELL_ERROR);
#endif
}
}
}
#endif
#endif
|
paupawsan/Irrlicht
|
985ddfc305c91d80431c03152a8136674c465e90
|
Fix memleak found by wing64
|
diff --git a/source/Irrlicht/COBJMeshFileLoader.cpp b/source/Irrlicht/COBJMeshFileLoader.cpp
index 54ca465..c4e1c2e 100644
--- a/source/Irrlicht/COBJMeshFileLoader.cpp
+++ b/source/Irrlicht/COBJMeshFileLoader.cpp
@@ -1,936 +1,931 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_OBJ_LOADER_
#include "COBJMeshFileLoader.h"
#include "IMeshManipulator.h"
#include "IVideoDriver.h"
#include "SMesh.h"
#include "SMeshBuffer.h"
#include "SAnimatedMesh.h"
#include "IReadFile.h"
#include "IAttributes.h"
#include "fast_atof.h"
#include "coreutil.h"
#include "os.h"
namespace irr
{
namespace scene
{
#ifdef _DEBUG
#define _IRR_DEBUG_OBJ_LOADER_
#endif
static const u32 WORD_BUFFER_LENGTH = 512;
//! Constructor
COBJMeshFileLoader::COBJMeshFileLoader(scene::ISceneManager* smgr, io::IFileSystem* fs)
: SceneManager(smgr), FileSystem(fs)
{
#ifdef _DEBUG
setDebugName("COBJMeshFileLoader");
#endif
if (FileSystem)
FileSystem->grab();
}
//! destructor
COBJMeshFileLoader::~COBJMeshFileLoader()
{
if (FileSystem)
FileSystem->drop();
}
//! returns true if the file maybe is able to be loaded by this class
//! based on the file extension (e.g. ".bsp")
bool COBJMeshFileLoader::isALoadableFileExtension(const io::path& filename) const
{
return core::hasFileExtension ( filename, "obj" );
}
//! creates/loads an animated mesh from the file.
//! \return Pointer to the created mesh. Returns 0 if loading failed.
//! If you no longer need the mesh, you should call IAnimatedMesh::drop().
//! See IReferenceCounted::drop() for more information.
IAnimatedMesh* COBJMeshFileLoader::createMesh(io::IReadFile* file)
{
const long filesize = file->getSize();
if (!filesize)
return 0;
const u32 WORD_BUFFER_LENGTH = 512;
core::array<core::vector3df> vertexBuffer;
core::array<core::vector3df> normalsBuffer;
core::array<core::vector2df> textureCoordBuffer;
SObjMtl * currMtl = new SObjMtl();
Materials.push_back(currMtl);
u32 smoothingGroup=0;
const io::path fullName = file->getFileName();
const io::path relPath = FileSystem->getFileDir(fullName)+"/";
c8* buf = new c8[filesize];
memset(buf, 0, filesize);
file->read((void*)buf, filesize);
const c8* const bufEnd = buf+filesize;
// Process obj information
const c8* bufPtr = buf;
core::stringc grpName, mtlName;
bool mtlChanged=false;
bool useGroups = !SceneManager->getParameters()->getAttributeAsBool(OBJ_LOADER_IGNORE_GROUPS);
bool useMaterials = !SceneManager->getParameters()->getAttributeAsBool(OBJ_LOADER_IGNORE_MATERIAL_FILES);
while(bufPtr != bufEnd)
{
switch(bufPtr[0])
{
case 'm': // mtllib (material)
{
if (useMaterials)
{
c8 name[WORD_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(name, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
#ifdef _IRR_DEBUG_OBJ_LOADER_
os::Printer::log("Reading material file",name);
#endif
readMTL(name, relPath);
}
}
break;
case 'v': // v, vn, vt
switch(bufPtr[1])
{
case ' ': // vertex
{
core::vector3df vec;
bufPtr = readVec3(bufPtr, vec, bufEnd);
vertexBuffer.push_back(vec);
}
break;
case 'n': // normal
{
core::vector3df vec;
bufPtr = readVec3(bufPtr, vec, bufEnd);
normalsBuffer.push_back(vec);
}
break;
case 't': // texcoord
{
core::vector2df vec;
bufPtr = readUV(bufPtr, vec, bufEnd);
textureCoordBuffer.push_back(vec);
}
break;
}
break;
case 'g': // group name
{
c8 grp[WORD_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(grp, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
#ifdef _IRR_DEBUG_OBJ_LOADER_
os::Printer::log("Loaded group start",grp);
#endif
if (useGroups)
{
if (0 != grp[0])
grpName = grp;
else
grpName = "default";
}
mtlChanged=true;
}
break;
case 's': // smoothing can be a group or off (equiv. to 0)
{
c8 smooth[WORD_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(smooth, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
#ifdef _IRR_DEBUG_OBJ_LOADER_
os::Printer::log("Loaded smoothing group start",smooth);
#endif
if (core::stringc("off")==smooth)
smoothingGroup=0;
else
smoothingGroup=core::strtol10(smooth, 0);
}
break;
case 'u': // usemtl
// get name of material
{
c8 matName[WORD_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(matName, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
#ifdef _IRR_DEBUG_OBJ_LOADER_
os::Printer::log("Loaded material start",matName);
#endif
mtlName=matName;
mtlChanged=true;
}
break;
case 'f': // face
{
c8 vertexWord[WORD_BUFFER_LENGTH]; // for retrieving vertex data
video::S3DVertex v;
// Assign vertex color from currently active material's diffuse colour
if (mtlChanged)
{
// retrieve the material
SObjMtl *useMtl = findMtl(mtlName, grpName);
// only change material if we found it
if (useMtl)
currMtl = useMtl;
mtlChanged=false;
}
if (currMtl)
v.Color = currMtl->Meshbuffer->Material.DiffuseColor;
// get all vertices data in this face (current line of obj file)
const core::stringc wordBuffer = copyLine(bufPtr, bufEnd);
const c8* linePtr = wordBuffer.c_str();
const c8* const endPtr = linePtr+wordBuffer.size();
core::array<int> faceCorners;
faceCorners.reallocate(32); // should be large enough
// read in all vertices
linePtr = goNextWord(linePtr, endPtr);
while (0 != linePtr[0])
{
// Array to communicate with retrieveVertexIndices()
// sends the buffer sizes and gets the actual indices
// if index not set returns -1
s32 Idx[3];
Idx[1] = Idx[2] = -1;
// read in next vertex's data
u32 wlength = copyWord(vertexWord, linePtr, WORD_BUFFER_LENGTH, bufEnd);
// this function will also convert obj's 1-based index to c++'s 0-based index
retrieveVertexIndices(vertexWord, Idx, vertexWord+wlength+1, vertexBuffer.size(), textureCoordBuffer.size(), normalsBuffer.size());
v.Pos = vertexBuffer[Idx[0]];
if ( -1 != Idx[1] )
v.TCoords = textureCoordBuffer[Idx[1]];
else
v.TCoords.set(0.0f,0.0f);
if ( -1 != Idx[2] )
v.Normal = normalsBuffer[Idx[2]];
else
{
v.Normal.set(0.0f,0.0f,0.0f);
currMtl->RecalculateNormals=true;
}
int vertLocation;
core::map<video::S3DVertex, int>::Node* n = currMtl->VertMap.find(v);
if (n)
{
vertLocation = n->getValue();
}
else
{
currMtl->Meshbuffer->Vertices.push_back(v);
vertLocation = currMtl->Meshbuffer->Vertices.size() -1;
currMtl->VertMap.insert(v, vertLocation);
}
faceCorners.push_back(vertLocation);
// go to next vertex
linePtr = goNextWord(linePtr, endPtr);
}
// triangulate the face
for ( u32 i = 1; i < faceCorners.size() - 1; ++i )
{
// Add a triangle
currMtl->Meshbuffer->Indices.push_back( faceCorners[i+1] );
currMtl->Meshbuffer->Indices.push_back( faceCorners[i] );
currMtl->Meshbuffer->Indices.push_back( faceCorners[0] );
}
faceCorners.set_used(0); // fast clear
faceCorners.reallocate(32);
}
break;
case '#': // comment
default:
break;
} // end switch(bufPtr[0])
// eat up rest of line
bufPtr = goNextLine(bufPtr, bufEnd);
} // end while(bufPtr && (bufPtr-buf<filesize))
SMesh* mesh = new SMesh();
// Combine all the groups (meshbuffers) into the mesh
for ( u32 m = 0; m < Materials.size(); ++m )
{
if ( Materials[m]->Meshbuffer->getIndexCount() > 0 )
{
Materials[m]->Meshbuffer->recalculateBoundingBox();
if (Materials[m]->RecalculateNormals)
SceneManager->getMeshManipulator()->recalculateNormals(Materials[m]->Meshbuffer);
if (Materials[m]->Meshbuffer->Material.MaterialType == video::EMT_PARALLAX_MAP_SOLID)
{
SMesh tmp;
tmp.addMeshBuffer(Materials[m]->Meshbuffer);
IMesh* tangentMesh = SceneManager->getMeshManipulator()->createMeshWithTangents(&tmp);
mesh->addMeshBuffer(tangentMesh->getMeshBuffer(0));
tangentMesh->drop();
}
else
mesh->addMeshBuffer( Materials[m]->Meshbuffer );
}
}
// Create the Animated mesh if there's anything in the mesh
SAnimatedMesh* animMesh = 0;
if ( 0 != mesh->getMeshBufferCount() )
{
mesh->recalculateBoundingBox();
animMesh = new SAnimatedMesh();
animMesh->Type = EAMT_OBJ;
animMesh->addMesh(mesh);
animMesh->recalculateBoundingBox();
}
// Clean up the allocate obj file contents
delete [] buf;
// more cleaning up
cleanUp();
mesh->drop();
return animMesh;
}
const c8* COBJMeshFileLoader::readTextures(const c8* bufPtr, const c8* const bufEnd, SObjMtl* currMaterial, const io::path& relPath)
{
u8 type=0; // map_Kd - diffuse color texture map
// map_Ks - specular color texture map
// map_Ka - ambient color texture map
// map_Ns - shininess texture map
if ((!strncmp(bufPtr,"map_bump",8)) || (!strncmp(bufPtr,"bump",4)))
type=1; // normal map
else if ((!strncmp(bufPtr,"map_d",5)) || (!strncmp(bufPtr,"map_opacity",11)))
type=2; // opacity map
else if (!strncmp(bufPtr,"map_refl",8))
type=3; // reflection map
// extract new material's name
c8 textureNameBuf[WORD_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
f32 bumpiness = 6.0f;
bool clamp = false;
// handle options
while (textureNameBuf[0]=='-')
{
if (!strncmp(bufPtr,"-bm",3))
{
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
currMaterial->Meshbuffer->Material.MaterialTypeParam=core::fast_atof(textureNameBuf);
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
continue;
}
else
if (!strncmp(bufPtr,"-blendu",7))
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
else
if (!strncmp(bufPtr,"-blendv",7))
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
else
if (!strncmp(bufPtr,"-cc",3))
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
else
if (!strncmp(bufPtr,"-clamp",6))
bufPtr = readBool(bufPtr, clamp, bufEnd);
else
if (!strncmp(bufPtr,"-texres",7))
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
else
if (!strncmp(bufPtr,"-type",5))
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
else
if (!strncmp(bufPtr,"-mm",3))
{
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
}
else
if (!strncmp(bufPtr,"-o",2)) // texture coord translation
{
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
// next parameters are optional, so skip rest of loop if no number is found
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
if (!core::isdigit(textureNameBuf[0]))
continue;
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
if (!core::isdigit(textureNameBuf[0]))
continue;
}
else
if (!strncmp(bufPtr,"-s",2)) // texture coord scale
{
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
// next parameters are optional, so skip rest of loop if no number is found
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
if (!core::isdigit(textureNameBuf[0]))
continue;
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
if (!core::isdigit(textureNameBuf[0]))
continue;
}
else
if (!strncmp(bufPtr,"-t",2))
{
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
// next parameters are optional, so skip rest of loop if no number is found
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
if (!core::isdigit(textureNameBuf[0]))
continue;
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
if (!core::isdigit(textureNameBuf[0]))
continue;
}
// get next word
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
}
if ((type==1) && (core::isdigit(textureNameBuf[0])))
{
currMaterial->Meshbuffer->Material.MaterialTypeParam=core::fast_atof(textureNameBuf);
bufPtr = goAndCopyNextWord(textureNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
}
if (clamp)
currMaterial->Meshbuffer->Material.setFlag(video::EMF_TEXTURE_WRAP, video::ETC_CLAMP);
io::path texname(textureNameBuf);
texname.replace('\\', '/');
video::ITexture * texture = 0;
bool newTexture=false;
if (texname.size())
{
io::path texnameWithUserPath( SceneManager->getParameters()->getAttributeAsString(OBJ_TEXTURE_PATH) );
if ( texnameWithUserPath.size() )
{
texnameWithUserPath += '/';
texnameWithUserPath += texname;
}
if (FileSystem->existFile(texnameWithUserPath))
texture = SceneManager->getVideoDriver()->getTexture(texnameWithUserPath);
else if (FileSystem->existFile(texname))
{
newTexture = SceneManager->getVideoDriver()->findTexture(texname) == 0;
texture = SceneManager->getVideoDriver()->getTexture(texname);
}
else
{
newTexture = SceneManager->getVideoDriver()->findTexture(relPath + texname) == 0;
// try to read in the relative path, the .obj is loaded from
texture = SceneManager->getVideoDriver()->getTexture( relPath + texname );
}
}
if ( texture )
{
if (type==0)
currMaterial->Meshbuffer->Material.setTexture(0, texture);
else if (type==1)
{
if (newTexture)
SceneManager->getVideoDriver()->makeNormalMapTexture(texture, bumpiness);
currMaterial->Meshbuffer->Material.setTexture(1, texture);
currMaterial->Meshbuffer->Material.MaterialType=video::EMT_PARALLAX_MAP_SOLID;
currMaterial->Meshbuffer->Material.MaterialTypeParam=0.035f;
}
else if (type==2)
{
currMaterial->Meshbuffer->Material.setTexture(0, texture);
currMaterial->Meshbuffer->Material.MaterialType=video::EMT_TRANSPARENT_ADD_COLOR;
}
else if (type==3)
{
// currMaterial->Meshbuffer->Material.Textures[1] = texture;
// currMaterial->Meshbuffer->Material.MaterialType=video::EMT_REFLECTION_2_LAYER;
}
// Set diffuse material colour to white so as not to affect texture colour
// Because Maya set diffuse colour Kd to black when you use a diffuse colour map
// But is this the right thing to do?
currMaterial->Meshbuffer->Material.DiffuseColor.set(
currMaterial->Meshbuffer->Material.DiffuseColor.getAlpha(), 255, 255, 255 );
}
return bufPtr;
}
void COBJMeshFileLoader::readMTL(const c8* fileName, const io::path& relPath)
{
const io::path realFile(fileName);
io::IReadFile * mtlReader;
if (FileSystem->existFile(realFile))
mtlReader = FileSystem->createAndOpenFile(realFile);
else if (FileSystem->existFile(relPath + realFile))
- {
mtlReader = FileSystem->createAndOpenFile(relPath + realFile);
- }
else if (FileSystem->existFile(FileSystem->getFileBasename(realFile)))
- {
mtlReader = FileSystem->createAndOpenFile(FileSystem->getFileBasename(realFile));
- }
else
- {
mtlReader = FileSystem->createAndOpenFile(relPath + FileSystem->getFileBasename(realFile));
- }
if (!mtlReader) // fail to open and read file
{
os::Printer::log("Could not open material file", realFile, ELL_WARNING);
return;
}
const long filesize = mtlReader->getSize();
if (!filesize)
{
os::Printer::log("Skipping empty material file", realFile, ELL_WARNING);
+ mtlReader->drop();
return;
}
c8* buf = new c8[filesize];
mtlReader->read((void*)buf, filesize);
const c8* bufEnd = buf+filesize;
SObjMtl* currMaterial = 0;
const c8* bufPtr = buf;
while(bufPtr != bufEnd)
{
switch(*bufPtr)
{
case 'n': // newmtl
{
// if there's an existing material, store it first
if ( currMaterial )
Materials.push_back( currMaterial );
// extract new material's name
c8 mtlNameBuf[WORD_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(mtlNameBuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
currMaterial = new SObjMtl;
currMaterial->Name = mtlNameBuf;
}
break;
case 'i': // illum - illumination
if ( currMaterial )
{
const u32 COLOR_BUFFER_LENGTH = 16;
c8 illumStr[COLOR_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(illumStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
currMaterial->Illumination = (c8)atol(illumStr);
}
break;
case 'N':
if ( currMaterial )
{
switch(bufPtr[1])
{
case 's': // Ns - shininess
{
const u32 COLOR_BUFFER_LENGTH = 16;
c8 nsStr[COLOR_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(nsStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
f32 shininessValue = core::fast_atof(nsStr);
// wavefront shininess is from [0, 1000], so scale for OpenGL
shininessValue *= 0.128f;
currMaterial->Meshbuffer->Material.Shininess = shininessValue;
}
break;
case 'i': // Ni - refraction index
{
c8 tmpbuf[WORD_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(tmpbuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
}
break;
}
}
break;
case 'K':
if ( currMaterial )
{
switch(bufPtr[1])
{
case 'd': // Kd = diffuse
{
bufPtr = readColor(bufPtr, currMaterial->Meshbuffer->Material.DiffuseColor, bufEnd);
}
break;
case 's': // Ks = specular
{
bufPtr = readColor(bufPtr, currMaterial->Meshbuffer->Material.SpecularColor, bufEnd);
}
break;
case 'a': // Ka = ambience
{
bufPtr=readColor(bufPtr, currMaterial->Meshbuffer->Material.AmbientColor, bufEnd);
}
break;
case 'e': // Ke = emissive
{
bufPtr=readColor(bufPtr, currMaterial->Meshbuffer->Material.EmissiveColor, bufEnd);
}
break;
} // end switch(bufPtr[1])
} // end case 'K': if ( 0 != currMaterial )...
break;
case 'b': // bump
case 'm': // texture maps
if (currMaterial)
{
bufPtr=readTextures(bufPtr, bufEnd, currMaterial, relPath);
}
break;
case 'd': // d - transparency
if ( currMaterial )
{
const u32 COLOR_BUFFER_LENGTH = 16;
c8 dStr[COLOR_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(dStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
f32 dValue = core::fast_atof(dStr);
currMaterial->Meshbuffer->Material.DiffuseColor.setAlpha( (s32)(dValue * 255) );
if (dValue<1.0f)
currMaterial->Meshbuffer->Material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
}
break;
case 'T':
if ( currMaterial )
{
switch ( bufPtr[1] )
{
case 'f': // Tf - Transmitivity
const u32 COLOR_BUFFER_LENGTH = 16;
c8 redStr[COLOR_BUFFER_LENGTH];
c8 greenStr[COLOR_BUFFER_LENGTH];
c8 blueStr[COLOR_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(redStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
bufPtr = goAndCopyNextWord(greenStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
bufPtr = goAndCopyNextWord(blueStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
f32 transparency = ( core::fast_atof(redStr) + core::fast_atof(greenStr) + core::fast_atof(blueStr) ) / 3;
currMaterial->Meshbuffer->Material.DiffuseColor.setAlpha( (s32)(transparency * 255) );
if (transparency < 1.0f)
currMaterial->Meshbuffer->Material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
}
}
break;
default: // comments or not recognised
break;
} // end switch(bufPtr[0])
// go to next line
bufPtr = goNextLine(bufPtr, bufEnd);
} // end while (bufPtr)
// end of file. if there's an existing material, store it
if ( currMaterial )
Materials.push_back( currMaterial );
delete [] buf;
mtlReader->drop();
}
//! Read RGB color
const c8* COBJMeshFileLoader::readColor(const c8* bufPtr, video::SColor& color, const c8* const bufEnd)
{
const u32 COLOR_BUFFER_LENGTH = 16;
c8 colStr[COLOR_BUFFER_LENGTH];
color.setAlpha(255);
bufPtr = goAndCopyNextWord(colStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
color.setRed((s32)(core::fast_atof(colStr) * 255.0f));
bufPtr = goAndCopyNextWord(colStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
color.setGreen((s32)(core::fast_atof(colStr) * 255.0f));
bufPtr = goAndCopyNextWord(colStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd);
color.setBlue((s32)(core::fast_atof(colStr) * 255.0f));
return bufPtr;
}
//! Read 3d vector of floats
const c8* COBJMeshFileLoader::readVec3(const c8* bufPtr, core::vector3df& vec, const c8* const bufEnd)
{
const u32 WORD_BUFFER_LENGTH = 256;
c8 wordBuffer[WORD_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
vec.X=-core::fast_atof(wordBuffer); // change handedness
bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
vec.Y=core::fast_atof(wordBuffer);
bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
vec.Z=core::fast_atof(wordBuffer);
return bufPtr;
}
//! Read 2d vector of floats
const c8* COBJMeshFileLoader::readUV(const c8* bufPtr, core::vector2df& vec, const c8* const bufEnd)
{
const u32 WORD_BUFFER_LENGTH = 256;
c8 wordBuffer[WORD_BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
vec.X=core::fast_atof(wordBuffer);
bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
vec.Y=1-core::fast_atof(wordBuffer); // change handedness
return bufPtr;
}
//! Read boolean value represented as 'on' or 'off'
const c8* COBJMeshFileLoader::readBool(const c8* bufPtr, bool& tf, const c8* const bufEnd)
{
const u32 BUFFER_LENGTH = 8;
c8 tfStr[BUFFER_LENGTH];
bufPtr = goAndCopyNextWord(tfStr, bufPtr, BUFFER_LENGTH, bufEnd);
tf = strcmp(tfStr, "off") != 0;
return bufPtr;
}
COBJMeshFileLoader::SObjMtl* COBJMeshFileLoader::findMtl(const core::stringc& mtlName, const core::stringc& grpName)
{
COBJMeshFileLoader::SObjMtl* defMaterial = 0;
// search existing Materials for best match
// exact match does return immediately, only name match means a new group
for (u32 i = 0; i < Materials.size(); ++i)
{
if ( Materials[i]->Name == mtlName )
{
if ( Materials[i]->Group == grpName )
return Materials[i];
else
defMaterial = Materials[i];
}
}
// we found a partial match
if (defMaterial)
{
Materials.push_back(new SObjMtl(*defMaterial));
Materials.getLast()->Group = grpName;
return Materials.getLast();
}
// we found a new group for a non-existant material
else if (grpName.size())
{
Materials.push_back(new SObjMtl(*Materials[0]));
Materials.getLast()->Group = grpName;
return Materials.getLast();
}
return 0;
}
//! skip space characters and stop on first non-space
const c8* COBJMeshFileLoader::goFirstWord(const c8* buf, const c8* const bufEnd, bool acrossNewlines)
{
// skip space characters
if (acrossNewlines)
while((buf != bufEnd) && core::isspace(*buf))
++buf;
else
while((buf != bufEnd) && core::isspace(*buf) && (*buf != '\n'))
++buf;
return buf;
}
//! skip current word and stop at beginning of next one
const c8* COBJMeshFileLoader::goNextWord(const c8* buf, const c8* const bufEnd, bool acrossNewlines)
{
// skip current word
while(( buf != bufEnd ) && !core::isspace(*buf))
++buf;
return goFirstWord(buf, bufEnd, acrossNewlines);
}
//! Read until line break is reached and stop at the next non-space character
const c8* COBJMeshFileLoader::goNextLine(const c8* buf, const c8* const bufEnd)
{
// look for newline characters
while(buf != bufEnd)
{
// found it, so leave
if (*buf=='\n' || *buf=='\r')
break;
++buf;
}
return goFirstWord(buf, bufEnd);
}
u32 COBJMeshFileLoader::copyWord(c8* outBuf, const c8* const inBuf, u32 outBufLength, const c8* const bufEnd)
{
if (!outBufLength)
return 0;
if (!inBuf)
{
*outBuf = 0;
return 0;
}
u32 i = 0;
while(inBuf[i])
{
if (core::isspace(inBuf[i]) || &(inBuf[i]) == bufEnd)
break;
++i;
}
u32 length = core::min_(i, outBufLength-1);
for (u32 j=0; j<length; ++j)
outBuf[j] = inBuf[j];
outBuf[i] = 0;
return length;
}
core::stringc COBJMeshFileLoader::copyLine(const c8* inBuf, const c8* bufEnd)
{
if (!inBuf)
return core::stringc();
const c8* ptr = inBuf;
while (ptr<bufEnd)
{
if (*ptr=='\n' || *ptr=='\r')
break;
++ptr;
}
return core::stringc(inBuf, (u32)(ptr-inBuf+1));
}
const c8* COBJMeshFileLoader::goAndCopyNextWord(c8* outBuf, const c8* inBuf, u32 outBufLength, const c8* bufEnd)
{
inBuf = goNextWord(inBuf, bufEnd, false);
copyWord(outBuf, inBuf, outBufLength, bufEnd);
return inBuf;
}
bool COBJMeshFileLoader::retrieveVertexIndices(c8* vertexData, s32* idx, const c8* bufEnd, u32 vbsize, u32 vtsize, u32 vnsize)
{
c8 word[16] = "";
const c8* p = goFirstWord(vertexData, bufEnd);
u32 idxType = 0; // 0 = posIdx, 1 = texcoordIdx, 2 = normalIdx
u32 i = 0;
while ( p != bufEnd )
{
if ( ( core::isdigit(*p)) || (*p == '-') )
{
// build up the number
word[i++] = *p;
}
else if ( *p == '/' || *p == ' ' || *p == '\0' )
{
// number is completed. Convert and store it
word[i] = '\0';
// if no number was found index will become 0 and later on -1 by decrement
if (word[0]=='-')
{
idx[idxType] = core::strtol10(word+1,0);
idx[idxType] *= -1;
switch (idxType)
{
case 0:
idx[idxType] += vbsize;
break;
case 1:
idx[idxType] += vtsize;
break;
case 2:
idx[idxType] += vnsize;
break;
}
}
else
idx[idxType] = core::strtol10(word,0)-1;
// reset the word
word[0] = '\0';
i = 0;
// go to the next kind of index type
if (*p == '/')
{
if ( ++idxType > 2 )
{
// error checking, shouldn't reach here unless file is wrong
idxType = 0;
}
}
else
{
// set all missing values to disable (=-1)
while (++idxType < 3)
idx[idxType]=-1;
++p;
break; // while
}
}
// go to the next char
++p;
}
return true;
}
void COBJMeshFileLoader::cleanUp()
{
for (u32 i=0; i < Materials.size(); ++i )
{
Materials[i]->Meshbuffer->drop();
delete Materials[i];
}
Materials.clear();
}
} // end namespace scene
} // end namespace irr
#endif // _IRR_COMPILE_WITH_OBJ_LOADER_
|
paupawsan/Irrlicht
|
527f796151c2b52815773c1ddf1e6ec839ac4860
|
Remove some defaults from overloaded methods, in order to reduce some ambigious situations
|
diff --git a/include/IGPUProgrammingServices.h b/include/IGPUProgrammingServices.h
index c1046f8..b666648 100644
--- a/include/IGPUProgrammingServices.h
+++ b/include/IGPUProgrammingServices.h
@@ -1,367 +1,367 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __I_GPU_PROGRAMMING_SERVICES_H_INCLUDED__
#define __I_GPU_PROGRAMMING_SERVICES_H_INCLUDED__
#include "EShaderTypes.h"
#include "EMaterialTypes.h"
#include "EPrimitiveTypes.h"
#include "path.h"
namespace irr
{
namespace io
{
class IReadFile;
} // end namespace io
namespace video
{
class IVideoDriver;
class IShaderConstantSetCallBack;
//! Interface making it possible to create and use programs running on the GPU.
class IGPUProgrammingServices
{
public:
//! Destructor
virtual ~IGPUProgrammingServices() {}
//! Adds a new high-level shading material renderer to the VideoDriver.
/** Currently only HLSL/D3D9 and GLSL/OpenGL are supported.
\param vertexShaderProgram: String containing the source of the vertex
shader program. This can be 0 if no vertex program shall be used.
\param vertexShaderEntryPointName: Name of the entry function of the
vertexShaderProgram
\param vsCompileTarget: Vertex shader version the high level shader
shall be compiled to.
\param pixelShaderProgram: String containing the source of the pixel
shader program. This can be 0 if no pixel shader shall be used.
\param pixelShaderEntryPointName: Entry name of the function of the
pixelShaderEntryPointName
\param psCompileTarget: Pixel shader version the high level shader
shall be compiled to.
\param geometryShaderProgram: String containing the source of the
geometry shader program. This can be 0 if no geometry shader shall be
used.
\param geometryShaderEntryPointName: Entry name of the function of the
geometryShaderEntryPointName
\param gsCompileTarget: Geometry shader version the high level shader
shall be compiled to.
\param inType Type of vertices passed to geometry shader
\param outType Type of vertices created by geometry shader
\param verticesOut Maximal number of vertices created by geometry
shader. If 0, maximal number supported is assumed.
\param callback: Pointer to an implementation of
IShaderConstantSetCallBack in which you can set the needed vertex,
pixel, and geometry shader program constants. Set this to 0 if you
don't need this.
\param baseMaterial: Base material which renderstates will be used to
shade the material.
\param userData: a user data int. This int can be set to any value and
will be set as parameter in the callback method when calling
OnSetConstants(). In this way it is easily possible to use the same
callback method for multiple materials and distinguish between them
during the call.
\return Number of the material type which can be set in
SMaterial::MaterialType to use the renderer. -1 is returned if an error
occured, e.g. if a shader program could not be compiled or a compile
target is not reachable. The error strings are then printed to the
error log and can be catched with a custom event receiver. */
virtual s32 addHighLevelShaderMaterial(
const c8* vertexShaderProgram,
- const c8* vertexShaderEntryPointName = "main",
- E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1,
- const c8* pixelShaderProgram = 0,
- const c8* pixelShaderEntryPointName = "main",
- E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1,
- const c8* geometryShaderProgram = 0,
+ const c8* vertexShaderEntryPointName,
+ E_VERTEX_SHADER_TYPE vsCompileTarget,
+ const c8* pixelShaderProgram,
+ const c8* pixelShaderEntryPointName,
+ E_PIXEL_SHADER_TYPE psCompileTarget,
+ const c8* geometryShaderProgram,
const c8* geometryShaderEntryPointName = "main",
E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0,
scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES,
scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP,
u32 verticesOut = 0,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData = 0 ) = 0;
//! convenience function for use without geometry shaders
s32 addHighLevelShaderMaterial(
const c8* vertexShaderProgram,
const c8* vertexShaderEntryPointName = "main",
E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1,
const c8* pixelShaderProgram = 0,
const c8* pixelShaderEntryPointName = "main",
E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData = 0 )
{
return addHighLevelShaderMaterial(
vertexShaderProgram, vertexShaderEntryPointName,
vsCompileTarget, pixelShaderProgram,
pixelShaderEntryPointName, psCompileTarget,
0, "main", EGST_GS_4_0,
scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0,
callback, baseMaterial, userData);
}
//! Like IGPUProgrammingServices::addShaderMaterial(), but loads from files.
/** \param vertexShaderProgramFileName: Text file containing the source
of the vertex shader program. Set to empty string if no vertex shader
shall be created.
\param vertexShaderEntryPointName: Name of the entry function of the
vertexShaderProgram
\param vsCompileTarget: Vertex shader version the high level shader
shall be compiled to.
\param pixelShaderProgramFileName: Text file containing the source of
the pixel shader program. Set to empty string if no pixel shader shall
be created.
\param pixelShaderEntryPointName: Entry name of the function of the
pixelShaderEntryPointName
\param psCompileTarget: Pixel shader version the high level shader
shall be compiled to.
\param geometryShaderProgramFileName: String containing the source of
the geometry shader program. Set to empty string if no geometry shader
shall be created.
\param geometryShaderEntryPointName: Entry name of the function of the
geometryShaderEntryPointName
\param gsCompileTarget: Geometry shader version the high level shader
shall be compiled to.
\param inType Type of vertices passed to geometry shader
\param outType Type of vertices created by geometry shader
\param verticesOut Maximal number of vertices created by geometry
shader. If 0, maximal number supported is assumed.
\param callback: Pointer to an implementation of
IShaderConstantSetCallBack in which you can set the needed vertex,
pixel, and geometry shader program constants. Set this to 0 if you
don't need this.
\param baseMaterial: Base material which renderstates will be used to
shade the material.
\param userData: a user data int. This int can be set to any value and
will be set as parameter in the callback method when calling
OnSetConstants(). In this way it is easily possible to use the same
callback method for multiple materials and distinguish between them
during the call.
\return Number of the material type which can be set in
SMaterial::MaterialType to use the renderer. -1 is returned if an error
occured, e.g. if a shader program could not be compiled or a compile
target is not reachable. The error strings are then printed to the
error log and can be catched with a custom event receiver. */
virtual s32 addHighLevelShaderMaterialFromFiles(
const io::path& vertexShaderProgramFileName,
- const c8* vertexShaderEntryPointName = "main",
- E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1,
- const io::path& pixelShaderProgramFileName = "",
- const c8* pixelShaderEntryPointName = "main",
- E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1,
- const io::path& geometryShaderProgramFileName="",
+ const c8* vertexShaderEntryPointName,
+ E_VERTEX_SHADER_TYPE vsCompileTarget,
+ const io::path& pixelShaderProgramFileName,
+ const c8* pixelShaderEntryPointName,
+ E_PIXEL_SHADER_TYPE psCompileTarget,
+ const io::path& geometryShaderProgramFileName,
const c8* geometryShaderEntryPointName = "main",
E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0,
scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES,
scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP,
u32 verticesOut = 0,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData = 0) = 0;
//! convenience function for use without geometry shaders
s32 addHighLevelShaderMaterialFromFiles(
const io::path& vertexShaderProgramFileName,
const c8* vertexShaderEntryPointName = "main",
E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1,
const io::path& pixelShaderProgramFileName = "",
const c8* pixelShaderEntryPointName = "main",
E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData = 0)
{
return addHighLevelShaderMaterialFromFiles(
vertexShaderProgramFileName, vertexShaderEntryPointName,
vsCompileTarget, pixelShaderProgramFileName,
pixelShaderEntryPointName, psCompileTarget,
"", "main", EGST_GS_4_0,
scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0,
callback, baseMaterial, userData);
}
//! Like IGPUProgrammingServices::addShaderMaterial(), but loads from files.
/** \param vertexShaderProgram: Text file handle containing the source
of the vertex shader program. Set to 0 if no vertex shader shall be
created.
\param vertexShaderEntryPointName: Name of the entry function of the
vertexShaderProgram
\param vsCompileTarget: Vertex shader version the high level shader
shall be compiled to.
\param pixelShaderProgram: Text file handle containing the source of
the pixel shader program. Set to 0 if no pixel shader shall be created.
\param pixelShaderEntryPointName: Entry name of the function of the
pixelShaderEntryPointName
\param psCompileTarget: Pixel shader version the high level shader
shall be compiled to.
\param geometryShaderProgram: Text file handle containing the source of
the geometry shader program. Set to 0 if no geometry shader shall be
created.
\param geometryShaderEntryPointName: Entry name of the function of the
geometryShaderEntryPointName
\param gsCompileTarget: Geometry shader version the high level shader
shall be compiled to.
\param inType Type of vertices passed to geometry shader
\param outType Type of vertices created by geometry shader
\param verticesOut Maximal number of vertices created by geometry
shader. If 0, maximal number supported is assumed.
\param callback: Pointer to an implementation of
IShaderConstantSetCallBack in which you can set the needed vertex and
pixel shader program constants. Set this to 0 if you don't need this.
\param baseMaterial: Base material which renderstates will be used to
shade the material.
\param userData: a user data int. This int can be set to any value and
will be set as parameter in the callback method when calling
OnSetConstants(). In this way it is easily possible to use the same
callback method for multiple materials and distinguish between them
during the call.
\return Number of the material type which can be set in
SMaterial::MaterialType to use the renderer. -1 is returned if an
error occured, e.g. if a shader program could not be compiled or a
compile target is not reachable. The error strings are then printed to
the error log and can be catched with a custom event receiver. */
virtual s32 addHighLevelShaderMaterialFromFiles(
io::IReadFile* vertexShaderProgram,
- const c8* vertexShaderEntryPointName = "main",
- E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1,
- io::IReadFile* pixelShaderProgram = 0,
- const c8* pixelShaderEntryPointName = "main",
- E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1,
- io::IReadFile* geometryShaderProgram = 0,
+ const c8* vertexShaderEntryPointName,
+ E_VERTEX_SHADER_TYPE vsCompileTarget,
+ io::IReadFile* pixelShaderProgram,
+ const c8* pixelShaderEntryPointName,
+ E_PIXEL_SHADER_TYPE psCompileTarget,
+ io::IReadFile* geometryShaderProgram,
const c8* geometryShaderEntryPointName = "main",
E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0,
scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES,
scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP,
u32 verticesOut = 0,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData = 0) = 0;
//! convenience function for use without geometry shaders
s32 addHighLevelShaderMaterialFromFiles(
io::IReadFile* vertexShaderProgram,
const c8* vertexShaderEntryPointName = "main",
E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1,
io::IReadFile* pixelShaderProgram = 0,
const c8* pixelShaderEntryPointName = "main",
E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData = 0)
{
return addHighLevelShaderMaterialFromFiles(
vertexShaderProgram, vertexShaderEntryPointName,
vsCompileTarget, pixelShaderProgram,
pixelShaderEntryPointName, psCompileTarget,
0, "main", EGST_GS_4_0,
scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0,
callback, baseMaterial, userData);
}
//! Adds a new ASM shader material renderer to the VideoDriver
/** Note that it is a good idea to call IVideoDriver::queryFeature() in
advance to check if the IVideoDriver supports the vertex and/or pixel
shader version your are using.
The material is added to the VideoDriver like with
IVideoDriver::addMaterialRenderer() and can be used like it had been
added with that method.
\param vertexShaderProgram: String containing the source of the vertex
shader program. This can be 0 if no vertex program shall be used.
For DX8 programs, the will always input registers look like this: v0:
position, v1: normal, v2: color, v3: texture cooridnates, v4: texture
coordinates 2 if available.
For DX9 programs, you can manually set the registers using the dcl_
statements.
\param pixelShaderProgram: String containing the source of the pixel
shader program. This can be 0 if you don't want to use a pixel shader.
\param callback: Pointer to an implementation of
IShaderConstantSetCallBack in which you can set the needed vertex and
pixel shader program constants. Set this to 0 if you don't need this.
\param baseMaterial: Base material which renderstates will be used to
shade the material.
\param userData: a user data int. This int can be set to any value and
will be set as parameter in the callback method when calling
OnSetConstants(). In this way it is easily possible to use the same
callback method for multiple materials and distinguish between them
during the call.
\return Returns the number of the material type which can be set in
SMaterial::MaterialType to use the renderer. -1 is returned if an
error occured. -1 is returned for example if a vertex or pixel shader
program could not be compiled, the error strings are then printed out
into the error log, and can be catched with a custom event receiver. */
virtual s32 addShaderMaterial(const c8* vertexShaderProgram = 0,
const c8* pixelShaderProgram = 0,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData = 0) = 0;
//! Like IGPUProgrammingServices::addShaderMaterial(), but loads from files.
/** \param vertexShaderProgram: Text file containing the source of the
vertex shader program. Set to 0 if no shader shall be created.
\param pixelShaderProgram: Text file containing the source of the pixel
shader program. Set to 0 if no shader shall be created.
\param callback: Pointer to an IShaderConstantSetCallback object to
which the OnSetConstants function is called.
\param baseMaterial: baseMaterial
\param userData: a user data int. This int can be set to any value and
will be set as parameter in the callback method when calling
OnSetConstants(). In this way it is easily possible to use the same
callback method for multiple materials and distinguish between them
during the call.
\return Returns the number of the material type which can be set in
SMaterial::MaterialType to use the renderer. -1 is returned if an
error occured. -1 is returned for example if a vertex or pixel shader
program could not be compiled, the error strings are then printed out
into the error log, and can be catched with a custom event receiver. */
virtual s32 addShaderMaterialFromFiles(io::IReadFile* vertexShaderProgram,
io::IReadFile* pixelShaderProgram,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData = 0) = 0;
//! Like IGPUProgrammingServices::addShaderMaterial(), but loads from files.
/** \param vertexShaderProgramFileName: Text file name containing the
source of the vertex shader program. Set to 0 if no shader shall be
created.
\param pixelShaderProgramFileName: Text file name containing the source
of the pixel shader program. Set to 0 if no shader shall be created.
\param callback: Pointer to an IShaderConstantSetCallback object on
which the OnSetConstants function is called.
\param baseMaterial: baseMaterial
\param userData: a user data int. This int can be set to any value and
will be set as parameter in the callback method when calling
OnSetConstants(). In this way it is easily possible to use the same
callback method for multiple materials and distinguish between them
during the call.
\return Returns the number of the material type which can be set in
SMaterial::MaterialType to use the renderer. -1 is returned if an
error occured. -1 is returned for example if a vertex or pixel shader
program could not be compiled, the error strings are then printed out
into the error log, and can be catched with a custom event receiver. */
virtual s32 addShaderMaterialFromFiles(const io::path& vertexShaderProgramFileName,
const io::path& pixelShaderProgramFileName,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData = 0) = 0;
};
} // end namespace video
} // end namespace irr
#endif
diff --git a/source/Irrlicht/CD3D9Driver.h b/source/Irrlicht/CD3D9Driver.h
index 98b7725..8e6448a 100644
--- a/source/Irrlicht/CD3D9Driver.h
+++ b/source/Irrlicht/CD3D9Driver.h
@@ -1,445 +1,445 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_VIDEO_DIRECTX_9_H_INCLUDED__
#define __C_VIDEO_DIRECTX_9_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
#ifdef _IRR_WINDOWS_
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include "CNullDriver.h"
#include "IMaterialRendererServices.h"
#include <d3d9.h>
namespace irr
{
namespace video
{
struct SDepthSurface : public IReferenceCounted
{
SDepthSurface() : Surface(0)
{
#ifdef _DEBUG
setDebugName("SDepthSurface");
#endif
}
virtual ~SDepthSurface()
{
if (Surface)
Surface->Release();
}
IDirect3DSurface9* Surface;
core::dimension2du Size;
};
class CD3D9Driver : public CNullDriver, IMaterialRendererServices
{
public:
friend class CD3D9Texture;
//! constructor
CD3D9Driver(const core::dimension2d<u32>& screenSize, HWND window, bool fullscreen,
bool stencibuffer, io::IFileSystem* io, bool pureSoftware=false);
//! destructor
virtual ~CD3D9Driver();
//! applications must call this method before performing any rendering. returns false if failed.
virtual bool beginScene(bool backBuffer=true, bool zBuffer=true,
SColor color=SColor(255,0,0,0),
const SExposedVideoData& videoData=SExposedVideoData(),
core::rect<s32>* sourceRect=0);
//! applications must call this method after performing any rendering. returns false if failed.
virtual bool endScene();
//! queries the features of the driver, returns true if feature is available
virtual bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const;
//! sets transformation
virtual void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat);
//! sets a material
virtual void setMaterial(const SMaterial& material);
//! sets a render target
virtual bool setRenderTarget(video::ITexture* texture,
bool clearBackBuffer=true, bool clearZBuffer=true,
SColor color=video::SColor(0,0,0,0));
//! Sets multiple render targets
virtual bool setRenderTarget(const core::array<video::IRenderTarget>& texture,
bool clearBackBuffer=true, bool clearZBuffer=true,
SColor color=video::SColor(0,0,0,0));
//! sets a viewport
virtual void setViewPort(const core::rect<s32>& area);
//! gets the area of the current viewport
virtual const core::rect<s32>& getViewPort() const;
struct SHWBufferLink_d3d9 : public SHWBufferLink
{
SHWBufferLink_d3d9(const scene::IMeshBuffer *_MeshBuffer):
SHWBufferLink(_MeshBuffer),
vertexBuffer(0), indexBuffer(0),
vertexBufferSize(0), indexBufferSize(0) {}
IDirect3DVertexBuffer9* vertexBuffer;
IDirect3DIndexBuffer9* indexBuffer;
u32 vertexBufferSize;
u32 indexBufferSize;
};
bool updateVertexHardwareBuffer(SHWBufferLink_d3d9 *HWBuffer);
bool updateIndexHardwareBuffer(SHWBufferLink_d3d9 *HWBuffer);
//! updates hardware buffer if needed
virtual bool updateHardwareBuffer(SHWBufferLink *HWBuffer);
//! Create hardware buffer from mesh
virtual SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer* mb);
//! Delete hardware buffer (only some drivers can)
virtual void deleteHardwareBuffer(SHWBufferLink *HWBuffer);
//! Draw hardware buffer
virtual void drawHardwareBuffer(SHWBufferLink *HWBuffer);
//! draws a vertex primitive list
virtual void drawVertexPrimitiveList(const void* vertices, u32 vertexCount,
const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType,
E_INDEX_TYPE iType);
//! draws a vertex primitive list in 2d
virtual void draw2DVertexPrimitiveList(const void* vertices, u32 vertexCount,
const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType,
E_INDEX_TYPE iType);
//! draws an 2d image, using a color (if color is other then Color(255,255,255,255)) and the alpha channel of the texture if wanted.
virtual void draw2DImage(const video::ITexture* texture, const core::position2d<s32>& destPos,
const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect = 0,
SColor color=SColor(255,255,255,255), bool useAlphaChannelOfTexture=false);
//! Draws a part of the texture into the rectangle.
virtual void draw2DImage(const video::ITexture* texture, const core::rect<s32>& destRect,
const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect = 0,
const video::SColor* const colors=0, bool useAlphaChannelOfTexture=false);
//! Draws a set of 2d images, using a color and the alpha channel of the texture.
virtual void draw2DImageBatch(const video::ITexture* texture,
const core::array<core::position2d<s32> >& positions,
const core::array<core::rect<s32> >& sourceRects,
const core::rect<s32>* clipRect=0,
SColor color=SColor(255,255,255,255),
bool useAlphaChannelOfTexture=false);
//!Draws an 2d rectangle with a gradient.
virtual void draw2DRectangle(const core::rect<s32>& pos,
SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown,
const core::rect<s32>* clip);
//! Draws a 2d line.
virtual void draw2DLine(const core::position2d<s32>& start,
const core::position2d<s32>& end,
SColor color=SColor(255,255,255,255));
//! Draws a pixel.
virtual void drawPixel(u32 x, u32 y, const SColor & color);
//! Draws a 3d line.
virtual void draw3DLine(const core::vector3df& start,
const core::vector3df& end, SColor color = SColor(255,255,255,255));
//! initialises the Direct3D API
bool initDriver(const core::dimension2d<u32>& screenSize, HWND hwnd,
u32 bits, bool fullScreen, bool pureSoftware,
bool highPrecisionFPU, bool vsync, u8 antiAlias);
//! \return Returns the name of the video driver. Example: In case of the DIRECT3D8
//! driver, it would return "Direct3D8.1".
virtual const wchar_t* getName() const;
//! deletes all dynamic lights there are
virtual void deleteAllDynamicLights();
//! adds a dynamic light, returning an index to the light
//! \param light: the light data to use to create the light
//! \return An index to the light, or -1 if an error occurs
virtual s32 addDynamicLight(const SLight& light);
//! Turns a dynamic light on or off
//! \param lightIndex: the index returned by addDynamicLight
//! \param turnOn: true to turn the light on, false to turn it off
virtual void turnLightOn(s32 lightIndex, bool turnOn);
//! returns the maximal amount of dynamic lights the device can handle
virtual u32 getMaximalDynamicLightAmount() const;
//! Sets the dynamic ambient light color. The default color is
//! (0,0,0,0) which means it is dark.
//! \param color: New color of the ambient light.
virtual void setAmbientLight(const SColorf& color);
//! Draws a shadow volume into the stencil buffer.
virtual void drawStencilShadowVolume(const core::vector3df* triangles, s32 count, bool zfail);
//! Fills the stencil shadow with color.
virtual void drawStencilShadow(bool clearStencilBuffer=false,
video::SColor leftUpEdge = video::SColor(0,0,0,0),
video::SColor rightUpEdge = video::SColor(0,0,0,0),
video::SColor leftDownEdge = video::SColor(0,0,0,0),
video::SColor rightDownEdge = video::SColor(0,0,0,0));
//! Returns the maximum amount of primitives (mostly vertices) which
//! the device is able to render with one drawIndexedTriangleList
//! call.
virtual u32 getMaximalPrimitiveCount() const;
//! Enables or disables a texture creation flag.
virtual void setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag, bool enabled);
//! Sets the fog mode.
virtual void setFog(SColor color, E_FOG_TYPE fogType, f32 start,
f32 end, f32 density, bool pixelFog, bool rangeFog);
//! Only used by the internal engine. Used to notify the driver that
//! the window was resized.
virtual void OnResize(const core::dimension2d<u32>& size);
//! Can be called by an IMaterialRenderer to make its work easier.
virtual void setBasicRenderStates(const SMaterial& material, const SMaterial& lastMaterial,
bool resetAllRenderstates);
//! Returns type of video driver
virtual E_DRIVER_TYPE getDriverType() const;
//! Returns the transformation set by setTransform
virtual const core::matrix4& getTransform(E_TRANSFORMATION_STATE state) const;
//! Sets a vertex shader constant.
virtual void setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1);
//! Sets a pixel shader constant.
virtual void setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1);
//! Sets a constant for the vertex shader based on a name.
virtual bool setVertexShaderConstant(const c8* name, const f32* floats, int count);
//! Sets a constant for the pixel shader based on a name.
virtual bool setPixelShaderConstant(const c8* name, const f32* floats, int count);
//! Returns a pointer to the IVideoDriver interface. (Implementation for
//! IMaterialRendererServices)
virtual IVideoDriver* getVideoDriver();
//! Creates a render target texture.
virtual ITexture* addRenderTargetTexture(const core::dimension2d<u32>& size,
const io::path& name, const ECOLOR_FORMAT format = ECF_UNKNOWN);
//! Clears the ZBuffer.
virtual void clearZBuffer();
//! Returns an image created from the last rendered frame.
virtual IImage* createScreenShot();
//! Set/unset a clipping plane.
virtual bool setClipPlane(u32 index, const core::plane3df& plane, bool enable=false);
//! Enable/disable a clipping plane.
virtual void enableClipPlane(u32 index, bool enable);
//! Returns the graphics card vendor name.
virtual core::stringc getVendorInfo() {return VendorName;}
//! Enable the 2d override material
virtual void enableMaterial2D(bool enable=true);
//! Check if the driver was recently reset.
virtual bool checkDriverReset() {return DriverWasReset;}
// removes the depth struct from the DepthSurface array
void removeDepthSurface(SDepthSurface* depth);
//! Get the current color format of the color buffer
/** \return Color format of the color buffer. */
virtual ECOLOR_FORMAT getColorFormat() const;
//! Returns the maximum texture size supported.
virtual core::dimension2du getMaxTextureSize() const;
//! Get the current color format of the color buffer
/** \return Color format of the color buffer as D3D color value. */
D3DFORMAT getD3DColorFormat() const;
//! Get D3D color format from Irrlicht color format.
D3DFORMAT getD3DFormatFromColorFormat(ECOLOR_FORMAT format) const;
//! Get Irrlicht color format from D3D color format.
ECOLOR_FORMAT getColorFormatFromD3DFormat(D3DFORMAT format) const;
private:
//! enumeration for rendering modes such as 2d and 3d for minizing the switching of renderStates.
enum E_RENDER_MODE
{
ERM_NONE = 0, // no render state has been set yet.
ERM_2D, // 2d drawing rendermode
ERM_3D, // 3d rendering mode
ERM_STENCIL_FILL, // stencil fill mode
ERM_SHADOW_VOLUME_ZFAIL, // stencil volume draw mode
ERM_SHADOW_VOLUME_ZPASS // stencil volume draw mode
};
//! sets right vertex shader
void setVertexShader(video::E_VERTEX_TYPE newType);
//! sets the needed renderstates
bool setRenderStates3DMode();
//! sets the needed renderstates
void setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel);
//! sets the needed renderstates
void setRenderStatesStencilFillMode(bool alpha);
//! sets the needed renderstates
void setRenderStatesStencilShadowMode(bool zfail);
//! sets the current Texture
bool setActiveTexture(u32 stage, const video::ITexture* texture);
//! resets the device
bool reset();
//! returns a device dependent texture from a software surface (IImage)
//! THIS METHOD HAS TO BE OVERRIDDEN BY DERIVED DRIVERS WITH OWN TEXTURES
virtual video::ITexture* createDeviceDependentTexture(IImage* surface, const io::path& name, void* mipmapData=0);
//! returns the current size of the screen or rendertarget
virtual const core::dimension2d<u32>& getCurrentRenderTargetSize() const;
//! Check if a proper depth buffer for the RTT is available, otherwise create it.
void checkDepthBuffer(ITexture* tex);
//! Adds a new material renderer to the VideoDriver, using pixel and/or
//! vertex shaders to render geometry.
s32 addShaderMaterial(const c8* vertexShaderProgram, const c8* pixelShaderProgram,
IShaderConstantSetCallBack* callback,
E_MATERIAL_TYPE baseMaterial, s32 userData);
//! Adds a new material renderer to the VideoDriver, based on a high level shading
//! language.
virtual s32 addHighLevelShaderMaterial(
const c8* vertexShaderProgram,
- const c8* vertexShaderEntryPointName = "main",
- E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1,
- const c8* pixelShaderProgram = 0,
- const c8* pixelShaderEntryPointName = "main",
- E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1,
- const c8* geometryShaderProgram = 0,
+ const c8* vertexShaderEntryPointName,
+ E_VERTEX_SHADER_TYPE vsCompileTarget,
+ const c8* pixelShaderProgram,
+ const c8* pixelShaderEntryPointName,
+ E_PIXEL_SHADER_TYPE psCompileTarget,
+ const c8* geometryShaderProgram,
const c8* geometryShaderEntryPointName = "main",
E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0,
scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES,
scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP,
u32 verticesOut = 0,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData=0);
void createMaterialRenderers();
void draw2D3DVertexPrimitiveList(const void* vertices,
u32 vertexCount, const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType,
E_INDEX_TYPE iType, bool is3D);
D3DTEXTUREADDRESS getTextureWrapMode(const u8 clamp);
inline D3DCOLORVALUE colorToD3D(const SColor& col)
{
const f32 f = 1.0f / 255.0f;
D3DCOLORVALUE v;
v.r = col.getRed() * f;
v.g = col.getGreen() * f;
v.b = col.getBlue() * f;
v.a = col.getAlpha() * f;
return v;
}
E_RENDER_MODE CurrentRenderMode;
D3DPRESENT_PARAMETERS present;
SMaterial Material, LastMaterial;
bool ResetRenderStates; // bool to make all renderstates be reseted if set.
bool Transformation3DChanged;
bool StencilBuffer;
u8 AntiAliasing;
const ITexture* CurrentTexture[MATERIAL_MAX_TEXTURES];
bool LastTextureMipMapsAvailable[MATERIAL_MAX_TEXTURES];
core::matrix4 Matrices[ETS_COUNT]; // matrizes of the 3d mode we need to restore when we switch back from the 2d mode.
HINSTANCE D3DLibrary;
IDirect3D9* pID3D;
IDirect3DDevice9* pID3DDevice;
IDirect3DSurface9* PrevRenderTarget;
core::dimension2d<u32> CurrentRendertargetSize;
core::dimension2d<u32> CurrentDepthBufferSize;
HWND WindowId;
core::rect<s32>* SceneSourceRect;
D3DCAPS9 Caps;
E_VERTEX_TYPE LastVertexType;
SColorf AmbientLight;
core::stringc VendorName;
u16 VendorID;
core::array<SDepthSurface*> DepthBuffers;
u32 MaxTextureUnits;
u32 MaxUserClipPlanes;
f32 MaxLightDistance;
s32 LastSetLight;
enum E_CACHE_2D_ATTRIBUTES
{
EC2D_ALPHA = 0x1,
EC2D_TEXTURE = 0x2,
EC2D_ALPHA_CHANNEL = 0x4
};
u32 Cached2DModeSignature;
ECOLOR_FORMAT ColorFormat;
D3DFORMAT D3DColorFormat;
bool DeviceLost;
bool Fullscreen;
bool DriverWasReset;
bool AlphaToCoverageSupport;
};
} // end namespace video
} // end namespace irr
#endif // _IRR_COMPILE_WITH_DIRECT3D_9_
#endif // __C_VIDEO_DIRECTX_9_H_INCLUDED__
diff --git a/source/Irrlicht/COpenGLDriver.h b/source/Irrlicht/COpenGLDriver.h
index ced21f9..8f3fe20 100644
--- a/source/Irrlicht/COpenGLDriver.h
+++ b/source/Irrlicht/COpenGLDriver.h
@@ -1,491 +1,491 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in Irrlicht.h
#ifndef __C_VIDEO_OPEN_GL_H_INCLUDED__
#define __C_VIDEO_OPEN_GL_H_INCLUDED__
#include "IrrCompileConfig.h"
#include "SIrrCreationParameters.h"
namespace irr
{
class CIrrDeviceWin32;
class CIrrDeviceLinux;
class CIrrDeviceSDL;
class CIrrDeviceMacOSX;
}
#ifdef _IRR_COMPILE_WITH_OPENGL_
#include "CNullDriver.h"
#include "IMaterialRendererServices.h"
// also includes the OpenGL stuff
#include "COpenGLExtensionHandler.h"
namespace irr
{
namespace video
{
class COpenGLTexture;
class COpenGLDriver : public CNullDriver, public IMaterialRendererServices, public COpenGLExtensionHandler
{
public:
#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_
COpenGLDriver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, CIrrDeviceWin32* device);
//! inits the windows specific parts of the open gl driver
bool initDriver(SIrrlichtCreationParameters params, CIrrDeviceWin32* device);
bool changeRenderContext(const SExposedVideoData& videoData, CIrrDeviceWin32* device);
#endif
#ifdef _IRR_COMPILE_WITH_X11_DEVICE_
COpenGLDriver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, CIrrDeviceLinux* device);
//! inits the GLX specific parts of the open gl driver
bool initDriver(SIrrlichtCreationParameters params, CIrrDeviceLinux* device);
bool changeRenderContext(const SExposedVideoData& videoData, CIrrDeviceLinux* device);
#endif
#ifdef _IRR_COMPILE_WITH_SDL_DEVICE_
COpenGLDriver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, CIrrDeviceSDL* device);
#endif
#ifdef _IRR_COMPILE_WITH_OSX_DEVICE_
COpenGLDriver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, CIrrDeviceMacOSX *device);
#endif
//! generic version which overloads the unimplemented versions
bool changeRenderContext(const SExposedVideoData& videoData, void* device) {return false;}
//! destructor
virtual ~COpenGLDriver();
//! clears the zbuffer
virtual bool beginScene(bool backBuffer=true, bool zBuffer=true,
SColor color=SColor(255,0,0,0),
const SExposedVideoData& videoData=SExposedVideoData(),
core::rect<s32>* sourceRect=0);
//! presents the rendered scene on the screen, returns false if failed
virtual bool endScene();
//! sets transformation
virtual void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat);
struct SHWBufferLink_opengl : public SHWBufferLink
{
SHWBufferLink_opengl(const scene::IMeshBuffer *_MeshBuffer): SHWBufferLink(_MeshBuffer), vbo_verticesID(0),vbo_indicesID(0){}
GLuint vbo_verticesID; //tmp
GLuint vbo_indicesID; //tmp
GLuint vbo_verticesSize; //tmp
GLuint vbo_indicesSize; //tmp
};
//! updates hardware buffer if needed
virtual bool updateHardwareBuffer(SHWBufferLink *HWBuffer);
//! Create hardware buffer from mesh
virtual SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer* mb);
//! Delete hardware buffer (only some drivers can)
virtual void deleteHardwareBuffer(SHWBufferLink *HWBuffer);
//! Draw hardware buffer
virtual void drawHardwareBuffer(SHWBufferLink *HWBuffer);
//! draws a vertex primitive list
virtual void drawVertexPrimitiveList(const void* vertices, u32 vertexCount,
const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType);
//! draws a vertex primitive list in 2d
virtual void draw2DVertexPrimitiveList(const void* vertices, u32 vertexCount,
const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType);
//! queries the features of the driver, returns true if feature is available
virtual bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const
{
return FeatureEnabled[feature] && COpenGLExtensionHandler::queryFeature(feature);
}
//! Sets a material. All 3d drawing functions draw geometry now
//! using this material.
//! \param material: Material to be used from now on.
virtual void setMaterial(const SMaterial& material);
//! draws a set of 2d images, using a color and the alpha channel of the
//! texture if desired.
void draw2DImageBatch(const video::ITexture* texture,
const core::array<core::position2d<s32> >& positions,
const core::array<core::rect<s32> >& sourceRects,
const core::rect<s32>* clipRect,
SColor color,
bool useAlphaChannelOfTexture);
//! draws an 2d image, using a color (if color is other then Color(255,255,255,255)) and the alpha channel of the texture if wanted.
virtual void draw2DImage(const video::ITexture* texture, const core::position2d<s32>& destPos,
const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect = 0,
SColor color=SColor(255,255,255,255), bool useAlphaChannelOfTexture=false);
//! draws a set of 2d images, using a color and the alpha
/** channel of the texture if desired. The images are drawn
beginning at pos and concatenated in one line. All drawings
are clipped against clipRect (if != 0).
The subtextures are defined by the array of sourceRects
and are chosen by the indices given.
\param texture: Texture to be drawn.
\param pos: Upper left 2d destination position where the image will be drawn.
\param sourceRects: Source rectangles of the image.
\param indices: List of indices which choose the actual rectangle used each time.
\param clipRect: Pointer to rectangle on the screen where the image is clipped to.
This pointer can be 0. Then the image is not clipped.
\param color: Color with which the image is colored.
Note that the alpha component is used: If alpha is other than 255, the image will be transparent.
\param useAlphaChannelOfTexture: If true, the alpha channel of the texture is
used to draw the image. */
virtual void draw2DImage(const video::ITexture* texture,
const core::position2d<s32>& pos,
const core::array<core::rect<s32> >& sourceRects,
const core::array<s32>& indices,
const core::rect<s32>* clipRect=0,
SColor color=SColor(255,255,255,255),
bool useAlphaChannelOfTexture=false);
//! Draws a part of the texture into the rectangle.
virtual void draw2DImage(const video::ITexture* texture, const core::rect<s32>& destRect,
const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect = 0,
const video::SColor* const colors=0, bool useAlphaChannelOfTexture=false);
//! draw an 2d rectangle
virtual void draw2DRectangle(SColor color, const core::rect<s32>& pos,
const core::rect<s32>* clip = 0);
//!Draws an 2d rectangle with a gradient.
virtual void draw2DRectangle(const core::rect<s32>& pos,
SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown,
const core::rect<s32>* clip = 0);
//! Draws a 2d line.
virtual void draw2DLine(const core::position2d<s32>& start,
const core::position2d<s32>& end,
SColor color=SColor(255,255,255,255));
//! Draws a single pixel
virtual void drawPixel(u32 x, u32 y, const SColor & color);
//! Draws a 3d line.
virtual void draw3DLine(const core::vector3df& start,
const core::vector3df& end,
SColor color = SColor(255,255,255,255));
//! \return Returns the name of the video driver. Example: In case of the Direct3D8
//! driver, it would return "Direct3D8.1".
virtual const wchar_t* getName() const;
//! deletes all dynamic lights there are
virtual void deleteAllDynamicLights();
//! adds a dynamic light, returning an index to the light
//! \param light: the light data to use to create the light
//! \return An index to the light, or -1 if an error occurs
virtual s32 addDynamicLight(const SLight& light);
//! Turns a dynamic light on or off
//! \param lightIndex: the index returned by addDynamicLight
//! \param turnOn: true to turn the light on, false to turn it off
virtual void turnLightOn(s32 lightIndex, bool turnOn);
//! returns the maximal amount of dynamic lights the device can handle
virtual u32 getMaximalDynamicLightAmount() const;
//! Sets the dynamic ambient light color. The default color is
//! (0,0,0,0) which means it is dark.
//! \param color: New color of the ambient light.
virtual void setAmbientLight(const SColorf& color);
//! Draws a shadow volume into the stencil buffer. To draw a stencil shadow, do
//! this: First, draw all geometry. Then use this method, to draw the shadow
//! volume. Then, use IVideoDriver::drawStencilShadow() to visualize the shadow.
virtual void drawStencilShadowVolume(const core::vector3df* triangles, s32 count, bool zfail);
//! Fills the stencil shadow with color. After the shadow volume has been drawn
//! into the stencil buffer using IVideoDriver::drawStencilShadowVolume(), use this
//! to draw the color of the shadow.
virtual void drawStencilShadow(bool clearStencilBuffer=false,
video::SColor leftUpEdge = video::SColor(0,0,0,0),
video::SColor rightUpEdge = video::SColor(0,0,0,0),
video::SColor leftDownEdge = video::SColor(0,0,0,0),
video::SColor rightDownEdge = video::SColor(0,0,0,0));
//! sets a viewport
virtual void setViewPort(const core::rect<s32>& area);
//! Sets the fog mode.
virtual void setFog(SColor color, E_FOG_TYPE fogType, f32 start,
f32 end, f32 density, bool pixelFog, bool rangeFog);
//! Only used by the internal engine. Used to notify the driver that
//! the window was resized.
virtual void OnResize(const core::dimension2d<u32>& size);
//! Returns type of video driver
virtual E_DRIVER_TYPE getDriverType() const;
//! get color format of the current color buffer
virtual ECOLOR_FORMAT getColorFormat() const;
//! Returns the transformation set by setTransform
virtual const core::matrix4& getTransform(E_TRANSFORMATION_STATE state) const;
//! Can be called by an IMaterialRenderer to make its work easier.
virtual void setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial,
bool resetAllRenderstates);
//! Sets a vertex shader constant.
virtual void setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1);
//! Sets a pixel shader constant.
virtual void setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1);
//! Sets a constant for the vertex shader based on a name.
virtual bool setVertexShaderConstant(const c8* name, const f32* floats, int count);
//! Sets a constant for the pixel shader based on a name.
virtual bool setPixelShaderConstant(const c8* name, const f32* floats, int count);
//! sets the current Texture
//! Returns whether setting was a success or not.
bool setActiveTexture(u32 stage, const video::ITexture* texture);
//! disables all textures beginning with the optional fromStage parameter. Otherwise all texture stages are disabled.
//! Returns whether disabling was successful or not.
bool disableTextures(u32 fromStage=0);
//! Adds a new material renderer to the VideoDriver, using
//! extGLGetObjectParameteriv(shaderHandle, GL_OBJECT_COMPILE_STATUS_ARB, &status)
//! pixel and/or vertex shaders to render geometry.
virtual s32 addShaderMaterial(const c8* vertexShaderProgram, const c8* pixelShaderProgram,
IShaderConstantSetCallBack* callback, E_MATERIAL_TYPE baseMaterial, s32 userData);
//! Adds a new material renderer to the VideoDriver, using GLSL to render geometry.
virtual s32 addHighLevelShaderMaterial(
const c8* vertexShaderProgram,
- const c8* vertexShaderEntryPointName = "main",
- E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1,
- const c8* pixelShaderProgram = 0,
- const c8* pixelShaderEntryPointName = "main",
- E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1,
- const c8* geometryShaderProgram = 0,
+ const c8* vertexShaderEntryPointName,
+ E_VERTEX_SHADER_TYPE vsCompileTarget,
+ const c8* pixelShaderProgram,
+ const c8* pixelShaderEntryPointName,
+ E_PIXEL_SHADER_TYPE psCompileTarget,
+ const c8* geometryShaderProgram,
const c8* geometryShaderEntryPointName = "main",
E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0,
scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES,
scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP,
u32 verticesOut = 0,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData = 0);
//! Returns a pointer to the IVideoDriver interface. (Implementation for
//! IMaterialRendererServices)
virtual IVideoDriver* getVideoDriver();
//! Returns the maximum amount of primitives (mostly vertices) which
//! the device is able to render with one drawIndexedTriangleList
//! call.
virtual u32 getMaximalPrimitiveCount() const;
virtual ITexture* addRenderTargetTexture(const core::dimension2d<u32>& size,
const io::path& name, const ECOLOR_FORMAT format = ECF_UNKNOWN);
//! set or reset render target
virtual bool setRenderTarget(video::E_RENDER_TARGET target, bool clearTarget,
bool clearZBuffer, SColor color);
//! set or reset render target texture
virtual bool setRenderTarget(video::ITexture* texture, bool clearBackBuffer,
bool clearZBuffer, SColor color);
//! Sets multiple render targets
virtual bool setRenderTarget(const core::array<video::IRenderTarget>& texture,
bool clearBackBuffer=true, bool clearZBuffer=true, SColor color=SColor(0,0,0,0));
//! Clears the ZBuffer.
virtual void clearZBuffer();
//! Returns an image created from the last rendered frame.
virtual IImage* createScreenShot();
//! checks if an OpenGL error has happend and prints it
//! for performance reasons only available in debug mode
bool testGLError();
//! Set/unset a clipping plane.
//! There are at least 6 clipping planes available for the user to set at will.
//! \param index: The plane index. Must be between 0 and MaxUserClipPlanes.
//! \param plane: The plane itself.
//! \param enable: If true, enable the clipping plane else disable it.
virtual bool setClipPlane(u32 index, const core::plane3df& plane, bool enable=false);
//! Enable/disable a clipping plane.
//! There are at least 6 clipping planes available for the user to set at will.
//! \param index: The plane index. Must be between 0 and MaxUserClipPlanes.
//! \param enable: If true, enable the clipping plane else disable it.
virtual void enableClipPlane(u32 index, bool enable);
//! Enable the 2d override material
virtual void enableMaterial2D(bool enable=true);
//! Returns the graphics card vendor name.
virtual core::stringc getVendorInfo() {return VendorName;}
//! Returns the maximum texture size supported.
virtual core::dimension2du getMaxTextureSize() const;
ITexture* createDepthTexture(ITexture* texture, bool shared=true);
void removeDepthTexture(ITexture* texture);
//! Convert E_PRIMITIVE_TYPE to OpenGL equivalent
GLenum primitiveTypeToGL(scene::E_PRIMITIVE_TYPE type) const;
private:
//! clears the zbuffer and color buffer
void clearBuffers(bool backBuffer, bool zBuffer, bool stencilBuffer, SColor color);
bool updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer);
bool updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer);
void uploadClipPlane(u32 index);
//! inits the parts of the open gl driver used on all platforms
bool genericDriverInit(const core::dimension2d<u32>& screenSize, bool stencilBuffer);
//! returns a device dependent texture from a software surface (IImage)
virtual video::ITexture* createDeviceDependentTexture(IImage* surface, const io::path& name, void* mipmapData);
//! creates a transposed matrix in supplied GLfloat array to pass to OpenGL
inline void createGLMatrix(GLfloat gl_matrix[16], const core::matrix4& m);
inline void createGLTextureMatrix(GLfloat gl_matrix[16], const core::matrix4& m);
//! Set GL pipeline to desired texture wrap modes of the material
void setWrapMode(const SMaterial& material);
//! get native wrap mode value
GLint getTextureWrapMode(const u8 clamp);
//! sets the needed renderstates
void setRenderStates3DMode();
//! sets the needed renderstates
void setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel);
// returns the current size of the screen or rendertarget
virtual const core::dimension2d<u32>& getCurrentRenderTargetSize() const;
void createMaterialRenderers();
//! Assign a hardware light to the specified requested light, if any
//! free hardware lights exist.
//! \param[in] lightIndex: the index of the requesting light
void assignHardwareLight(u32 lightIndex);
//! helper function for render setup.
void createColorBuffer(const void* vertices, u32 vertexCount, E_VERTEX_TYPE vType);
//! helper function doing the actual rendering.
void renderArray(const void* indexList, u32 primitiveCount,
scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType);
core::stringw Name;
core::matrix4 Matrices[ETS_COUNT];
core::array<u8> ColorBuffer;
//! enumeration for rendering modes such as 2d and 3d for minizing the switching of renderStates.
enum E_RENDER_MODE
{
ERM_NONE = 0, // no render state has been set yet.
ERM_2D, // 2d drawing rendermode
ERM_3D // 3d rendering mode
};
E_RENDER_MODE CurrentRenderMode;
//! bool to make all renderstates reset if set to true.
bool ResetRenderStates;
bool Transformation3DChanged;
u8 AntiAlias;
SMaterial Material, LastMaterial;
COpenGLTexture* RenderTargetTexture;
const ITexture* CurrentTexture[MATERIAL_MAX_TEXTURES];
core::array<ITexture*> DepthTextures;
struct SUserClipPlane
{
SUserClipPlane() : Enabled(false) {}
core::plane3df Plane;
bool Enabled;
};
core::array<SUserClipPlane> UserClipPlanes;
core::dimension2d<u32> CurrentRendertargetSize;
core::stringc VendorName;
core::matrix4 TextureFlipMatrix;
//! Color buffer format
ECOLOR_FORMAT ColorFormat;
//! Render target type for render operations
E_RENDER_TARGET CurrentTarget;
bool Doublebuffer;
bool Stereo;
//! All the lights that have been requested; a hardware limited
//! number of them will be used at once.
struct RequestedLight
{
RequestedLight(SLight const & lightData)
: LightData(lightData), HardwareLightIndex(-1), DesireToBeOn(true) { }
SLight LightData;
s32 HardwareLightIndex; // GL_LIGHT0 - GL_LIGHT7
bool DesireToBeOn;
};
core::array<RequestedLight> RequestedLights;
#ifdef _IRR_WINDOWS_API_
HDC HDc; // Private GDI Device Context
HWND Window;
#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_
CIrrDeviceWin32 *Device;
#endif
#endif
#ifdef _IRR_COMPILE_WITH_X11_DEVICE_
GLXDrawable Drawable;
Display* X11Display;
CIrrDeviceLinux *Device;
#endif
#ifdef _IRR_COMPILE_WITH_OSX_DEVICE_
CIrrDeviceMacOSX *Device;
#endif
#ifdef _IRR_COMPILE_WITH_SDL_DEVICE_
CIrrDeviceSDL *Device;
#endif
E_DEVICE_TYPE DeviceType;
};
} // end namespace video
} // end namespace irr
#endif // _IRR_COMPILE_WITH_OPENGL_
#endif
diff --git a/tests/tests-last-passed-at.txt b/tests/tests-last-passed-at.txt
index 16c6adc..9578463 100644
--- a/tests/tests-last-passed-at.txt
+++ b/tests/tests-last-passed-at.txt
@@ -1,4 +1,4 @@
Tests finished. 51 tests of 51 passed.
Compiled as DEBUG
-Test suite pass at GMT Tue Jan 26 11:59:00 2010
+Test suite pass at GMT Wed Feb 03 19:37:45 2010
|
paupawsan/Irrlicht
|
d13c15a15d775b80f9f03ce89df662559e712aa5
|
Fix transparency just as in Demo.
|
diff --git a/examples/21.Quake3Explorer/main.cpp b/examples/21.Quake3Explorer/main.cpp
index 1367fc2..909f83f 100644
--- a/examples/21.Quake3Explorer/main.cpp
+++ b/examples/21.Quake3Explorer/main.cpp
@@ -1262,914 +1262,916 @@ void CQuake3EventHandler::SetGUIActive( s32 command)
ICameraSceneNode * camera = Game->Device->getSceneManager()->getActiveCamera ();
switch ( command )
{
case 0: Game->guiActive = 0; inputState = !Game->guiActive; break;
case 1: Game->guiActive = 1; inputState = !Game->guiActive;;break;
case 2: Game->guiActive ^= 1; inputState = !Game->guiActive;break;
case 3:
if ( camera )
inputState = !camera->isInputReceiverEnabled();
break;
}
if ( camera )
{
camera->setInputReceiverEnabled ( inputState );
Game->Device->getCursorControl()->setVisible( !inputState );
}
if ( gui.Window )
{
gui.Window->setVisible ( Game->guiActive != 0 );
}
if ( Game->guiActive &&
gui.SceneTree && Game->Device->getGUIEnvironment()->getFocus() != gui.SceneTree
)
{
gui.SceneTree->getRoot()->clearChilds();
addSceneTreeItem ( Game->Device->getSceneManager()->getRootSceneNode(), gui.SceneTree->getRoot() );
}
Game->Device->getGUIEnvironment()->setFocus ( Game->guiActive ? gui.Window: 0 );
}
/*
Handle game input
*/
bool CQuake3EventHandler::OnEvent(const SEvent& eve)
{
if ( eve.EventType == EET_LOG_TEXT_EVENT )
{
return false;
}
if ( Game->guiActive && eve.EventType == EET_GUI_EVENT )
{
if ( eve.GUIEvent.Caller == gui.MapList && eve.GUIEvent.EventType == gui::EGET_LISTBOX_SELECTED_AGAIN )
{
s32 selected = gui.MapList->getSelected();
if ( selected >= 0 )
{
stringw loadMap = gui.MapList->getListItem ( selected );
if ( 0 == MapParent || loadMap != Game->CurrentMapName )
{
printf ( "Loading map %ls\n", loadMap.c_str() );
LoadMap ( loadMap , 1 );
if ( 0 == Game->loadParam.loadSkyShader )
{
AddSky ( 1, "skydome2" );
}
CreatePlayers ();
CreateGUI ();
SetGUIActive ( 0 );
return true;
}
}
}
else
if ( eve.GUIEvent.Caller == gui.ArchiveRemove && eve.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
{
Game->Device->getFileSystem()->removeFileArchive( gui.ArchiveList->getSelected() );
Game->CurrentMapName = "";
AddArchive ( "" );
}
else
if ( eve.GUIEvent.Caller == gui.ArchiveAdd && eve.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
{
if ( 0 == gui.ArchiveFileOpen )
{
Game->Device->getFileSystem()->setFileListSystem ( FILESYSTEM_NATIVE );
gui.ArchiveFileOpen = Game->Device->getGUIEnvironment()->addFileOpenDialog ( L"Add Game Archive" , false,gui.Window );
}
}
else
if ( eve.GUIEvent.Caller == gui.ArchiveFileOpen && eve.GUIEvent.EventType == gui::EGET_FILE_SELECTED )
{
AddArchive ( gui.ArchiveFileOpen->getFileName() );
gui.ArchiveFileOpen = 0;
}
else
if ( eve.GUIEvent.Caller == gui.ArchiveFileOpen && eve.GUIEvent.EventType == gui::EGET_DIRECTORY_SELECTED )
{
AddArchive ( gui.ArchiveFileOpen->getDirectoryName() );
}
else
if ( eve.GUIEvent.Caller == gui.ArchiveFileOpen && eve.GUIEvent.EventType == gui::EGET_FILE_CHOOSE_DIALOG_CANCELLED )
{
gui.ArchiveFileOpen = 0;
}
else
if ( ( eve.GUIEvent.Caller == gui.ArchiveUp || eve.GUIEvent.Caller == gui.ArchiveDown ) &&
eve.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
{
s32 rel = eve.GUIEvent.Caller == gui.ArchiveUp ? -1 : 1;
if ( Game->Device->getFileSystem()->moveFileArchive ( gui.ArchiveList->getSelected (), rel ) )
{
s32 newIndex = core::s32_clamp ( gui.ArchiveList->getSelected() + rel, 0, gui.ArchiveList->getRowCount() - 1 );
AddArchive ( "" );
gui.ArchiveList->setSelected ( newIndex );
Game->CurrentMapName = "";
}
}
else
if ( eve.GUIEvent.Caller == gui.VideoDriver && eve.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED )
{
Game->deviceParam.DriverType = (E_DRIVER_TYPE) gui.VideoDriver->getItemData ( gui.VideoDriver->getSelected() );
}
else
if ( eve.GUIEvent.Caller == gui.VideoMode && eve.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED )
{
u32 val = gui.VideoMode->getItemData ( gui.VideoMode->getSelected() );
Game->deviceParam.WindowSize.Width = val >> 16;
Game->deviceParam.WindowSize.Height = val & 0xFFFF;
}
else
if ( eve.GUIEvent.Caller == gui.FullScreen && eve.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED )
{
Game->deviceParam.Fullscreen = gui.FullScreen->isChecked();
}
else
if ( eve.GUIEvent.Caller == gui.Bit32 && eve.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED )
{
Game->deviceParam.Bits = gui.Bit32->isChecked() ? 32 : 16;
}
else
if ( eve.GUIEvent.Caller == gui.MultiSample && eve.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED )
{
Game->deviceParam.AntiAlias = gui.MultiSample->getPos();
}
else
if ( eve.GUIEvent.Caller == gui.Tesselation && eve.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED )
{
Game->loadParam.patchTesselation = gui.Tesselation->getPos ();
}
else
if ( eve.GUIEvent.Caller == gui.Gamma && eve.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED )
{
Game->GammaValue = gui.Gamma->getPos () * 0.01f;
Game->Device->setGammaRamp ( Game->GammaValue, Game->GammaValue, Game->GammaValue, 0.f, 0.f );
}
else
if ( eve.GUIEvent.Caller == gui.SetVideoMode && eve.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
{
Game->retVal = 2;
Game->Device->closeDevice();
}
else
if ( eve.GUIEvent.Caller == gui.Window && eve.GUIEvent.EventType == gui::EGET_ELEMENT_CLOSED )
{
Game->Device->closeDevice();
}
else
if ( eve.GUIEvent.Caller == gui.Collision && eve.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED )
{
// set fly through active
Game->flyTroughState ^= 1;
Player[0].cam()->setAnimateTarget ( Game->flyTroughState == 0 );
printf ( "collision %d\n", Game->flyTroughState == 0 );
}
else
if ( eve.GUIEvent.Caller == gui.Visible_Map && eve.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED )
{
bool v = gui.Visible_Map->isChecked();
if ( MapParent )
{
printf ( "static node set visible %d\n",v );
MapParent->setVisible ( v );
}
}
else
if ( eve.GUIEvent.Caller == gui.Visible_Shader && eve.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED )
{
bool v = gui.Visible_Shader->isChecked();
if ( ShaderParent )
{
printf ( "shader node set visible %d\n",v );
ShaderParent->setVisible ( v );
}
}
else
if ( eve.GUIEvent.Caller == gui.Visible_Skydome && eve.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED )
{
if ( SkyNode )
{
bool v = !SkyNode->isVisible();
printf ( "skynode set visible %d\n",v );
SkyNode->setVisible ( v );
}
}
else
if ( eve.GUIEvent.Caller == gui.Respawn && eve.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
{
Player[0].respawn ();
}
return false;
}
// fire
if ((eve.EventType == EET_KEY_INPUT_EVENT && eve.KeyInput.Key == KEY_SPACE &&
eve.KeyInput.PressedDown == false) ||
(eve.EventType == EET_MOUSE_INPUT_EVENT && eve.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
)
{
ICameraSceneNode * camera = Game->Device->getSceneManager()->getActiveCamera ();
if ( camera && camera->isInputReceiverEnabled () )
{
useItem( Player + 0 );
}
}
// gui active
if ((eve.EventType == EET_KEY_INPUT_EVENT && eve.KeyInput.Key == KEY_F1 &&
eve.KeyInput.PressedDown == false) ||
(eve.EventType == EET_MOUSE_INPUT_EVENT && eve.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
)
{
SetGUIActive ( 2 );
}
// check if user presses the key
if ( eve.EventType == EET_KEY_INPUT_EVENT && eve.KeyInput.PressedDown == false)
{
// Escape toggles camera Input
if ( eve.KeyInput.Key == irr::KEY_ESCAPE )
{
SetGUIActive ( 3 );
}
else
if (eve.KeyInput.Key == KEY_F11)
{
// screenshot are taken without gamma!
IImage* image = Game->Device->getVideoDriver()->createScreenShot();
if (image)
{
core::vector3df pos;
core::vector3df rot;
ICameraSceneNode * cam = Game->Device->getSceneManager()->getActiveCamera ();
if ( cam )
{
pos = cam->getPosition ();
rot = cam->getRotation ();
}
static const c8 *dName[] = { "null", "software", "burning",
"d3d8", "d3d9", "opengl" };
snprintf(buf, 256, "%s_%ls_%.0f_%.0f_%.0f_%.0f_%.0f_%.0f.jpg",
dName[Game->Device->getVideoDriver()->getDriverType()],
Game->CurrentMapName.c_str(),
pos.X, pos.Y, pos.Z,
rot.X, rot.Y, rot.Z
);
path filename ( buf );
filename.replace ( '/', '_' );
printf ( "screenshot : %s\n", filename.c_str() );
Game->Device->getVideoDriver()->writeImageToFile(image, filename, 100 );
image->drop();
}
}
else
if (eve.KeyInput.Key == KEY_F9)
{
s32 value = EDS_OFF;
Game->debugState = ( Game->debugState + 1 ) & 3;
switch ( Game->debugState )
{
case 1: value = EDS_NORMALS | EDS_MESH_WIRE_OVERLAY | EDS_BBOX_ALL; break;
case 2: value = EDS_NORMALS | EDS_MESH_WIRE_OVERLAY | EDS_SKELETON; break;
}
/*
// set debug map data on/off
debugState = debugState == EDS_OFF ?
EDS_NORMALS | EDS_MESH_WIRE_OVERLAY | EDS_BBOX_ALL:
EDS_OFF;
*/
if ( ItemParent )
{
list<ISceneNode*>::ConstIterator it = ItemParent->getChildren().begin();
for (; it != ItemParent->getChildren().end(); ++it)
{
(*it)->setDebugDataVisible ( value );
}
}
if ( ShaderParent )
{
list<ISceneNode*>::ConstIterator it = ShaderParent->getChildren().begin();
for (; it != ShaderParent->getChildren().end(); ++it)
{
(*it)->setDebugDataVisible ( value );
}
}
if ( UnresolvedParent )
{
list<ISceneNode*>::ConstIterator it = UnresolvedParent->getChildren().begin();
for (; it != UnresolvedParent->getChildren().end(); ++it)
{
(*it)->setDebugDataVisible ( value );
}
}
if ( FogParent )
{
list<ISceneNode*>::ConstIterator it = FogParent->getChildren().begin();
for (; it != FogParent->getChildren().end(); ++it)
{
(*it)->setDebugDataVisible ( value );
}
}
if ( SkyNode )
{
SkyNode->setDebugDataVisible ( value );
}
}
else
if (eve.KeyInput.Key == KEY_F8)
{
// set gravity on/off
Game->gravityState ^= 1;
Player[0].cam()->setGravity ( getGravity ( Game->gravityState ? "earth" : "none" ) );
printf ( "gravity %s\n", Game->gravityState ? "earth" : "none" );
}
else
if (eve.KeyInput.Key == KEY_F7)
{
// set fly through active
Game->flyTroughState ^= 1;
Player[0].cam()->setAnimateTarget ( Game->flyTroughState == 0 );
if ( gui.Collision )
gui.Collision->setChecked ( Game->flyTroughState == 0 );
printf ( "collision %d\n", Game->flyTroughState == 0 );
}
else
if (eve.KeyInput.Key == KEY_F2)
{
Player[0].respawn ();
}
else
if (eve.KeyInput.Key == KEY_F3)
{
if ( MapParent )
{
bool v = !MapParent->isVisible ();
printf ( "static node set visible %d\n",v );
MapParent->setVisible ( v );
if ( gui.Visible_Map )
gui.Visible_Map->setChecked ( v );
}
}
else
if (eve.KeyInput.Key == KEY_F4)
{
if ( ShaderParent )
{
bool v = !ShaderParent->isVisible ();
printf ( "shader node set visible %d\n",v );
ShaderParent->setVisible ( v );
if ( gui.Visible_Shader )
gui.Visible_Shader->setChecked ( v );
}
}
else
if (eve.KeyInput.Key == KEY_F5)
{
if ( FogParent )
{
bool v = !FogParent->isVisible ();
printf ( "fog node set visible %d\n",v );
FogParent->setVisible ( v );
if ( gui.Visible_Fog )
gui.Visible_Fog->setChecked ( v );
}
}
else
if (eve.KeyInput.Key == KEY_F6)
{
if ( UnresolvedParent )
{
bool v = !UnresolvedParent->isVisible ();
printf ( "unresolved node set visible %d\n",v );
UnresolvedParent->setVisible ( v );
if ( gui.Visible_Unresolved )
gui.Visible_Unresolved->setChecked ( v );
}
}
}
// check if user presses the key C ( for crouch)
if ( eve.EventType == EET_KEY_INPUT_EVENT && eve.KeyInput.Key == KEY_KEY_C )
{
// crouch
ISceneNodeAnimatorCollisionResponse *anim = Player[0].cam ();
if ( anim && 0 == Game->flyTroughState )
{
if ( false == eve.KeyInput.PressedDown )
{
// stand up
anim->setEllipsoidRadius ( vector3df(30,45,30) );
anim->setEllipsoidTranslation ( vector3df(0,40,0));
}
else
{
// on your knees
anim->setEllipsoidRadius ( vector3df(30,20,30) );
anim->setEllipsoidTranslation ( vector3df(0,20,0));
}
return true;
}
}
return false;
}
/*
useItem
*/
void CQuake3EventHandler::useItem( Q3Player * player)
{
ISceneManager* smgr = Game->Device->getSceneManager();
ICameraSceneNode* camera = smgr->getActiveCamera();
if (!camera)
return;
SParticleImpact imp;
imp.when = 0;
// get line of camera
vector3df start = camera->getPosition();
if ( player->WeaponNode )
{
start.X += 0.f;
start.Y += 0.f;
start.Z += 0.f;
}
vector3df end = (camera->getTarget() - start);
end.normalize();
start += end*20.0f;
end = start + (end * camera->getFarValue());
triangle3df triangle;
line3d<f32> line(start, end);
// get intersection point with map
const scene::ISceneNode* hitNode;
if (smgr->getSceneCollisionManager()->getCollisionPoint(
line, Meta, end, triangle,hitNode))
{
// collides with wall
vector3df out = triangle.getNormal();
out.setLength(0.03f);
imp.when = 1;
imp.outVector = out;
imp.pos = end;
player->setAnim ( "pow" );
player->Anim[1].next += player->Anim[1].delta;
}
else
{
// doesnt collide with wall
vector3df start = camera->getPosition();
if ( player->WeaponNode )
{
//start.X += 10.f;
//start.Y += -5.f;
//start.Z += 1.f;
}
vector3df end = (camera->getTarget() - start);
end.normalize();
start += end*20.0f;
end = start + (end * camera->getFarValue());
}
// create fire ball
ISceneNode* node = 0;
node = smgr->addBillboardSceneNode( BulletParent,dimension2d<f32>(10,10), start);
node->setMaterialFlag(EMF_LIGHTING, false);
node->setMaterialTexture(0, Game->Device->getVideoDriver()->getTexture("fireball.bmp"));
+ node->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
node->setMaterialType(EMT_TRANSPARENT_ADD_COLOR);
f32 length = (f32)(end - start).getLength();
const f32 speed = 5.8f;
u32 time = (u32)(length / speed);
ISceneNodeAnimator* anim = 0;
// set flight line
anim = smgr->createFlyStraightAnimator(start, end, time);
node->addAnimator(anim);
anim->drop();
snprintf ( buf, 64, "bullet: %s on %.1f,%1.f,%1.f",
imp.when ? "hit" : "nohit", end.X, end.Y, end.Z );
node->setName ( buf );
anim = smgr->createDeleteAnimator(time);
node->addAnimator(anim);
anim->drop();
if (imp.when)
{
// create impact note
imp.when = Game->Device->getTimer()->getTime() +
(time + (s32) ( ( 1.f + Noiser::get() ) * 250.f ));
Impacts.push_back(imp);
}
// play sound
}
// rendered when bullets hit something
void CQuake3EventHandler::createParticleImpacts( u32 now )
{
ISceneManager* sm = Game->Device->getSceneManager();
struct smokeLayer
{
const c8 * texture;
f32 scale;
f32 minparticleSize;
f32 maxparticleSize;
f32 boxSize;
u32 minParticle;
u32 maxParticle;
u32 fadeout;
u32 lifetime;
};
smokeLayer smoke[] =
{
{ "smoke2.jpg", 0.4f, 1.5f, 18.f, 20.f, 20, 50, 2000, 10000 },
{ "smoke3.jpg", 0.2f, 1.2f, 15.f, 20.f, 10, 30, 1000, 12000 }
};
u32 i;
u32 g;
s32 factor = 1;
for ( g = 0; g != 2; ++g )
{
smoke[g].minParticle *= factor;
smoke[g].maxParticle *= factor;
smoke[g].lifetime *= factor;
smoke[g].boxSize *= Noiser::get() * 0.5f;
}
for ( i=0; i < Impacts.size(); ++i)
{
if (now < Impacts[i].when)
continue;
// create smoke particle system
IParticleSystemSceneNode* pas = 0;
for ( g = 0; g != 2; ++g )
{
pas = sm->addParticleSystemSceneNode(false, BulletParent, -1, Impacts[i].pos);
snprintf ( buf, 64, "bullet impact smoke at %.1f,%.1f,%1.f",
Impacts[i].pos.X,Impacts[i].pos.Y,Impacts[i].pos.Z);
pas->setName ( buf );
// create a flat smoke
vector3df direction = Impacts[i].outVector;
direction *= smoke[g].scale;
IParticleEmitter* em = pas->createBoxEmitter(
aabbox3d<f32>(-4.f,0.f,-4.f,20.f,smoke[g].minparticleSize,20.f),
direction,smoke[g].minParticle, smoke[g].maxParticle,
video::SColor(0,0,0,0),video::SColor(0,128,128,128),
250,4000, 60);
em->setMinStartSize (dimension2d<f32>( smoke[g].minparticleSize, smoke[g].minparticleSize));
em->setMaxStartSize (dimension2d<f32>( smoke[g].maxparticleSize, smoke[g].maxparticleSize));
pas->setEmitter(em);
em->drop();
// particles get invisible
IParticleAffector* paf = pas->createFadeOutParticleAffector(
video::SColor ( 0, 0, 0, 0 ), smoke[g].fadeout);
pas->addAffector(paf);
paf->drop();
// particle system life time
ISceneNodeAnimator* anim = sm->createDeleteAnimator( smoke[g].lifetime);
pas->addAnimator(anim);
anim->drop();
pas->setMaterialFlag(video::EMF_LIGHTING, false);
+ pas->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
pas->setMaterialType(video::EMT_TRANSPARENT_VERTEX_ALPHA );
pas->setMaterialTexture(0, Game->Device->getVideoDriver()->getTexture( smoke[g].texture ));
}
// play impact sound
#ifdef USE_IRRKLANG
/*
if (irrKlang)
{
audio::ISound* sound =
irrKlang->play3D(impactSound, Impacts[i].pos, false, false, true);
if (sound)
{
// adjust max value a bit to make to sound of an impact louder
sound->setMinDistance(400);
sound->drop();
}
}
*/
#endif
// delete entry
Impacts.erase(i);
i--;
}
}
/*
render
*/
void CQuake3EventHandler::Render()
{
IVideoDriver * driver = Game->Device->getVideoDriver();
if ( 0 == driver )
return;
// TODO: This does not work, yet.
const bool anaglyph=false;
if (anaglyph)
{
scene::ICameraSceneNode* cameraOld = Game->Device->getSceneManager()->getActiveCamera();
driver->beginScene(true, true, SColor(0,0,0,0));
driver->getOverrideMaterial().Material.ColorMask = ECP_NONE;
driver->getOverrideMaterial().EnableFlags = EMF_COLOR_MASK;
driver->getOverrideMaterial().EnablePasses = ESNRP_SKY_BOX +
ESNRP_SOLID +
ESNRP_TRANSPARENT +
ESNRP_TRANSPARENT_EFFECT +
ESNRP_SHADOW;
Game->Device->getSceneManager()->drawAll();
driver->clearZBuffer();
const vector3df oldPosition = cameraOld->getPosition();
const vector3df oldTarget = cameraOld->getTarget();
const matrix4 startMatrix = cameraOld->getAbsoluteTransformation();
const vector3df focusPoint = (oldTarget -
cameraOld->getAbsolutePosition()).setLength(10000) +
cameraOld->getAbsolutePosition() ;
scene::ICameraSceneNode* camera = cameraOld;//Game->Device->getSceneManager()->addCameraSceneNode();
//Left eye...
vector3df pos;
matrix4 move;
move.setTranslation( vector3df(-1.5f,0.0f,0.0f) );
pos=(startMatrix*move).getTranslation();
driver->getOverrideMaterial().Material.ColorMask = ECP_RED;
driver->getOverrideMaterial().EnableFlags = EMF_COLOR_MASK;
driver->getOverrideMaterial().EnablePasses =
ESNRP_SKY_BOX|ESNRP_SOLID|ESNRP_TRANSPARENT|
ESNRP_TRANSPARENT_EFFECT|ESNRP_SHADOW;
camera->setPosition(pos);
camera->setTarget(focusPoint);
Game->Device->getSceneManager()->drawAll();
driver->clearZBuffer();
//Right eye...
move.setTranslation( vector3df(1.5f,0.0f,0.0f) );
pos=(startMatrix*move).getTranslation();
driver->getOverrideMaterial().Material.ColorMask = ECP_GREEN + ECP_BLUE;
driver->getOverrideMaterial().EnableFlags = EMF_COLOR_MASK;
driver->getOverrideMaterial().EnablePasses =
ESNRP_SKY_BOX|ESNRP_SOLID|ESNRP_TRANSPARENT|
ESNRP_TRANSPARENT_EFFECT|ESNRP_SHADOW;
camera->setPosition(pos);
camera->setTarget(focusPoint);
Game->Device->getSceneManager()->drawAll();
driver->getOverrideMaterial().Material.ColorMask=ECP_ALL;
driver->getOverrideMaterial().EnableFlags=0;
driver->getOverrideMaterial().EnablePasses=0;
if (camera != cameraOld)
{
Game->Device->getSceneManager()->setActiveCamera(cameraOld);
camera->remove();
}
else
{
camera->setPosition(oldPosition);
camera->setTarget(oldTarget);
}
}
else
{
driver->beginScene(true, true, SColor(0,0,0,0));
Game->Device->getSceneManager()->drawAll();
}
Game->Device->getGUIEnvironment()->drawAll();
driver->endScene();
}
/*
update the generic scene node
*/
void CQuake3EventHandler::Animate()
{
u32 now = Game->Device->getTimer()->getTime();
Q3Player * player = Player + 0;
checkTimeFire ( player->Anim, 4, now );
// Query Scene Manager attributes
if ( player->Anim[0].flags & FIRED )
{
ISceneManager *smgr = Game->Device->getSceneManager ();
wchar_t msg[128];
IVideoDriver * driver = Game->Device->getVideoDriver();
IAttributes * attr = smgr->getParameters();
swprintf ( msg, 128,
L"Q3 %s [%ls], FPS:%03d Tri:%.03fm Cull %d/%d nodes (%d,%d,%d)",
Game->CurrentMapName.c_str(),
driver->getName(),
driver->getFPS (),
(f32) driver->getPrimitiveCountDrawn( 0 ) * ( 1.f / 1000000.f ),
attr->getAttributeAsInt ( "culled" ),
attr->getAttributeAsInt ( "calls" ),
attr->getAttributeAsInt ( "drawn_solid" ),
attr->getAttributeAsInt ( "drawn_transparent" ),
attr->getAttributeAsInt ( "drawn_transparent_effect" )
);
Game->Device->setWindowCaption( msg );
swprintf ( msg, 128,
L"%03d fps, F1 GUI on/off, F2 respawn, F3-F6 toggle Nodes, F7 Collision on/off"
L", F8 Gravity on/off, Right Mouse Toggle GUI",
Game->Device->getVideoDriver()->getFPS ()
);
if ( gui.StatusLine )
gui.StatusLine->setText ( msg );
player->Anim[0].flags &= ~FIRED;
}
// idle..
if ( player->Anim[1].flags & FIRED )
{
if ( strcmp ( player->animation, "idle" ) )
player->setAnim ( "idle" );
player->Anim[1].flags &= ~FIRED;
}
createParticleImpacts ( now );
}
/* The main game states
*/
void runGame ( GameData *game )
{
if ( game->retVal >= 3 )
return;
game->Device = (*game->createExDevice) ( game->deviceParam );
if ( 0 == game->Device)
{
// could not create selected driver.
game->retVal = 0;
return;
}
// create an event receiver based on current game data
CQuake3EventHandler *eventHandler = new CQuake3EventHandler( game );
// load stored config
game->load ( "explorer.cfg" );
// add our media directory and archive to the file system
for ( u32 i = 0; i < game->CurrentArchiveList.size(); ++i )
{
eventHandler->AddArchive ( game->CurrentArchiveList[i] );
}
// Load a Map or startup to the GUI
if ( game->CurrentMapName.size () )
{
eventHandler->LoadMap ( game->CurrentMapName, 1 );
if ( 0 == game->loadParam.loadSkyShader )
eventHandler->AddSky ( 1, "skydome2" );
eventHandler->CreatePlayers ();
eventHandler->CreateGUI ();
eventHandler->SetGUIActive ( 0 );
// set player to last position on restart
if ( game->retVal == 2 )
{
eventHandler->GetPlayer( 0 )->setpos ( game->PlayerPosition, game->PlayerRotation );
}
}
else
{
// start up empty
eventHandler->AddSky ( 1, "skydome2" );
eventHandler->CreatePlayers ();
eventHandler->CreateGUI ();
eventHandler->SetGUIActive ( 1 );
background_music ( "IrrlichtTheme.ogg" );
}
game->retVal = 3;
while( game->Device->run() )
{
eventHandler->Animate ();
eventHandler->Render ();
//if ( !game->Device->isWindowActive() )
game->Device->yield();
}
game->Device->setGammaRamp ( 1.f, 1.f, 1.f, 0.f, 0.f );
delete eventHandler;
}
#if defined (_IRR_WINDOWS_) && 0
#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
#endif
/* The main routine, doing all setup
*/
int IRRCALLCONV main(int argc, char* argv[])
{
path prgname(argv[0]);
GameData game ( deletePathFromPath ( prgname, 1 ) );
// dynamically load irrlicht
const c8 * dllName = argc > 1 ? argv[1] : "irrlicht.dll";
game.createExDevice = load_createDeviceEx ( dllName );
if ( 0 == game.createExDevice )
{
game.retVal = 3;
printf ( "Could not load %s.\n", dllName );
return game.retVal; // could not load dll
}
// start without asking for driver
game.retVal = 1;
do
{
// if driver could not created, ask for another driver
if ( game.retVal == 0 )
{
game.setDefault ();
// ask user for driver
game.deviceParam.DriverType=driverChoiceConsole();
if (game.deviceParam.DriverType==video::EDT_COUNT)
game.retVal = 3;
}
runGame ( &game );
} while ( game.retVal < 3 );
return game.retVal;
}
/*
**/
|
paupawsan/Irrlicht
|
1b23d7f50da185d274440dfb692a83a7dd27d203
|
Full upgrade-guide.txt.
|
diff --git a/doc/upgrade-guide.txt b/doc/upgrade-guide.txt
index 77dfbc6..ee638b9 100644
--- a/doc/upgrade-guide.txt
+++ b/doc/upgrade-guide.txt
@@ -1993,524 +1993,899 @@ Changed parameters to use io::path (instead of C strings/stringc)
virtual bool changeWorkingDirectoryTo(const path& newDirectory) =0;
virtual path getAbsolutePath(const path& filename) const =0;
virtual path getFileDir(const path& filename) const =0;
virtual path getFileBasename(const path& filename, bool keepExtension=true) const =0;
virtual bool existFile(const path& filename) const =0;
virtual IXMLReader* createXMLReader(const path& filename) =0;
virtual IXMLReaderUTF8* createXMLReaderUTF8(const path& filename) =0;
virtual IXMLWriter* createXMLWriter(const path& filename) =0;
New methods
virtual IReadFile* createLimitReadFile(const path& fileName,
IReadFile* alreadyOpenedFile, long pos, long areaSize) =0;
virtual IWriteFile* createMemoryWriteFile(void* memory, s32 len, const path& fileName, bool deleteMemoryWhenDropped=false) =0;
virtual bool addFileArchive(const path& filename, bool ignoreCase=true, bool ignorePaths=true,
E_FILE_ARCHIVE_TYPE archiveType=EFAT_UNKNOWN) =0;
virtual void addArchiveLoader(IArchiveLoader* loader) =0;
virtual u32 getFileArchiveCount() const =0;
virtual bool removeFileArchive(u32 index) =0;
virtual bool removeFileArchive(const path& filename) =0;
virtual bool moveFileArchive(u32 sourceIndex, s32 relative) =0;
virtual IFileArchive* getFileArchive(u32 index) =0;
virtual path& flattenFilename(path& directory, const path& root="/") const =0;
virtual EFileSystemType setFileListSystem(EFileSystemType listType) =0;
Deprecate methods
virtual bool addZipFileArchive(const c8* filename, bool ignoreCase=true, bool ignorePaths=true)
virtual bool addFolderFileArchive(const c8* filename, bool ignoreCase=true, bool ignorePaths=true)
virtual bool addPakFileArchive(const c8* filename, bool ignoreCase=true, bool ignorePaths=true)
Constification of method
virtual IFileList* createFileList() =0;
IrrlichtDevice.h
Renamed method (from setResizeAble)
virtual void setResizable(bool resize=false) = 0;
New methods
virtual void minimizeWindow() =0;
virtual void maximizeWindow() =0;
virtual void restoreWindow() =0;
virtual bool setGammaRamp(f32 red, f32 green, f32 blue,
f32 relativebrightness, f32 relativecontrast) =0;
virtual bool getGammaRamp(f32 &red, f32 &green, f32 &blue,
f32 &brightness, f32 &contrast) =0;
virtual E_DEVICE_TYPE getType() const = 0;
irrMath.h
Renamed from ROUNDING_ERROR_32
const f32 ROUNDING_ERROR_f32 = 0.000001f;
Renamed from ROUNDING_ERROR_64
const f64 ROUNDING_ERROR_f64 = 0.00000001;
New constant
const s32 ROUNDING_ERROR_S32 = 1;
New methods
bool isnotzero(const f32 a, const f32 tolerance = ROUNDING_ERROR_f32)
u16 if_c_a_else_b ( const s16 condition, const u16 a, const u16 b )
f32 squareroot(const f32 f)
f64 squareroot(const f64 f)
s32 squareroot(const s32 f)
f64 reciprocal_squareroot(const f64 x)
s32 reciprocal_squareroot(const s32 x)
f64 reciprocal ( const f64 f )
IGPUProgrammingServices.h
Changed parameters to use io::path
virtual s32 addHighLevelShaderMaterialFromFiles(
const io::path& vertexShaderProgramFileName,
const c8* vertexShaderEntryPointName = "main",
E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1,
const io::path& pixelShaderProgramFileName = "",
const c8* pixelShaderEntryPointName = "main",
E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1,
IShaderConstantSetCallBack* callback = 0,
virtual s32 addShaderMaterialFromFiles(const io::path& vertexShaderProgramFileName,
const io::path& pixelShaderProgramFileName,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData = 0) = 0;
ISceneNode.h
New method
virtual bool isTrulyVisible() const
IEventReceiver.h
New enum values
EMIE_MOUSE_DOUBLE_CLICK,
EMIE_MOUSE_TRIPLE_CLICK,
EGET_DIRECTORY_SELECTED,
EGET_EDITBOX_CHANGED,
EGET_EDITBOX_MARKING_CHANGED,
EGET_TREEVIEW_NODE_DESELECT,
EGET_TREEVIEW_NODE_SELECT,
EGET_TREEVIEW_NODE_EXPAND,
EGET_TREEVIEW_NODE_COLLAPS,
EGET_COUNT
New enum
enum E_MOUSE_BUTTON_STATE_MASK
New members
bool Shift:1;
bool Control:1;
u32 ButtonStates;
New methods
bool isLeftPressed() const { return 0 != ( ButtonStates & EMBSM_LEFT ); }
bool isRightPressed() const { return 0 != ( ButtonStates & EMBSM_RIGHT ); }
bool isMiddlePressed() const { return 0 != ( ButtonStates & EMBSM_MIDDLE ); }
Types changed
bool PressedDown:1;
bool Shift:1;
bool Control:1;
IGUISpriteBank.h
New method
virtual void draw2DSpriteBatch(const core::array<u32>& indices, const core::array<core::position2di>& pos,
const core::rect<s32>* clip=0,
const video::SColor& color= video::SColor(255,255,255,255),
u32 starttime=0, u32 currenttime=0,
bool loop=true, bool center=false) = 0;
SMaterial.h
New enums
enum E_COMPARISON_FUNC
enum E_COLOR_PLANE
enum E_ALPHA_SOURCE
enum E_ANTI_ALIASING_MODE
enum E_COLOR_MATERIAL
New parameters
inline f32 pack_texureBlendFunc ( const E_BLEND_FACTOR srcFact, const E_BLEND_FACTOR dstFact, const E_MODULATE_FUNC modulate=EMFN_MODULATE_1X, const u32 alphaSource=EAS_TEXTURE )
inline void unpack_texureBlendFunc ( E_BLEND_FACTOR &srcFact, E_BLEND_FACTOR &dstFact,
E_MODULATE_FUNC &modulo, u32& alphaSource, const f32 param )
New methods
inline bool textureBlendFunc_hasAlpha ( const E_BLEND_FACTOR factor )
Default value set elsewhere now (see IrrCompileConfig.h)
const u32 MATERIAL_MAX_TEXTURES = _IRR_MATERIAL_MAX_TEXTURES_;
Types changed
u8 ZBuffer;
bool Wireframe:1;
bool PointCloud:1;
bool GouraudShading:1;
bool Lighting:1;
bool ZWriteEnable:1;
bool BackfaceCulling:1;
bool FrontfaceCulling:1;
bool FogEnable:1;
bool NormalizeNormals:1;
New members
u8 AntiAliasing;
u8 ColorMask:4;
u8 ColorMaterial:3;
New constant
IRRLICHT_API extern SMaterial IdentityMaterial;
IGUISkin.h
New enum values
EGDS_TITLEBARTEXT_DISTANCE_X,
EGDS_TITLEBARTEXT_DISTANCE_Y,
quaternion.h
New parameters
void getMatrix( matrix4 &dest, const vector3df &translation ) const;
New method
void getMatrixCenter( matrix4 &dest, const vector3df ¢er, const vector3df &translation ) const;
ISceneNodeAnimatorCameraFPS.h
New method
virtual void setInvertMouse(bool invert) = 0;
IImage.h
New enum values
/** Floating Point formats. The following formats may only be used for render target textures. */
ECF_R16F,
ECF_G16R16F,
ECF_A16B16G16R16F,
ECF_R32F,
ECF_G32R32F,
ECF_A32B32G32R32F,
ECF_UNKNOWN
Signedness change
virtual const core::dimension2d<u32>& getDimension() const = 0;
virtual void copyToScaling(void* target, u32 width, u32 height, ECOLOR_FORMAT format=ECF_A8R8G8B8, u32 pitch=0) =0;
New parameter
virtual void setPixel(u32 x, u32 y, const SColor &color, bool blend = false ) = 0;
New method
virtual void copyToScalingBoxFilter(IImage* target, s32 bias = 0, bool blend = false) = 0;
static u32 getBitsPerPixelFromFormat(const ECOLOR_FORMAT format)
static bool isRenderTargetOnlyFormat(const ECOLOR_FORMAT format)
IVideoDriver.h
New enum values (only existing if _IRR_MATERIAL_MAX_TEXTURES_ large enough)
ETS_TEXTURE_4
ETS_TEXTURE_5
ETS_TEXTURE_6
ETS_TEXTURE_7
New enums
enum E_RENDER_TARGET
enum E_FOG_TYPE
New type
struct SOverrideMaterial
New methods
virtual u32 getImageLoaderCount() const = 0;
virtual IImageLoader* getImageLoader(u32 n) = 0;
virtual u32 getImageWriterCount() const = 0;
virtual IImageWriter* getImageWriter(u32 n) = 0;
virtual bool setRenderTarget(E_RENDER_TARGET target, bool clearTarget=true,
bool clearZBuffer=true, SColor color=video::SColor(0,0,0,0)) =0;
virtual void draw2DVertexPrimitiveList(const void* vertices, u32 vertexCount,
const void* indexList, u32 primCount,
E_VERTEX_TYPE vType=EVT_STANDARD,
scene::E_PRIMITIVE_TYPE pType=scene::EPT_TRIANGLES,
E_INDEX_TYPE iType=EIT_16BIT) =0;
virtual void draw2DImageBatch(const video::ITexture* texture,
const core::array<core::position2d<s32> >& positions,
const core::array<core::rect<s32> >& sourceRects,
const core::rect<s32>* clipRect=0,
SColor color=SColor(255,255,255,255),
bool useAlphaChannelOfTexture=false) =0;
virtual void turnLightOn(s32 lightIndex, bool turnOn) =0;
virtual bool writeImageToFile(IImage* image, io::IWriteFile* file, u32 param =0) =0;
virtual IImage* createImage(ITexture* texture,
const core::position2d<s32>& pos, const core::dimension2d<u32>& size) =0;
virtual void setMinHardwareBufferVertexCount(u32 count) =0;
virtual SOverrideMaterial& getOverrideMaterial() =0;
Changed parameters to use io::path
virtual ITexture* getTexture(const io::path& filename) = 0;
virtual void renameTexture(ITexture* texture, const io::path& newName) = 0;
virtual ITexture* addTexture(const io::path& name, IImage* image) = 0;
virtual IImage* createImageFromFile(const io::path& filename) = 0;
virtual bool writeImageToFile(IImage* image, const io::path& filename, u32 param = 0) = 0;
virtual video::ITexture* findTexture(const io::path& filename) = 0;
Changed signedness
virtual ITexture* addTexture(const core::dimension2d<u32>& size,
const io::path& name, ECOLOR_FORMAT format = ECF_A8R8G8B8) = 0;
virtual const core::dimension2d<u32>& getScreenSize() const =0;
virtual const core::dimension2d<u32>& getCurrentRenderTargetSize() const =0;
virtual IImage* createImageFromData(ECOLOR_FORMAT format,
const core::dimension2d<u32>& size, void *data,
bool ownForeignMemory=false,
bool deleteMemory = true) =0;
virtual IImage* createImage(ECOLOR_FORMAT format, const core::dimension2d<u32>& size) =0;
virtual IImage* createImage(IImage* imageToCopy,
const core::position2d<s32>& pos,
const core::dimension2d<u32>& size) =0;
virtual void OnResize(const core::dimension2d<u32>& size) =0;
Changed signedness and usage of io::path
virtual ITexture* addRenderTargetTexture(const core::dimension2d<u32>& size,
const io::path& name = "rt", const ECOLOR_FORMAT format = ECF_UNKNOWN) =0;
Removed deprecated method
virtual ITexture* createRenderTargetTexture(const core::dimension2d<s32>& size,
const c8* name=0) =0;
New parameter
virtual void makeColorKeyTexture(video::ITexture* texture,
video::SColor color, bool zeroTexels = false) const =0;
virtual void makeColorKeyTexture(video::ITexture* texture,
core::position2d<s32> colorKeyPixelPos, bool zeroTexels = false) const =0;
Changed parameters
virtual void setFog(SColor color=SColor(0,255,255,255),
E_FOG_TYPE fogType=EFT_FOG_LINEAR,
f32 start=50.0f, f32 end=100.0f, f32 density=0.01f,
bool pixelFog=false, bool rangeFog=false) =0;
Changed return types
virtual s32 addDynamicLight(const SLight& light) =0;
EDriverFeatures.h
New enum values
EVDF_ALPHA_TO_COVERAGE,
EVDF_COLOR_MASK,
IGUIScrollBar.h
New methods
virtual void setMin(s32 max) = 0;
virtual s32 getMin() const = 0;
IQ3LevelMesh.h
Removed method
virtual void releaseMesh(s32 index) = 0;
Made return value non-const
virtual quake3::tQ3EntityList& getEntityList() = 0;
ISceneCollisionManager.h
New parameter
virtual bool getCollisionPoint(const core::line3d<f32>& ray,
ITriangleSelector* selector, core::vector3df& outCollisionPoint,
core::triangle3df& outTriangle, const ISceneNode*& outNode) =0;
virtual core::vector3df getCollisionResultPosition(
ITriangleSelector* selector,
const core::vector3df &ellipsoidPosition,
const core::vector3df& ellipsoidRadius,
const core::vector3df& ellipsoidDirectionAndSpeed,
core::triangle3df& triout,
core::vector3df& hitPosition,
bool& outFalling,
const ISceneNode*& outNode,
f32 slidingSpeed = 0.0005f,
const core::vector3df& gravityDirectionAndSpeed = core::vector3df(0.0f, 0.0f, 0.0f)) = 0;
Made parameter const&
virtual core::line3d<f32> getRayFromScreenCoordinates(
const core::position2d<s32> & pos, ICameraSceneNode* camera = 0) = 0;
virtual core::position2d<s32> getScreenCoordinatesFrom3DPosition(
const core::vector3df & pos, ICameraSceneNode* camera=0) = 0;
Made parameter const& and added new parameter
virtual ISceneNode* getSceneNodeFromScreenCoordinatesBB(const core::position2d<s32>& pos,
s32 idBitMask=0, bool bNoDebugObjects=false, ISceneNode* root=0) =0;
virtual ISceneNode* getSceneNodeFromRayBB(const core::line3d<f32>& ray,
s32 idBitMask=0, bool bNoDebugObjects=false, ISceneNode* root=0) =0;
New method
virtual ISceneNode* getSceneNodeAndCollisionPointFromRay(
core::line3df ray, core::vector3df & outCollisionPoint,
core::triangle3df & outTriangle, s32 idBitMask = 0,
ISceneNode * collisionRootNode = 0, bool noDebugObjects = false) = 0;
irrlicht.h
Changed interface of method (qualifiers and signedness)
extern "C" IRRLICHT_API IrrlichtDevice* IRRCALLCONV createDevice(
video::E_DRIVER_TYPE deviceType = video::EDT_SOFTWARE,
// parantheses are necessary for some compilers
const core::dimension2d<u32>& windowSize = (core::dimension2d<u32>(640,480)),
u32 bits = 16,
bool fullscreen = false,
bool stencilbuffer = false,
bool vsync = false,
IEventReceiver* receiver = 0);
extern "C" IRRLICHT_API IrrlichtDevice* IRRCALLCONV createDeviceEx(
const SIrrlichtCreationParameters& parameters);
IImageLoader.h
Changed parameters to use io::path
virtual bool isALoadableFileExtension(const io::path& filename) const = 0;
IGUIWindow.h
New methods
virtual bool isDraggable() const = 0;
virtual void setDraggable(bool draggable) = 0;
virtual void setDrawBackground(bool draw) = 0;
virtual bool getDrawBackground() const = 0;
virtual void setDrawTitlebar(bool draw) = 0;
virtual bool getDrawTitlebar() const = 0;
ICameraSceneNode.h
New methods
virtual void setViewMatrixAffector(const core::matrix4& affector) =0;
virtual const core::matrix4& getViewMatrixAffector() const =0;
EGUIElementTypes.h
New enum value
EGUIET_TREE_VIEW,
IImageWriter.h
Changed parameters to use io::path
virtual bool isAWriteableFileExtension(const io::path& filename) const = 0;
SIrrCreationParameters.h
Added members
E_DEVICE_TYPE DeviceType;
bool Doublebuffer;
bool Stereobuffer;
Changed signedness
core::dimension2d<u32> WindowSize;
Changed type (from bool)
u8 AntiAlias;
matrix4.h
New methods
bool isOrthogonal() const;
CMatrix4<T>& buildRotateFromTo(const core::vector3df& from, const core::vector3df& to);
void setRotationCenter(const core::vector3df& center, const core::vector3df& translate);
void buildAxisAlignedBillboard( const core::vector3df& camPos,
const core::vector3df& center, const core::vector3df& translation,
const core::vector3df& axis, const core::vector3df& from);
IWriteFile.h
Changed parameters to use io::path
virtual const path& getFileName() const = 0;
IGUITable.h
New methods
virtual void setSelected( s32 index ) = 0;
Changed type (from wide c string)
virtual void setCellText(u32 rowIndex, u32 columnIndex, const core::stringw& text) = 0;
virtual void setCellText(u32 rowIndex, u32 columnIndex, const core::stringw& text, video::SColor color) = 0;
SKeyMap.h
New enum value
EKA_CROUCH,
IGUIFont.h
Changed type (from wide c string)
virtual void draw(const core::stringw& text, const core::rect<s32>& position,
video::SColor color, bool hcenter=false, bool vcenter=false,
const core::rect<s32>* clip=0) = 0;
Changed signedness
virtual core::dimension2d<u32> getDimension(const wchar_t* text) const = 0;
New method
virtual void setInvisibleCharacters( const wchar_t *s ) = 0;
IMeshCache.h
Changed parameters to use io::path
virtual void addMesh(const io::path& filename, IAnimatedMesh* mesh) = 0;
virtual IAnimatedMesh* getMeshByFilename(const io::path& filename) = 0;
virtual const io::path& getMeshFilename(u32 index) const = 0;
virtual const io::path& getMeshFilename(const IAnimatedMesh* const mesh) const = 0;
virtual const io::path& getMeshFilename(const IMesh* const mesh) const = 0;
virtual bool setMeshFilename(u32 index, const io::path& filename) = 0;
virtual bool setMeshFilename(const IAnimatedMesh* const mesh, const io::path& filename) = 0;
virtual bool setMeshFilename(const IMesh* const mesh, const io::path& filename) = 0;
virtual bool isMeshLoaded(const io::path& filename) = 0;
IGUIButton.h
Added default value
virtual void setImage(video::ITexture* image=0) = 0;
virtual void setPressedImage(video::ITexture* image=0) = 0;
virtual void setSpriteBank(IGUISpriteBank* bank=0) = 0;
virtual void setIsPushButton(bool isPushButton=true) = 0;
virtual void setPressed(bool pressed=true) = 0;
virtual void setUseAlphaChannel(bool useAlphaChannel=true) = 0;
virtual void setDrawBorder(bool border=true) = 0;
New methods
virtual void setScaleImage(bool scaleImage=true) = 0;
virtual bool isScalingImage() const = 0;
position2d.h
Replaced by vector2d
IGUIImageList.h
New interface
class IGUIImageList : public virtual IReferenceCounted
rect.h
Added second template parameter to allow mismatched signedness
template <class U>
rect(const position2d<T>& pos, const dimension2d<U>& size)
IParticleEmitter.h
Removed wrong overrides
virtual void serializeAttributes(io::IAttributes* out,
io::SAttributeReadWriteOptions* options=0) const {}
virtual s32 deserializeAttributes(s32 startIndex, io::IAttributes* in,
io::SAttributeReadWriteOptions* options=0) { return 0; }
IOSOperator.h
Return const string
virtual const c8* getTextFromClipboard() const = 0;
IGUIElement.h
Signedness change
void setMaxSize(core::dimension2du size)
void setMinSize(core::dimension2du size)
IReadFile.h
Changed parameters to use io::path
virtual const io::path& getFileName() const = 0;
IReadFile* createReadFile(const io::path& fileName);
IReadFile* createLimitReadFile(const io::path& fileName, IReadFile* alreadyOpenedFile, long pos, long areaSize);
IReadFile* createMemoryReadFile(void* memory, long size, const io::path& fileName, bool deleteMemoryWhenDropped);
IGUITabControl.h
New methods
virtual void setTabMaxWidth(s32 width ) = 0;
virtual s32 getTabMaxWidth() const = 0;
IParticleAffector.h
Removed wrong overrides
virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const {}
virtual s32 deserializeAttributes(s32 startIndex, io::IAttributes* in, io::SAttributeReadWriteOptions* options=0) { return 0; }
ILogger.h
New method
virtual void log(const c8* text, const wchar_t* hint, ELOG_LEVEL ll=ELL_INFORMATION) = 0;
vector2d.h
New methods
vector2d(const dimension2d<T>& other) : X(other.Width), Y(other.Height) {}
vector2d<T>& operator=(const dimension2d<T>& other) { X = other.Width; Y = other.Height; return *this; }
vector2d<T> operator+(const dimension2d<T>& other) const { return vector2d<T>(X + other.Width, Y + other.Height); }
vector2d<T>& operator+=(const dimension2d<T>& other) { X += other.Width; Y += other.Height; return *this; }
vector2d<T> operator-(const dimension2d<T>& other) const { return vector2d<T>(X - other.Width, Y - other.Height); }
vector2d<T>& operator-=(const dimension2d<T>& other) { X -= other.Width; Y -= other.Height; return *this; }
// These methods are declared in dimension2d, but need definitions of vector2d
template<class T>
dimension2d<T>::dimension2d(const vector2d<T>& other) : Width(other.X), Height(other.Y) { }
template<class T>
bool dimension2d<T>::operator==(const vector2d<T>& other) const { return Width == other.X && Height == other.Y; }
Changes for Version 1.6.1
-------------------------
This is again just a bugfix release. However, some minor API changes have happened. The most important one is the removal of lins anti-aliasing from SMaterial's default values. Please add that line smoothing flag to the materials you want to be smoothed. But note that this may lead to drastically reduced performance, if no multi-sampling is active.
IFileList.h
new methods
virtual u32 getID(u32 index) const = 0;
virtual u32 addItem(const io::path& fullPath, u32 size, bool isDirectory, u32 id=0) = 0;
virtual void sort() = 0;
IrrCompileConfig.h
Removed auto recognition of Solaris OS, please define the setting on your own if you need it
_IRR_SOLARIS_PLATFORM_
IGUITreeView.h
removed methods (use automatically generated versions)
IGUITreeViewNode() {}
virtual ~IGUITreeViewNode() {}
virtual ~IGUITreeView() {}
IFileSystem.h
new method
virtual IFileList* createEmptyFileList(const io::path& path, bool ignoreCase, bool ignorePaths) =0;
SMaterial.h
Removed default value (EAAM_LINE_SMOOTH from AntiAliasing)
ZBuffer(ECFN_LESSEQUAL), AntiAliasing(EAAM_SIMPLE), ColorMask(ECP_ALL),
IGUISkin.h
new enum value
EGST_COUNT
Changes for Version 1.7
-------------------------
-IEventReceiver.h
-- EMIE_LMOUSE_DOUBLE_CLICK replaces EMIE_MOUSE_DOUBLE_CLICK
-- EMIE_LMOUSE_TRIPLE_CLICK replaces EMIE_MOUSE_TRIPLE_CLICK
+This version has less API-breaking changes than the previous major changes. It has many new features, which simply add methods. All those changes, which affect old methods or structures are mostly put in parallel to the old (and now deprecated) methods. Only a few things are changed without backward compatibility: The texture wrap mode is split into separate U and V modes. The beginScene void* parameter has been replaced by an SExposedVideoData. Simply wrap the pointer with this struct and it should work again.
+EMIE_LMOUSE_DOUBLE_CLICK replaces EMIE_MOUSE_DOUBLE_CLICK and EMIE_LMOUSE_TRIPLE_CLICK replaces EMIE_MOUSE_TRIPLE_CLICK
+Elements used in the array container need now to have an operator=
+Here comes the full list:
-irrMap.h
-- map::empty replaces map::isEmpty
+path.h
+New type
+struct SNamedPath
+
+triangle3d.h
+New method
+bool isTotalOutsideBox(const aabbox3d<T>& box) const
+
+ESceneNodeTypes.h
+Changed enum value (from octt)
+ESNT_OCTREE = MAKE_IRR_ID('o','c','t','r'),
+
+SColor.h
+New method
+f32 getLightness() const
+
+driverChoice.h
+New method
+static irr::video::E_DRIVER_TYPE driverChoiceConsole(bool allDrivers=true)
+ITexture.h
+New parameter
+virtual void regenerateMipMapLevels(void* mipmapData=0) = 0;
+Changed return value (from io:path)
+const io::SNamedPath& getName() const { return NamedPath; }
+
+SceneParameters.h
+New scene parameters
+const c8* const OBJ_TEXTURE_PATH = "OBJ_TexturePath";
+const c8* const B3D_TEXTURE_PATH = "B3D_TexturePath";
+
+IMeshManipulator.h
+Not virtual anymore
+void setVertexColorAlpha(IMesh* mesh, s32 alpha) const
+void setVertexColors(IMesh* mesh, video::SColor color) const
+void scale(IMeshBuffer* buffer, const core::vector3df& factor) const
+void scaleMesh(IMesh* mesh, const core::vector3df& factor) const
+void scaleTCoords(scene::IMesh* mesh, const core::vector2df& factor, u32 level=1) const
+void scaleTCoords(scene::IMeshBuffer* buffer, const core::vector2df& factor, u32 level=1) const
+void transform(IMesh* mesh, const core::matrix4& m) const
+void transform(IMeshBuffer* buffer, const core::matrix4& m) const
+New method
+template <typename Functor>
+bool apply(const Functor& func, IMeshBuffer* buffer, bool boundingBoxUpdate=false) const
+template <typename Functor>
+bool apply(const Functor& func, IMesh* mesh, bool boundingBoxUpdate=false) const
+virtual void recalculateTangents(IMesh* mesh, bool recalculateNormals=false,
+ bool smooth=false, bool angleWeighted=false) const=0;
+void scale(IMesh* mesh, const core::vector3df& factor) const
+New parameter
+virtual IMesh* createMeshWithTangents(IMesh* mesh, bool recalculateNormals=false, bool smooth=false, bool angleWeighted=false, bool recalculateTangents=true) const = 0;
+
+coreutil.h
+Changed return type and parameters (from stringc/w)
+inline io::path& cutFilenameExtension ( io::path &dest, const io::path &source )
+inline io::path& getFileNameExtension ( io::path &dest, const io::path &source )
+inline io::path& deletePathFromFilename(io::path& filename)
+Fixed behavior
+inline io::path& deletePathFromPath(io::path& filename, s32 pathCount)
+
+ICursorControl.h
+Return const-ref
+virtual const core::position2d<s32>& getPosition() = 0;
+
irrArray.h
-- Elements used in the array container need now to have an operator=
+Fixed allocator template usage
+array(const array<T, TAlloc>& other) : data(0)
+const array<T, TAlloc>& operator=(const array<T, TAlloc>& other)
+bool operator == (const array<T, TAlloc>& other) const
+bool operator != (const array<T, TAlloc>& other) const
+Changed behavior for free_when_destroyed
+void set_pointer(T* newPointer, u32 size, bool _is_sorted=false, bool _free_when_destroyed=true)
+void set_free_when_destroyed(bool f)
+
+irrMap.h
+Renamed method (from isEmpty)
+bool empty() const
+New method
+void swap(map<KeyType, ValueType>& other)
+
+IAnimatedMesh.h
+virtual f32 getAnimationSpeed() const =0;
+
+IAttributes.h
+Made parameters const-ref
+virtual void addArray(const c8* attributeName, const core::array<core::stringw>& value) = 0;
+virtual void setAttribute(const c8* attributeName, const core::array<core::stringw>& value) = 0;
+virtual void setAttribute(s32 index, const core::array<core::stringw>& value) = 0;
+
+ISceneManager.h
+Renamed method (from OctTree)
+virtual IMeshSceneNode* addOctreeSceneNode(IAnimatedMesh* mesh, ISceneNode* parent=0,
+ s32 id=-1, s32 minimalPolysPerNode=512, bool alsoAddIfMeshPointerZero=false) = 0;
+virtual IMeshSceneNode* addOctreeSceneNode(IMesh* mesh, ISceneNode* parent=0,
+ s32 id=-1, s32 minimalPolysPerNode=256, bool alsoAddIfMeshPointerZero=false) = 0;
+virtual ITriangleSelector* createOctreeTriangleSelector(IMesh* mesh,
+ ISceneNode* node, s32 minimalPolysPerNode=32) = 0;
+New parameter (makeActive)
+virtual ICameraSceneNode* addCameraSceneNode(ISceneNode* parent = 0,
+ const core::vector3df& position = core::vector3df(0,0,0),
+ const core::vector3df& lookat = core::vector3df(0,0,100),
+ s32 id=-1, bool makeActive=true) = 0;
+virtual ICameraSceneNode* addCameraSceneNodeMaya(ISceneNode* parent = 0,
+ f32 rotateSpeed = -1500.0f, f32 zoomSpeed = 200.0f,
+ f32 translationSpeed = 1500.0f, s32 id=-1,
+ bool makeActive=true) = 0;
+virtual ICameraSceneNode* addCameraSceneNodeFPS(ISceneNode* parent = 0,
+ f32 rotateSpeed = 100.0f, f32 moveSpeed = 0.5f, s32 id=-1,
+ SKeyMap* keyMapArray=0, s32 keyMapSize=0, bool noVerticalMovement=false,
+ f32 jumpSpeed = 0.f, bool invertMouse=false,
+ bool makeActive=true) = 0;
+Make parameter const
+virtual IMeshSceneNode* addQuake3SceneNode(const IMeshBuffer* meshBuffer, const quake3::IShader * shader,
+ ISceneNode* parent=0, s32 id=-1) = 0;
+New parameter (loop, pingpong)
+virtual ISceneNodeAnimator* createFollowSplineAnimator(s32 startTime,
+ const core::array< core::vector3df >& points,
+ f32 speed = 1.0f, f32 tightness = 0.5f, bool loop=true, bool pingpong=false) = 0;
+
+SMaterialLayer.h
+New clamp modes
+ETC_MIRROR_CLAMP, ETC_MIRROR_CLAMP_TO_EDGE, ETC_MIRROR_CLAMP_TO_BORDER
+New material layer modes (replaces TextureWrap)
+TextureWrapU(ETC_REPEAT), TextureWrapV(ETC_REPEAT)
+
+vector3d.h
+Use tolerance to compare, changed order function to total order
+bool operator<=(const vector3d<T>&other) const
+bool operator>=(const vector3d<T>&other) const
+bool operator<(const vector3d<T>&other) const
+bool operator>(const vector3d<T>&other) const
+New method
+vector3d<T> getSphericalCoordinateAngles()
+New method specializations
+template <>
+inline vector3d<s32> vector3d<s32>::operator /(s32 val) const {return core::vector3d<s32>(X/val,Y/val,Z/val);}
+template <>
+inline vector3d<s32>& vector3d<s32>::operator /=(s32 val) {X/=val;Y/=val;Z/=val; return *this;}
+
+SExposedVideoData.h
+New constructors
+SExposedVideoData() {OpenGLWin32.HDc=0; OpenGLWin32.HRc=0; OpenGLWin32.HWnd=0;}
+explicit SExposedVideoData(void* Window) {OpenGLWin32.HDc=0; OpenGLWin32.HRc=0; OpenGLWin32.HWnd=Window;}
+
+IGUIEnvironment.h
+New method
+virtual IGUIFont* addFont(const io::path& name, IGUIFont* font) = 0;
+New parameter (image)
+virtual IGUIWindow* addMessageBox(const wchar_t* caption, const wchar_t* text=0,
+ bool modal = true, s32 flags = EMBF_OK, IGUIElement* parent=0, s32 id=-1, video::ITexture* image=0) = 0;
+
+IGeometryCreator.h
+New method
+IMesh* createPlaneMesh(const core::dimension2d<f32>& tileSize,
+ const core::dimension2d<u32>& tileCount,
+ video::SMaterial* material,
+ const core::dimension2d<f32>& textureRepeatCount) const
+
+IFileArchive.h
+New archive type
+EFAT_NPK = MAKE_IRR_ID('N','P','K', 0),
+New member for storing the password of AES-encrypted archives
+core::stringc Password;
+
+IFileSystem.h
+New parameter (password)
+virtual bool addFileArchive(const path& filename, bool ignoreCase=true,
+ bool ignorePaths=true,
+ E_FILE_ARCHIVE_TYPE archiveType=EFAT_UNKNOWN,
+ const core::stringc& password="") =0;
-Octrees (the structure formerly know as octtree):
-- All references to OctTree, OctTreeSceneNode, OctTreeTriangleSelector and OCT_TREE got replaced by Octree, OctreeSceneNode, OctreeTriangleSelector and OCTREE. (one 't' less).
+IrrlichtDevice.h
+New method
+virtual void clearSystemMessages() = 0;
+
+irrMath.h
+Changed constant (from 1)
+const s32 ROUNDING_ERROR_S32 = 0;
+New method
+template <class T>
+inline void swap(T& a, T& b)
+
+IGPUProgrammingServices.h
+New parameters (for geometry shaders)
+virtual s32 addHighLevelShaderMaterial
+virtual s32 addHighLevelShaderMaterialFromFiles
+virtual s32 addHighLevelShaderMaterialFromFiles
+New overload (for calling with geometry shaders)
+s32 addHighLevelShaderMaterial
+s32 addHighLevelShaderMaterialFromFiles
+s32 addHighLevelShaderMaterialFromFiles
+
+ISceneNode.h
+New types
+ typedef core::list<ISceneNode*> ISceneNodeList;
+ typedef core::list<ISceneNodeAnimator*> ISceneNodeAnimatorList;
+
+IEventReceiver.h
+Renamed events (split from EMIE_MOUSE_*)
+EMIE_LMOUSE_DOUBLE_CLICK,
+EMIE_RMOUSE_DOUBLE_CLICK,
+EMIE_MMOUSE_DOUBLE_CLICK,
+EMIE_LMOUSE_TRIPLE_CLICK,
+EMIE_RMOUSE_TRIPLE_CLICK,
+EMIE_MMOUSE_TRIPLE_CLICK,
+
+IGUISpriteBank.h
+New method
+virtual s32 addTextureAsSprite(video::ITexture* texture) = 0;
+virtual void clear() = 0;
+
+SMaterial.h
+Changed binary packing (non-visible from user calls)
+inline f32 pack_texureBlendFunc ( const E_BLEND_FACTOR srcFact, const E_BLEND_FACTOR dstFact, const E_MODULATE_FUNC modulate=EMFN_MODULATE_1X, const u32 alphaSource=EAS_TEXTURE )
+
+IGUISkin.h
+New values
+EGDS_MESSAGE_BOX_GAP_SPACE,
+EGDS_MESSAGE_BOX_MIN_TEXT_WIDTH,
+EGDS_MESSAGE_BOX_MAX_TEST_WIDTH,
+EGDS_MESSAGE_BOX_MIN_TEXT_HEIGHT,
+EGDS_MESSAGE_BOX_MAX_TEXT_HEIGHT,
+New parameter (checkClientArea)
+virtual core::rect<s32> draw3DWindowBackground(IGUIElement* element,
+ bool drawTitleBar, video::SColor titleBarColor,
+ const core::rect<s32>& rect,
+ const core::rect<s32>* clip=0,
+ core::rect<s32>* checkClientArea=0) = 0;
+
+quaternion.h
+New operator
+bool operator!=(const quaternion& other) const;
+New method
+inline quaternion& set(const core::quaternion& quat);
+inline bool equals(const quaternion& other,
+ const f32 tolerance = ROUNDING_ERROR_f32 ) const;
+
+irrList.h
+New method
+u32 size() const
+void swap(list<T>& other)
+
+IVideoDriver.h
+New render targets
+ERT_MULTI_RENDER_TEXTURES
+New class
+struct IRenderTarget
+Changed parameter (from void*)
+virtual bool beginScene(bool backBuffer=true, bool zBuffer=true,
+ SColor color=SColor(255,0,0,0),
+ const SExposedVideoData& videoData=SExposedVideoData(),
+ core::rect<s32>* sourceRect=0) =0;
+New parameter (mipmapData)
+virtual ITexture* addTexture(const io::path& name, IImage* image, void* mipmapData=0) = 0;
+New method
+virtual bool setRenderTarget(const core::array<video::IRenderTarget>& texture,
+ bool clearBackBuffer=true, bool clearZBuffer=true,
+ SColor color=video::SColor(0,0,0,0)) =0;
+void drawIndexedTriangleFan(const S3DVertexTangents* vertices,
+ u32 vertexCount, const u16* indexList, u32 triangleCount)
+virtual void getFog(SColor& color, E_FOG_TYPE& fogType,
+ f32& start, f32& end, f32& density,
+ bool& pixelFog, bool& rangeFog) = 0;
+virtual SMaterial& getMaterial2D() =0;
+virtual void enableMaterial2D(bool enable=true) =0;
+virtual core::dimension2du getMaxTextureSize() const =0;
+Made non-virtual
+void drawIndexedTriangleList(const S3DVertex* vertices,
+ u32 vertexCount, const u16* indexList, u32 triangleCount)
+void drawIndexedTriangleList(const S3DVertex2TCoords* vertices,
+ u32 vertexCount, const u16* indexList, u32 triangleCount)
+void drawIndexedTriangleList(const S3DVertexTangents* vertices,
+ u32 vertexCount, const u16* indexList, u32 triangleCount)
+void drawIndexedTriangleFan(const S3DVertex* vertices,
+ u32 vertexCount, const u16* indexList, u32 triangleCount)
+void drawIndexedTriangleFan(const S3DVertex2TCoords* vertices,
+ u32 vertexCount, const u16* indexList, u32 triangleCount)
+
+EDriverFeatures.h
+New driver feature enums
+EVDF_MULTIPLE_RENDER_TARGETS,
+EVDF_MRT_BLEND,
+EVDF_MRT_COLOR_MASK,
+EVDF_MRT_BLEND_FUNC,
+EVDF_GEOMETRY_SHADER,
+
+IGUIWindow.h
+New method
+virtual core::rect<s32> getClientRect() const = 0;
+
+IGUIContextMenu.h
+New enum
+enum ECONTEXT_MENU_CLOSE
+New method
+virtual void setCloseHandling(ECONTEXT_MENU_CLOSE onClose) = 0;
+virtual ECONTEXT_MENU_CLOSE getCloseHandling() const = 0;
+virtual u32 insertItem(u32 idx, const wchar_t* text, s32 commandId=-1, bool enabled=true,
+ bool hasSubMenu=false, bool checked=false, bool autoChecking=false) = 0;
+virtual s32 findItemWithCommandId(s32 commandId, u32 idxStartSearch=0) const = 0;
+virtual void setItemAutoChecking(u32 idx, bool autoChecking) = 0;
+virtual bool getItemAutoChecking(u32 idx) const = 0;
+virtual void setEventParent(IGUIElement *parent) = 0;
+New parameter
+virtual u32 addItem(const wchar_t* text, s32 commandId=-1, bool enabled=true,
+ bool hasSubMenu=false, bool checked=false, bool autoChecking=false) = 0;
+
+SIrrCreationParameters.h
+New parameter (LoggingLevel)
+createDevice
+
+matrix4.h
+New method
+bool equals(const core::CMatrix4<T>& other, const T tolerance=(T)ROUNDING_ERROR_f64) const;
+
+SSkinMeshBuffer.h
+Renamed method (from MoveTo_2TCoords)
+virtual void convertTo2TCoords()
+Renamed method (from MoveTo_Tangents)
+virtual void convertToTangents()
+
+SVertexManipulator.h
+New classes (for vertex manipulation)
+class SVertexColorSetManipulator : public IVertexManipulator
+class SVertexColorSetAlphaManipulator : public IVertexManipulator
+class SVertexColorInvertManipulator : public IVertexManipulator
+class SVertexColorThresholdManipulator : public IVertexManipulator
+class SVertexColorBrightnessManipulator : public IVertexManipulator
+class SVertexColorContrastManipulator : public IVertexManipulator
+class SVertexColorContrastBrightnessManipulator : public IVertexManipulator
+class SVertexColorGammaManipulator : public IVertexManipulator
+;
+class SVertexColorScaleManipulator : public IVertexManipulator
+class SVertexColorDesaturateToLightnessManipulator : public IVertexManipulator
+class SVertexColorDesaturateToAverageManipulator : public IVertexManipulator
+class SVertexColorDesaturateToLuminanceManipulator : public IVertexManipulator
+class SVertexColorInterpolateLinearManipulator : public IVertexManipulator
+class SVertexColorInterpolateQuadraticManipulator : public IVertexManipulator
+class SVertexPositionScaleManipulator : public IVertexManipulator
+;
+class SVertexPositionScaleAlongNormalsManipulator : public IVertexManipulator
+class SVertexPositionTransformManipulator : public IVertexManipulator
+class SVertexTCoordsScaleManipulator : public IVertexManipulator
+
+IMeshCache.h
+Renamed method (from getMeshByFilename)
+virtual IAnimatedMesh* getMeshByName(const io::path& name) = 0;
+Renamed method and changed return type (from getMeshFilename/io::path)
+virtual const io::SNamedPath& getMeshName(u32 index) const = 0;
+virtual const io::SNamedPath& getMeshName(const IAnimatedMesh* const mesh) const = 0;
+virtual const io::SNamedPath& getMeshName(const IMesh* const mesh) const = 0;
+Renamed method (from setMeshFilename)
+virtual bool renameMesh(u32 index, const io::path& name) = 0;
+virtual bool renameMesh(const IAnimatedMesh* const mesh, const io::path& name) = 0;
+virtual bool renameMesh(const IMesh* const mesh, const io::path& name) = 0;
+
+IGUIElement.h
+Changed parameter (to const-ref)
+ IGUIElement(EGUI_ELEMENT_TYPE type, IGUIEnvironment* environment, IGUIElement* parent,
+s32 id, const core::rect<s32>& rectangle)
+New method
+virtual bool hasType(EGUI_ELEMENT_TYPE type) const
+
+irrString.h
+Changed parameter (to template with allocator) in all methods with templates
+Made destructor non-virtual
+~string()
+Added parameter
+s32 find(const B* const str, const u32 start = 0) const
+New method
+void remove(T c)
+void remove(const string<T,TAlloc> toRemove)
+void removeChars(const string<T,TAlloc> & characters)
+template<class container>
+u32 split(container& ret, const T* const c, u32 count=1, bool ignoreEmptyTokens=true, bool keepSeparators=false) const
+
+vector2d.h
+Use tolerance to compare, changed order function to total order
+bool operator<=(const vector2d<T>&other) const
+bool operator>=(const vector2d<T>&other) const
+bool operator<(const vector2d<T>&other) const
+bool operator>(const vector2d<T>&other) const
+
|
paupawsan/Irrlicht
|
29419309259ae2307a4e081aacb03c71349fc72c
|
Fix transparency issues in Demo. Code layout changes in GUI.
|
diff --git a/examples/Demo/CDemo.cpp b/examples/Demo/CDemo.cpp
index d824973..eddee01 100644
--- a/examples/Demo/CDemo.cpp
+++ b/examples/Demo/CDemo.cpp
@@ -205,609 +205,610 @@ void CDemo::switchToNextScene()
case -1: // loading screen
timeForThisScene = 0;
createLoadingScreen();
break;
case 0: // load scene
timeForThisScene = 0;
loadSceneData();
break;
case 1: // panorama camera
{
currentScene += 1;
//camera = sm->addCameraSceneNode(0, core::vector3df(0,0,0), core::vector3df(-586,708,52));
//camera->setTarget(core::vector3df(0,400,0));
core::array<core::vector3df> points;
points.push_back(core::vector3df(-931.473755f, 138.300003f, 987.279114f)); // -49873
points.push_back(core::vector3df(-847.902222f, 136.757553f, 915.792725f)); // -50559
points.push_back(core::vector3df(-748.680420f, 152.254501f, 826.418945f)); // -51964
points.push_back(core::vector3df(-708.428406f, 213.569580f, 784.466675f)); // -53251
points.push_back(core::vector3df(-686.217651f, 288.141174f, 762.965576f)); // -54015
points.push_back(core::vector3df(-679.685059f, 365.095612f, 756.551453f)); // -54733
points.push_back(core::vector3df(-671.317871f, 447.360107f, 749.394592f)); // -55588
points.push_back(core::vector3df(-669.468445f, 583.335632f, 747.711853f)); // -56178
points.push_back(core::vector3df(-667.611267f, 727.313232f, 746.018250f)); // -56757
points.push_back(core::vector3df(-665.853210f, 862.791931f, 744.436096f)); // -57859
points.push_back(core::vector3df(-642.649597f, 1026.047607f, 724.259827f)); // -59705
points.push_back(core::vector3df(-517.793884f, 838.396790f, 490.326050f)); // -60983
points.push_back(core::vector3df(-474.387299f, 715.691467f, 344.639984f)); // -61629
points.push_back(core::vector3df(-444.600250f, 601.155701f, 180.938095f)); // -62319
points.push_back(core::vector3df(-414.808899f, 479.691406f, 4.866660f)); // -63048
points.push_back(core::vector3df(-410.418945f, 429.642242f, -134.332687f)); // -63757
points.push_back(core::vector3df(-399.837585f, 411.498383f, -349.350983f)); // -64418
points.push_back(core::vector3df(-390.756653f, 403.970093f, -524.454407f)); // -65005
points.push_back(core::vector3df(-334.864227f, 350.065491f, -732.397400f)); // -65701
points.push_back(core::vector3df(-195.253387f, 349.577209f, -812.475891f)); // -66335
points.push_back(core::vector3df(16.255573f, 363.743134f, -833.800415f)); // -67170
points.push_back(core::vector3df(234.940964f, 352.957825f, -820.150696f)); // -67939
points.push_back(core::vector3df(436.797668f, 349.236450f, -816.914185f)); // -68596
points.push_back(core::vector3df(575.236206f, 356.244812f, -719.788513f)); // -69166
points.push_back(core::vector3df(594.131042f, 387.173828f, -609.675598f)); // -69744
points.push_back(core::vector3df(617.615234f, 412.002899f, -326.174072f)); // -70640
points.push_back(core::vector3df(606.456848f, 403.221954f, -104.179291f)); // -71390
points.push_back(core::vector3df(610.958252f, 407.037750f, 117.209778f)); // -72085
points.push_back(core::vector3df(597.956909f, 395.167877f, 345.942200f)); // -72817
points.push_back(core::vector3df(587.383118f, 391.444519f, 566.098633f)); // -73477
points.push_back(core::vector3df(559.572449f, 371.991333f, 777.689453f)); // -74124
points.push_back(core::vector3df(423.753204f, 329.990051f, 925.859741f)); // -74941
points.push_back(core::vector3df(247.520050f, 252.818954f, 935.311829f)); // -75651
points.push_back(core::vector3df(114.756012f, 199.799759f, 805.014160f));
points.push_back(core::vector3df(96.783348f, 181.639481f, 648.188110f));
points.push_back(core::vector3df(97.865623f, 138.905975f, 484.812561f));
points.push_back(core::vector3df(99.612457f, 102.463669f, 347.603210f));
points.push_back(core::vector3df(99.612457f, 102.463669f, 347.603210f));
points.push_back(core::vector3df(99.612457f, 102.463669f, 347.603210f));
timeForThisScene = (points.size()-3)* 1000;
camera = sm->addCameraSceneNode(0, points[0], core::vector3df(0 ,400,0));
//camera->setTarget(core::vector3df(0,400,0));
sa = sm->createFollowSplineAnimator(device->getTimer()->getTime(),
points);
camera->addAnimator(sa);
sa->drop();
model1->setVisible(false);
model2->setVisible(false);
campFire->setVisible(false);
inOutFader->fadeIn(7000);
}
break;
case 2: // down fly anim camera
camera = sm->addCameraSceneNode(0, core::vector3df(100,40,-80), core::vector3df(844,670,-885));
sa = sm->createFlyStraightAnimator(core::vector3df(94, 1002, 127),
core::vector3df(108, 15, -60), 10000, true);
camera->addAnimator(sa);
timeForThisScene = 9900;
model1->setVisible(true);
model2->setVisible(false);
campFire->setVisible(false);
sa->drop();
break;
case 3: // interactive, go around
{
model1->setVisible(true);
model2->setVisible(true);
campFire->setVisible(true);
timeForThisScene = -1;
SKeyMap keyMap[9];
keyMap[0].Action = EKA_MOVE_FORWARD;
keyMap[0].KeyCode = KEY_UP;
keyMap[1].Action = EKA_MOVE_FORWARD;
keyMap[1].KeyCode = KEY_KEY_W;
keyMap[2].Action = EKA_MOVE_BACKWARD;
keyMap[2].KeyCode = KEY_DOWN;
keyMap[3].Action = EKA_MOVE_BACKWARD;
keyMap[3].KeyCode = KEY_KEY_S;
keyMap[4].Action = EKA_STRAFE_LEFT;
keyMap[4].KeyCode = KEY_LEFT;
keyMap[5].Action = EKA_STRAFE_LEFT;
keyMap[5].KeyCode = KEY_KEY_A;
keyMap[6].Action = EKA_STRAFE_RIGHT;
keyMap[6].KeyCode = KEY_RIGHT;
keyMap[7].Action = EKA_STRAFE_RIGHT;
keyMap[7].KeyCode = KEY_KEY_D;
keyMap[8].Action = EKA_JUMP_UP;
keyMap[8].KeyCode = KEY_KEY_J;
camera = sm->addCameraSceneNodeFPS(0, 100.0f, .4f, -1, keyMap, 9, false, 3.f);
camera->setPosition(core::vector3df(108,140,-140));
scene::ISceneNodeAnimatorCollisionResponse* collider =
sm->createCollisionResponseAnimator(
metaSelector, camera, core::vector3df(25,50,25),
core::vector3df(0, quakeLevelMesh ? -10.f : 0.0f,0),
core::vector3df(0,45,0), 0.005f);
camera->addAnimator(collider);
collider->drop();
}
break;
}
sceneStartTime = device->getTimer()->getTime();
}
void CDemo::loadSceneData()
{
// load quake level
video::IVideoDriver* driver = device->getVideoDriver();
scene::ISceneManager* sm = device->getSceneManager();
// Quake3 Shader controls Z-Writing
sm->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
quakeLevelMesh = (scene::IQ3LevelMesh*) sm->getMesh("maps/20kdm2.bsp");
if (quakeLevelMesh)
{
u32 i;
//move all quake level meshes (non-realtime)
core::matrix4 m;
m.setTranslation(core::vector3df(-1300,-70,-1249));
for ( i = 0; i!= scene::quake3::E_Q3_MESH_SIZE; ++i )
sm->getMeshManipulator()->transform(quakeLevelMesh->getMesh(i), m);
quakeLevelNode = sm->addOctreeSceneNode(
quakeLevelMesh->getMesh( scene::quake3::E_Q3_MESH_GEOMETRY));
if (quakeLevelNode)
{
//quakeLevelNode->setPosition(core::vector3df(-1300,-70,-1249));
quakeLevelNode->setVisible(true);
// create map triangle selector
mapSelector = sm->createOctreeTriangleSelector(quakeLevelMesh->getMesh(0),
quakeLevelNode, 128);
// if not using shader and no gamma it's better to use more lighting, because
// quake3 level are usually dark
quakeLevelNode->setMaterialType ( video::EMT_LIGHTMAP_M4 );
// set additive blending if wanted
if (additive)
quakeLevelNode->setMaterialType(video::EMT_LIGHTMAP_ADD);
}
// the additional mesh can be quite huge and is unoptimized
scene::IMesh * additional_mesh = quakeLevelMesh->getMesh ( scene::quake3::E_Q3_MESH_ITEMS );
for ( i = 0; i!= additional_mesh->getMeshBufferCount (); ++i )
{
scene::IMeshBuffer *meshBuffer = additional_mesh->getMeshBuffer ( i );
const video::SMaterial &material = meshBuffer->getMaterial();
//! The ShaderIndex is stored in the material parameter
s32 shaderIndex = (s32) material.MaterialTypeParam2;
// the meshbuffer can be rendered without additional support, or it has no shader
const scene::quake3::IShader *shader = quakeLevelMesh->getShader ( shaderIndex );
if ( 0 == shader )
{
continue;
}
// Now add the MeshBuffer(s) with the current Shader to the Manager
sm->addQuake3SceneNode ( meshBuffer, shader );
}
}
// load sydney model and create 2 instances
scene::IAnimatedMesh* mesh = 0;
mesh = sm->getMesh("../../media/sydney.md2");
if (mesh)
{
model1 = sm->addAnimatedMeshSceneNode(mesh);
if (model1)
{
model1->setMaterialTexture(0, driver->getTexture("../../media/spheremap.jpg"));
model1->setPosition(core::vector3df(100,40,-80));
model1->setScale(core::vector3df(2,2,2));
model1->setMD2Animation(scene::EMAT_STAND);
model1->setMaterialFlag(video::EMF_LIGHTING, false);
model1->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
model1->setMaterialType(video::EMT_SPHERE_MAP);
model1->addShadowVolumeSceneNode();
}
model2 = sm->addAnimatedMeshSceneNode(mesh);
if (model2)
{
model2->setPosition(core::vector3df(180,15,-60));
model2->setScale(core::vector3df(2,2,2));
model2->setMD2Animation(scene::EMAT_RUN);
model2->setMaterialTexture(0, device->getVideoDriver()->getTexture("../../media/sydney.bmp"));
model2->setMaterialFlag(video::EMF_LIGHTING, true);
model1->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
model2->addShadowVolumeSceneNode();
}
}
scene::ISceneNodeAnimator* anim = 0;
// create sky box
driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
skyboxNode = sm->addSkyBoxSceneNode(
driver->getTexture("../../media/irrlicht2_up.jpg"),
driver->getTexture("../../media/irrlicht2_dn.jpg"),
driver->getTexture("../../media/irrlicht2_lf.jpg"),
driver->getTexture("../../media/irrlicht2_rt.jpg"),
driver->getTexture("../../media/irrlicht2_ft.jpg"),
driver->getTexture("../../media/irrlicht2_bk.jpg"));
driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, true);
// create walk-between-portals animation
core::vector3df waypoint[2];
waypoint[0].set(-150,40,100);
waypoint[1].set(350,40,100);
if (model2)
{
anim = device->getSceneManager()->createFlyStraightAnimator(
waypoint[0], waypoint[1], 2000, true);
model2->addAnimator(anim);
anim->drop();
}
// create animation for portals;
core::array<video::ITexture*> textures;
for (s32 g=1; g<8; ++g)
{
core::stringc tmp("../../media/portal");
tmp += g;
tmp += ".bmp";
video::ITexture* t = driver->getTexture( tmp );
textures.push_back(t);
}
anim = sm->createTextureAnimator(textures, 100);
// create portals
scene::IBillboardSceneNode* bill = 0;
for (int r=0; r<2; ++r)
{
bill = sm->addBillboardSceneNode(0, core::dimension2d<f32>(100,100),
waypoint[r]+ core::vector3df(0,20,0));
bill->setMaterialFlag(video::EMF_LIGHTING, false);
bill->setMaterialTexture(0, driver->getTexture("../../media/portal1.bmp"));
bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
bill->addAnimator(anim);
}
anim->drop();
// create cirlce flying dynamic light with transparent billboard attached
scene::ILightSceneNode* light = 0;
light = sm->addLightSceneNode(0,
core::vector3df(0,0,0), video::SColorf(1.0f, 1.0f, 1.f, 1.0f), 500.f);
anim = sm->createFlyCircleAnimator(
core::vector3df(100,150,80), 80.0f, 0.0005f);
light->addAnimator(anim);
anim->drop();
bill = device->getSceneManager()->addBillboardSceneNode(
light, core::dimension2d<f32>(40,40));
bill->setMaterialFlag(video::EMF_LIGHTING, false);
bill->setMaterialTexture(0, driver->getTexture("../../media/particlewhite.bmp"));
bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
// create meta triangle selector with all triangles selectors in it.
metaSelector = sm->createMetaTriangleSelector();
metaSelector->addTriangleSelector(mapSelector);
// create camp fire
campFire = sm->addParticleSystemSceneNode(false);
campFire->setPosition(core::vector3df(100,120,600));
campFire->setScale(core::vector3df(2,2,2));
scene::IParticleEmitter* em = campFire->createBoxEmitter(
core::aabbox3d<f32>(-7,0,-7,7,1,7),
core::vector3df(0.0f,0.06f,0.0f),
80,100, video::SColor(0,255,255,255),video::SColor(0,255,255,255), 800,2000);
em->setMinStartSize(core::dimension2d<f32>(20.0f, 10.0f));
em->setMaxStartSize(core::dimension2d<f32>(20.0f, 10.0f));
campFire->setEmitter(em);
em->drop();
scene::IParticleAffector* paf = campFire->createFadeOutParticleAffector();
campFire->addAffector(paf);
paf->drop();
campFire->setMaterialFlag(video::EMF_LIGHTING, false);
campFire->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
campFire->setMaterialTexture(0, driver->getTexture("../../media/fireball.bmp"));
campFire->setMaterialType(video::EMT_TRANSPARENT_VERTEX_ALPHA);
// load music
#ifdef USE_IRRKLANG
if (music)
startIrrKlang();
#endif
#ifdef USE_SDL_MIXER
if (music)
startSound();
#endif
}
void CDemo::createLoadingScreen()
{
core::dimension2d<u32> size = device->getVideoDriver()->getScreenSize();
device->getCursorControl()->setVisible(false);
// setup loading screen
backColor.set(255,90,90,156);
// create in fader
inOutFader = device->getGUIEnvironment()->addInOutFader();
inOutFader->setColor(backColor, video::SColor ( 0, 230, 230, 230 ));
// irrlicht logo
device->getGUIEnvironment()->addImage(device->getVideoDriver()->getTexture("../../media/irrlichtlogo2.png"),
core::position2d<s32>(5,5));
// loading text
const int lwidth = size.Width - 20;
const int lheight = 16;
core::rect<int> pos(10, size.Height-lheight-10, 10+lwidth, size.Height-10);
device->getGUIEnvironment()->addImage(pos);
statusText = device->getGUIEnvironment()->addStaticText(L"Loading...", pos, true);
statusText->setOverrideColor(video::SColor(255,205,200,200));
// load bigger font
device->getGUIEnvironment()->getSkin()->setFont(
device->getGUIEnvironment()->getFont("../../media/fonthaettenschweiler.bmp"));
// set new font color
device->getGUIEnvironment()->getSkin()->setColor(gui::EGDC_BUTTON_TEXT,
video::SColor(255,100,100,100));
}
void CDemo::shoot()
{
scene::ISceneManager* sm = device->getSceneManager();
scene::ICameraSceneNode* camera = sm->getActiveCamera();
if (!camera || !mapSelector)
return;
SParticleImpact imp;
imp.when = 0;
// get line of camera
core::vector3df start = camera->getPosition();
core::vector3df end = (camera->getTarget() - start);
end.normalize();
start += end*8.0f;
end = start + (end * camera->getFarValue());
core::triangle3df triangle;
core::line3d<f32> line(start, end);
// get intersection point with map
const scene::ISceneNode* hitNode;
if (sm->getSceneCollisionManager()->getCollisionPoint(
line, mapSelector, end, triangle, hitNode))
{
// collides with wall
core::vector3df out = triangle.getNormal();
out.setLength(0.03f);
imp.when = 1;
imp.outVector = out;
imp.pos = end;
}
else
{
// doesnt collide with wall
core::vector3df start = camera->getPosition();
core::vector3df end = (camera->getTarget() - start);
end.normalize();
start += end*8.0f;
end = start + (end * camera->getFarValue());
}
// create fire ball
scene::ISceneNode* node = 0;
node = sm->addBillboardSceneNode(0,
core::dimension2d<f32>(25,25), start);
node->setMaterialFlag(video::EMF_LIGHTING, false);
node->setMaterialTexture(0, device->getVideoDriver()->getTexture("../../media/fireball.bmp"));
node->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
f32 length = (f32)(end - start).getLength();
const f32 speed = 0.6f;
u32 time = (u32)(length / speed);
scene::ISceneNodeAnimator* anim = 0;
// set flight line
anim = sm->createFlyStraightAnimator(start, end, time);
node->addAnimator(anim);
anim->drop();
anim = sm->createDeleteAnimator(time);
node->addAnimator(anim);
anim->drop();
if (imp.when)
{
// create impact note
imp.when = device->getTimer()->getTime() + (time - 100);
Impacts.push_back(imp);
}
// play sound
#ifdef USE_IRRKLANG
if (ballSound)
irrKlang->play2D(ballSound);
#endif
#ifdef USE_SDL_MIXER
if (ballSound)
playSound(ballSound);
#endif
}
void CDemo::createParticleImpacts()
{
u32 now = device->getTimer()->getTime();
scene::ISceneManager* sm = device->getSceneManager();
for (s32 i=0; i<(s32)Impacts.size(); ++i)
if (now > Impacts[i].when)
{
// create smoke particle system
scene::IParticleSystemSceneNode* pas = 0;
pas = sm->addParticleSystemSceneNode(false, 0, -1, Impacts[i].pos);
pas->setParticleSize(core::dimension2d<f32>(10.0f, 10.0f));
scene::IParticleEmitter* em = pas->createBoxEmitter(
core::aabbox3d<f32>(-5,-5,-5,5,5,5),
Impacts[i].outVector, 20,40, video::SColor(0,255,255,255),video::SColor(0,255,255,255),
1200,1600, 20);
pas->setEmitter(em);
em->drop();
scene::IParticleAffector* paf = campFire->createFadeOutParticleAffector();
pas->addAffector(paf);
paf->drop();
pas->setMaterialFlag(video::EMF_LIGHTING, false);
+ pas->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
pas->setMaterialTexture(0, device->getVideoDriver()->getTexture("../../media/smoke.bmp"));
pas->setMaterialType(video::EMT_TRANSPARENT_VERTEX_ALPHA);
scene::ISceneNodeAnimator* anim = sm->createDeleteAnimator(2000);
pas->addAnimator(anim);
anim->drop();
// play impact sound
#ifdef USE_IRRKLANG
if (irrKlang)
{
irrklang::ISound* sound =
irrKlang->play3D(impactSound, Impacts[i].pos, false, false, true);
if (sound)
{
// adjust max value a bit to make to sound of an impact louder
sound->setMinDistance(400);
sound->drop();
}
}
#endif
#ifdef USE_SDL_MIXER
if (impactSound)
playSound(impactSound);
#endif
// delete entry
Impacts.erase(i);
i--;
}
}
#ifdef USE_IRRKLANG
void CDemo::startIrrKlang()
{
irrKlang = irrklang::createIrrKlangDevice();
if (!irrKlang)
return;
// play music
irrklang::ISound* snd = irrKlang->play2D("../../media/IrrlichtTheme.ogg", true, false, true);
if ( !snd )
snd = irrKlang->play2D("IrrlichtTheme.ogg", true, false, true);
if (snd)
{
snd->setVolume(0.5f); // 50% volume
snd->drop();
}
// preload both sound effects
ballSound = irrKlang->getSoundSource("../../media/ball.wav");
impactSound = irrKlang->getSoundSource("../../media/impact.wav");
}
#endif
#ifdef USE_SDL_MIXER
void CDemo::startSound()
{
stream = NULL;
ballSound = NULL;
impactSound = NULL;
SDL_Init(SDL_INIT_AUDIO);
if (Mix_OpenAudio(22050, AUDIO_S16, 2, 128))
return;
stream = Mix_LoadMUS("../../media/IrrlichtTheme.ogg");
if (stream)
Mix_PlayMusic(stream, -1);
ballSound = Mix_LoadWAV("../../media/ball.wav");
impactSound = Mix_LoadWAV("../../media/impact.wav");
}
void CDemo::playSound(Mix_Chunk *sample)
{
if (sample)
Mix_PlayChannel(-1, sample, 0);
}
void CDemo::pollSound(void)
{
SDL_Event event;
while (SDL_PollEvent(&event))
;
}
#endif
diff --git a/source/Irrlicht/CGUISkin.cpp b/source/Irrlicht/CGUISkin.cpp
index 3fd8e73..77206dc 100644
--- a/source/Irrlicht/CGUISkin.cpp
+++ b/source/Irrlicht/CGUISkin.cpp
@@ -1,984 +1,976 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CGUISkin.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include "IGUIFont.h"
#include "IGUISpriteBank.h"
#include "IVideoDriver.h"
#include "IAttributes.h"
namespace irr
{
namespace gui
{
CGUISkin::CGUISkin(EGUI_SKIN_TYPE type, video::IVideoDriver* driver)
: SpriteBank(0), Driver(driver), Type(type)
{
#ifdef _DEBUG
setDebugName("CGUISkin");
#endif
if ((Type == EGST_WINDOWS_CLASSIC) || (Type == EGST_WINDOWS_METALLIC))
{
Colors[EGDC_3D_DARK_SHADOW] = video::SColor(101,50,50,50);
Colors[EGDC_3D_SHADOW] = video::SColor(101,130,130,130);
Colors[EGDC_3D_FACE] = video::SColor(101,210,210,210);
Colors[EGDC_3D_HIGH_LIGHT] = video::SColor(101,255,255,255);
Colors[EGDC_3D_LIGHT] = video::SColor(101,210,210,210);
Colors[EGDC_ACTIVE_BORDER] = video::SColor(101,16,14,115);
Colors[EGDC_ACTIVE_CAPTION] = video::SColor(255,255,255,255);
Colors[EGDC_APP_WORKSPACE] = video::SColor(101,100,100,100);
Colors[EGDC_BUTTON_TEXT] = video::SColor(240,10,10,10);
Colors[EGDC_GRAY_TEXT] = video::SColor(240,130,130,130);
Colors[EGDC_HIGH_LIGHT] = video::SColor(101,8,36,107);
Colors[EGDC_HIGH_LIGHT_TEXT] = video::SColor(240,255,255,255);
Colors[EGDC_INACTIVE_BORDER] = video::SColor(101,165,165,165);
Colors[EGDC_INACTIVE_CAPTION] = video::SColor(255,30,30,30);
Colors[EGDC_TOOLTIP] = video::SColor(200,0,0,0);
Colors[EGDC_TOOLTIP_BACKGROUND]= video::SColor(200,255,255,225);
Colors[EGDC_SCROLLBAR] = video::SColor(101,230,230,230);
Colors[EGDC_WINDOW] = video::SColor(101,255,255,255);
Colors[EGDC_WINDOW_SYMBOL] = video::SColor(200,10,10,10);
Colors[EGDC_ICON] = video::SColor(200,255,255,255);
Colors[EGDC_ICON_HIGH_LIGHT] = video::SColor(200,8,36,107);
Sizes[EGDS_SCROLLBAR_SIZE] = 14;
Sizes[EGDS_MENU_HEIGHT] = 30;
Sizes[EGDS_WINDOW_BUTTON_WIDTH] = 15;
Sizes[EGDS_CHECK_BOX_WIDTH] = 18;
Sizes[EGDS_MESSAGE_BOX_WIDTH] = 500;
Sizes[EGDS_MESSAGE_BOX_HEIGHT] = 200;
Sizes[EGDS_BUTTON_WIDTH] = 80;
Sizes[EGDS_BUTTON_HEIGHT] = 30;
Sizes[EGDS_TEXT_DISTANCE_X] = 2;
Sizes[EGDS_TEXT_DISTANCE_Y] = 0;
Sizes[EGDS_TITLEBARTEXT_DISTANCE_X] = 2;
Sizes[EGDS_TITLEBARTEXT_DISTANCE_Y] = 0;
}
else
{
//0x80a6a8af
Colors[EGDC_3D_DARK_SHADOW] = 0x60767982;
//Colors[EGDC_3D_FACE] = 0xc0c9ccd4; // tab background
Colors[EGDC_3D_FACE] = 0xc0cbd2d9; // tab background
Colors[EGDC_3D_SHADOW] = 0x50e4e8f1; // tab background, and left-top highlight
Colors[EGDC_3D_HIGH_LIGHT] = 0x40c7ccdc;
Colors[EGDC_3D_LIGHT] = 0x802e313a;
Colors[EGDC_ACTIVE_BORDER] = 0x80404040; // window title
Colors[EGDC_ACTIVE_CAPTION] = 0xffd0d0d0;
Colors[EGDC_APP_WORKSPACE] = 0xc0646464; // unused
Colors[EGDC_BUTTON_TEXT] = 0xd0161616;
Colors[EGDC_GRAY_TEXT] = 0x3c141414;
Colors[EGDC_HIGH_LIGHT] = 0x6c606060;
Colors[EGDC_HIGH_LIGHT_TEXT]= 0xd0e0e0e0;
Colors[EGDC_INACTIVE_BORDER]= 0xf0a5a5a5;
Colors[EGDC_INACTIVE_CAPTION]= 0xffd2d2d2;
Colors[EGDC_TOOLTIP] = 0xf00f2033;
Colors[EGDC_TOOLTIP_BACKGROUND]=0xc0cbd2d9;
Colors[EGDC_SCROLLBAR] = 0xf0e0e0e0;
Colors[EGDC_WINDOW] = 0xf0f0f0f0;
Colors[EGDC_WINDOW_SYMBOL] = 0xd0161616;
Colors[EGDC_ICON] = 0xd0161616;
Colors[EGDC_ICON_HIGH_LIGHT]= 0xd0606060;
Sizes[EGDS_SCROLLBAR_SIZE] = 14;
Sizes[EGDS_MENU_HEIGHT] = 48;
Sizes[EGDS_WINDOW_BUTTON_WIDTH] = 15;
Sizes[EGDS_CHECK_BOX_WIDTH] = 18;
Sizes[EGDS_MESSAGE_BOX_WIDTH] = 500;
Sizes[EGDS_MESSAGE_BOX_HEIGHT] = 200;
Sizes[EGDS_BUTTON_WIDTH] = 80;
Sizes[EGDS_BUTTON_HEIGHT] = 30;
Sizes[EGDS_TEXT_DISTANCE_X] = 3;
Sizes[EGDS_TEXT_DISTANCE_Y] = 2;
Sizes[EGDS_TITLEBARTEXT_DISTANCE_X] = 3;
Sizes[EGDS_TITLEBARTEXT_DISTANCE_Y] = 2;
}
Sizes[EGDS_MESSAGE_BOX_GAP_SPACE] = 15;
Sizes[EGDS_MESSAGE_BOX_MIN_TEXT_WIDTH] = 0;
Sizes[EGDS_MESSAGE_BOX_MAX_TEST_WIDTH] = 500;
Sizes[EGDS_MESSAGE_BOX_MIN_TEXT_HEIGHT] = 0;
Sizes[EGDS_MESSAGE_BOX_MAX_TEXT_HEIGHT] = 99999;
Texts[EGDT_MSG_BOX_OK] = L"OK";
Texts[EGDT_MSG_BOX_CANCEL] = L"Cancel";
Texts[EGDT_MSG_BOX_YES] = L"Yes";
Texts[EGDT_MSG_BOX_NO] = L"No";
Texts[EGDT_WINDOW_CLOSE] = L"Close";
Texts[EGDT_WINDOW_RESTORE] = L"Restore";
Texts[EGDT_WINDOW_MINIMIZE] = L"Minimize";
Texts[EGDT_WINDOW_MAXIMIZE] = L"Maximize";
Icons[EGDI_WINDOW_MAXIMIZE] = 225;
Icons[EGDI_WINDOW_RESTORE] = 226;
Icons[EGDI_WINDOW_CLOSE] = 227;
Icons[EGDI_WINDOW_MINIMIZE] = 228;
Icons[EGDI_CURSOR_UP] = 229;
Icons[EGDI_CURSOR_DOWN] = 230;
Icons[EGDI_CURSOR_LEFT] = 231;
Icons[EGDI_CURSOR_RIGHT] = 232;
Icons[EGDI_MENU_MORE] = 232;
Icons[EGDI_CHECK_BOX_CHECKED] = 233;
Icons[EGDI_DROP_DOWN] = 234;
Icons[EGDI_SMALL_CURSOR_UP] = 235;
Icons[EGDI_SMALL_CURSOR_DOWN] = 236;
Icons[EGDI_RADIO_BUTTON_CHECKED] = 237;
Icons[EGDI_MORE_LEFT] = 238;
Icons[EGDI_MORE_RIGHT] = 239;
Icons[EGDI_MORE_UP] = 240;
Icons[EGDI_MORE_DOWN] = 241;
Icons[EGDI_WINDOW_RESIZE] = 242;
Icons[EGDI_EXPAND] = 243;
Icons[EGDI_COLLAPSE] = 244;
Icons[EGDI_FILE] = 245;
Icons[EGDI_DIRECTORY] = 246;
for (u32 i=0; i<EGDF_COUNT; ++i)
Fonts[i] = 0;
UseGradient = (Type == EGST_WINDOWS_METALLIC) || (Type == EGST_BURNING_SKIN) ;
}
//! destructor
CGUISkin::~CGUISkin()
{
for (u32 i=0; i<EGDF_COUNT; ++i)
{
if (Fonts[i])
Fonts[i]->drop();
}
if (SpriteBank)
SpriteBank->drop();
}
//! returns default color
video::SColor CGUISkin::getColor(EGUI_DEFAULT_COLOR color) const
{
if ((u32)color < EGDC_COUNT)
return Colors[color];
else
return video::SColor();
}
//! sets a default color
void CGUISkin::setColor(EGUI_DEFAULT_COLOR which, video::SColor newColor)
{
if ((u32)which < EGDC_COUNT)
Colors[which] = newColor;
}
//! returns size for the given size type
s32 CGUISkin::getSize(EGUI_DEFAULT_SIZE size) const
{
if ((u32)size < EGDS_COUNT)
return Sizes[size];
else
return 0;
}
//! sets a default size
void CGUISkin::setSize(EGUI_DEFAULT_SIZE which, s32 size)
{
if ((u32)which < EGDS_COUNT)
Sizes[which] = size;
}
//! returns the default font
IGUIFont* CGUISkin::getFont(EGUI_DEFAULT_FONT which) const
{
if (((u32)which < EGDF_COUNT) && Fonts[which])
return Fonts[which];
else
return Fonts[EGDF_DEFAULT];
}
//! sets a default font
void CGUISkin::setFont(IGUIFont* font, EGUI_DEFAULT_FONT which)
{
if ((u32)which >= EGDF_COUNT)
return;
if (font)
{
font->grab();
if (Fonts[which])
Fonts[which]->drop();
Fonts[which] = font;
}
}
//! gets the sprite bank stored
IGUISpriteBank* CGUISkin::getSpriteBank() const
{
return SpriteBank;
}
//! set a new sprite bank or remove one by passing 0
void CGUISkin::setSpriteBank(IGUISpriteBank* bank)
{
if (bank)
bank->grab();
if (SpriteBank)
SpriteBank->drop();
SpriteBank = bank;
}
//! Returns a default icon
u32 CGUISkin::getIcon(EGUI_DEFAULT_ICON icon) const
{
if ((u32)icon < EGDI_COUNT)
return Icons[icon];
else
return 0;
}
//! Sets a default icon
void CGUISkin::setIcon(EGUI_DEFAULT_ICON icon, u32 index)
{
if ((u32)icon < EGDI_COUNT)
Icons[icon] = index;
}
//! Returns a default text. For example for Message box button captions:
//! "OK", "Cancel", "Yes", "No" and so on.
const wchar_t* CGUISkin::getDefaultText(EGUI_DEFAULT_TEXT text) const
{
if ((u32)text < EGDT_COUNT)
return Texts[text].c_str();
else
return Texts[0].c_str();
}
//! Sets a default text. For example for Message box button captions:
//! "OK", "Cancel", "Yes", "No" and so on.
void CGUISkin::setDefaultText(EGUI_DEFAULT_TEXT which, const wchar_t* newText)
{
if ((u32)which < EGDT_COUNT)
Texts[which] = newText;
}
//! draws a standard 3d button pane
/** Used for drawing for example buttons in normal state.
It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and
EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details.
\param rect: Defining area where to draw.
\param clip: Clip area.
\param element: Pointer to the element which wishes to draw this. This parameter
is usually not used by ISkin, but can be used for example by more complex
implementations to find out how to draw the part exactly. */
void CGUISkin::draw3DButtonPaneStandard(IGUIElement* element,
const core::rect<s32>& r,
const core::rect<s32>* clip)
{
if (!Driver)
return;
core::rect<s32> rect = r;
if ( Type == EGST_BURNING_SKIN )
{
rect.UpperLeftCorner.X -= 1;
rect.UpperLeftCorner.Y -= 1;
rect.LowerRightCorner.X += 1;
rect.LowerRightCorner.Y += 1;
draw3DSunkenPane(element,
getColor( EGDC_WINDOW ).getInterpolated( 0xFFFFFFFF, 0.9f )
,false, true, rect, clip);
return;
}
Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), rect, clip);
rect.LowerRightCorner.X -= 1;
rect.LowerRightCorner.Y -= 1;
Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip);
rect.UpperLeftCorner.X += 1;
rect.UpperLeftCorner.Y += 1;
Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip);
rect.LowerRightCorner.X -= 1;
rect.LowerRightCorner.Y -= 1;
if (!UseGradient)
{
Driver->draw2DRectangle(getColor(EGDC_3D_FACE), rect, clip);
}
else
{
const video::SColor c1 = getColor(EGDC_3D_FACE);
const video::SColor c2 = c1.getInterpolated(getColor(EGDC_3D_DARK_SHADOW), 0.4f);
Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip);
}
}
//! draws a pressed 3d button pane
/** Used for drawing for example buttons in pressed state.
It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and
EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details.
\param rect: Defining area where to draw.
\param clip: Clip area.
\param element: Pointer to the element which wishes to draw this. This parameter
is usually not used by ISkin, but can be used for example by more complex
implementations to find out how to draw the part exactly. */
void CGUISkin::draw3DButtonPanePressed(IGUIElement* element,
const core::rect<s32>& r,
const core::rect<s32>* clip)
{
if (!Driver)
return;
core::rect<s32> rect = r;
Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip);
rect.LowerRightCorner.X -= 1;
rect.LowerRightCorner.Y -= 1;
Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), rect, clip);
rect.UpperLeftCorner.X += 1;
rect.UpperLeftCorner.Y += 1;
Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip);
rect.UpperLeftCorner.X += 1;
rect.UpperLeftCorner.Y += 1;
if (!UseGradient)
{
Driver->draw2DRectangle(getColor(EGDC_3D_FACE), rect, clip);
}
else
{
const video::SColor c1 = getColor(EGDC_3D_FACE);
const video::SColor c2 = c1.getInterpolated(getColor(EGDC_3D_DARK_SHADOW), 0.4f);
Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip);
}
}
//! draws a sunken 3d pane
/** Used for drawing the background of edit, combo or check boxes.
\param element: Pointer to the element which wishes to draw this. This parameter
is usually not used by ISkin, but can be used for example by more complex
implementations to find out how to draw the part exactly.
\param bgcolor: Background color.
\param flat: Specifies if the sunken pane should be flat or displayed as sunken
deep into the ground.
\param rect: Defining area where to draw.
\param clip: Clip area. */
void CGUISkin::draw3DSunkenPane(IGUIElement* element, video::SColor bgcolor,
bool flat, bool fillBackGround,
const core::rect<s32>& r,
const core::rect<s32>* clip)
{
if (!Driver)
return;
core::rect<s32> rect = r;
if (flat)
{
// draw flat sunken pane
if (fillBackGround)
Driver->draw2DRectangle(bgcolor, rect, clip);
rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 1;
Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip);
rect.LowerRightCorner.Y = r.LowerRightCorner.Y;
rect.LowerRightCorner.X = rect.UpperLeftCorner.X + 1;
Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip);
rect = r;
rect.UpperLeftCorner.X = rect.LowerRightCorner.X - 1;
Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip);
rect = r;
rect.UpperLeftCorner.Y = r.LowerRightCorner.Y - 1;
rect.LowerRightCorner.Y = r.LowerRightCorner.Y;
Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip);
}
else
{
// draw deep sunken pane
if (fillBackGround)
Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip);
rect.LowerRightCorner.X -= 1;
rect.LowerRightCorner.Y -= 1;
Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip);
rect.UpperLeftCorner.X += 1;
rect.UpperLeftCorner.Y += 1;
Driver->draw2DRectangle(getColor(EGDC_3D_LIGHT), rect, clip);
rect.LowerRightCorner.X -= 1;
rect.LowerRightCorner.Y -= 1;
Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), rect, clip);
rect.UpperLeftCorner.X += 1;
rect.UpperLeftCorner.Y += 1;
Driver->draw2DRectangle(bgcolor, rect, clip);
}
}
//! draws a window background
-/** Used for drawing the background of dialogs and windows.
-\param element: Pointer to the element which wishes to draw this. This parameter
-is usually not used by ISkin, but can be used for example by more complex
-implementations to find out how to draw the part exactly.
-\param titleBarColor: Title color.
-\param drawTitleBar: True to enable title drawing.
-\param rect: Defining area where to draw.
-\param clip: Clip area.
-\return Returns rect where to draw title bar text. */
+// return where to draw title bar text.
core::rect<s32> CGUISkin::draw3DWindowBackground(IGUIElement* element,
bool drawTitleBar, video::SColor titleBarColor,
const core::rect<s32>& r,
- const core::rect<s32>* cl,
+ const core::rect<s32>* clip,
core::rect<s32>* checkClientArea)
{
if (!Driver)
{
if ( checkClientArea )
{
*checkClientArea = r;
}
return r;
}
core::rect<s32> rect = r;
// top border
rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 1;
if ( !checkClientArea )
{
- Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, cl);
+ Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip);
}
// left border
rect.LowerRightCorner.Y = r.LowerRightCorner.Y;
rect.LowerRightCorner.X = rect.UpperLeftCorner.X + 1;
if ( !checkClientArea )
{
- Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, cl);
+ Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip);
}
// right border dark outer line
rect.UpperLeftCorner.X = r.LowerRightCorner.X - 1;
rect.LowerRightCorner.X = r.LowerRightCorner.X;
rect.UpperLeftCorner.Y = r.UpperLeftCorner.Y;
rect.LowerRightCorner.Y = r.LowerRightCorner.Y;
if ( !checkClientArea )
{
- Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), rect, cl);
+ Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), rect, clip);
}
// right border bright innner line
rect.UpperLeftCorner.X -= 1;
rect.LowerRightCorner.X -= 1;
rect.UpperLeftCorner.Y += 1;
rect.LowerRightCorner.Y -= 1;
if ( !checkClientArea )
{
- Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, cl);
+ Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip);
}
// bottom border dark outer line
rect.UpperLeftCorner.X = r.UpperLeftCorner.X;
rect.UpperLeftCorner.Y = r.LowerRightCorner.Y - 1;
rect.LowerRightCorner.Y = r.LowerRightCorner.Y;
rect.LowerRightCorner.X = r.LowerRightCorner.X;
if ( !checkClientArea )
{
- Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), rect, cl);
+ Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), rect, clip);
}
// bottom border bright inner line
rect.UpperLeftCorner.X += 1;
rect.LowerRightCorner.X -= 1;
rect.UpperLeftCorner.Y -= 1;
rect.LowerRightCorner.Y -= 1;
if ( !checkClientArea )
{
- Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, cl);
+ Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip);
}
// client area for background
rect = r;
rect.UpperLeftCorner.X +=1;
rect.UpperLeftCorner.Y +=1;
rect.LowerRightCorner.X -= 2;
rect.LowerRightCorner.Y -= 2;
if (checkClientArea)
{
*checkClientArea = rect;
}
if ( !checkClientArea )
{
if (!UseGradient)
{
- Driver->draw2DRectangle(getColor(EGDC_3D_FACE), rect, cl);
+ Driver->draw2DRectangle(getColor(EGDC_3D_FACE), rect, clip);
}
else if ( Type == EGST_BURNING_SKIN )
{
const video::SColor c1 = getColor(EGDC_WINDOW).getInterpolated ( 0xFFFFFFFF, 0.9f );
const video::SColor c2 = getColor(EGDC_WINDOW).getInterpolated ( 0xFFFFFFFF, 0.8f );
- Driver->draw2DRectangle(rect, c1, c1, c2, c2, cl);
+ Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip);
}
else
{
const video::SColor c2 = getColor(EGDC_3D_SHADOW);
const video::SColor c1 = getColor(EGDC_3D_FACE);
- Driver->draw2DRectangle(rect, c1, c1, c1, c2, cl);
+ Driver->draw2DRectangle(rect, c1, c1, c1, c2, clip);
}
}
// title bar
rect = r;
rect.UpperLeftCorner.X += 2;
rect.UpperLeftCorner.Y += 2;
rect.LowerRightCorner.X -= 2;
rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + getSize(EGDS_WINDOW_BUTTON_WIDTH) + 2;
if (drawTitleBar )
{
if (checkClientArea)
{
(*checkClientArea).UpperLeftCorner.Y = rect.LowerRightCorner.Y;
}
else
{
// draw title bar
//if (!UseGradient)
- // Driver->draw2DRectangle(titleBarColor, rect, cl);
+ // Driver->draw2DRectangle(titleBarColor, rect, clip);
//else
if ( Type == EGST_BURNING_SKIN )
{
const video::SColor c = titleBarColor.getInterpolated( 0xffffffff, 0.8f);
- Driver->draw2DRectangle(rect, titleBarColor, titleBarColor, c, c, cl);
+ Driver->draw2DRectangle(rect, titleBarColor, titleBarColor, c, c, clip);
}
else
{
const video::SColor c = titleBarColor.getInterpolated(video::SColor(255,0,0,0), 0.2f);
- Driver->draw2DRectangle(rect, titleBarColor, c, titleBarColor, c, cl);
+ Driver->draw2DRectangle(rect, titleBarColor, c, titleBarColor, c, clip);
}
}
}
return rect;
}
//! draws a standard 3d menu pane
/** Used for drawing for menus and context menus.
It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and
EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details.
\param element: Pointer to the element which wishes to draw this. This parameter
is usually not used by ISkin, but can be used for example by more complex
implementations to find out how to draw the part exactly.
\param rect: Defining area where to draw.
\param clip: Clip area. */
void CGUISkin::draw3DMenuPane(IGUIElement* element,
const core::rect<s32>& r, const core::rect<s32>* clip)
{
if (!Driver)
return;
core::rect<s32> rect = r;
if ( Type == EGST_BURNING_SKIN )
{
rect.UpperLeftCorner.Y -= 3;
draw3DButtonPaneStandard(element, rect, clip);
return;
}
// in this skin, this is exactly what non pressed buttons look like,
// so we could simply call
// draw3DButtonPaneStandard(element, rect, clip);
// here.
// but if the skin is transparent, this doesn't look that nice. So
// We draw it a little bit better, with some more draw2DRectangle calls,
// but there aren't that much menus visible anyway.
rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 1;
Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip);
rect.LowerRightCorner.Y = r.LowerRightCorner.Y;
rect.LowerRightCorner.X = rect.UpperLeftCorner.X + 1;
Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip);
rect.UpperLeftCorner.X = r.LowerRightCorner.X - 1;
rect.LowerRightCorner.X = r.LowerRightCorner.X;
rect.UpperLeftCorner.Y = r.UpperLeftCorner.Y;
rect.LowerRightCorner.Y = r.LowerRightCorner.Y;
Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), rect, clip);
rect.UpperLeftCorner.X -= 1;
rect.LowerRightCorner.X -= 1;
rect.UpperLeftCorner.Y += 1;
rect.LowerRightCorner.Y -= 1;
Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip);
rect.UpperLeftCorner.X = r.UpperLeftCorner.X;
rect.UpperLeftCorner.Y = r.LowerRightCorner.Y - 1;
rect.LowerRightCorner.Y = r.LowerRightCorner.Y;
rect.LowerRightCorner.X = r.LowerRightCorner.X;
Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), rect, clip);
rect.UpperLeftCorner.X += 1;
rect.LowerRightCorner.X -= 1;
rect.UpperLeftCorner.Y -= 1;
rect.LowerRightCorner.Y -= 1;
Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip);
rect = r;
rect.UpperLeftCorner.X +=1;
rect.UpperLeftCorner.Y +=1;
rect.LowerRightCorner.X -= 2;
rect.LowerRightCorner.Y -= 2;
if (!UseGradient)
Driver->draw2DRectangle(getColor(EGDC_3D_FACE), rect, clip);
else
{
const video::SColor c1 = getColor(EGDC_3D_FACE);
const video::SColor c2 = getColor(EGDC_3D_SHADOW);
Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip);
}
}
//! draws a standard 3d tool bar
/** Used for drawing for toolbars and menus.
\param element: Pointer to the element which wishes to draw this. This parameter
is usually not used by ISkin, but can be used for example by more complex
implementations to find out how to draw the part exactly.
\param rect: Defining area where to draw.
\param clip: Clip area. */
void CGUISkin::draw3DToolBar(IGUIElement* element,
const core::rect<s32>& r,
const core::rect<s32>* clip)
{
if (!Driver)
return;
core::rect<s32> rect = r;
rect.UpperLeftCorner.X = r.UpperLeftCorner.X;
rect.UpperLeftCorner.Y = r.LowerRightCorner.Y - 1;
rect.LowerRightCorner.Y = r.LowerRightCorner.Y;
rect.LowerRightCorner.X = r.LowerRightCorner.X;
Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip);
rect = r;
rect.LowerRightCorner.Y -= 1;
if (!UseGradient)
{
Driver->draw2DRectangle(getColor(EGDC_3D_FACE), rect, clip);
}
else
if ( Type == EGST_BURNING_SKIN )
{
const video::SColor c1 = 0xF0000000 | getColor(EGDC_3D_FACE).color;
const video::SColor c2 = 0xF0000000 | getColor(EGDC_3D_SHADOW).color;
rect.LowerRightCorner.Y += 1;
Driver->draw2DRectangle(rect, c1, c2, c1, c2, clip);
}
else
{
const video::SColor c1 = getColor(EGDC_3D_FACE);
const video::SColor c2 = getColor(EGDC_3D_SHADOW);
Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip);
}
}
//! draws a tab button
/** Used for drawing for tab buttons on top of tabs.
\param element: Pointer to the element which wishes to draw this. This parameter
is usually not used by ISkin, but can be used for example by more complex
implementations to find out how to draw the part exactly.
\param active: Specifies if the tab is currently active.
\param rect: Defining area where to draw.
\param clip: Clip area. */
void CGUISkin::draw3DTabButton(IGUIElement* element, bool active,
const core::rect<s32>& frameRect, const core::rect<s32>* clip, EGUI_ALIGNMENT alignment)
{
if (!Driver)
return;
core::rect<s32> tr = frameRect;
if ( alignment == EGUIA_UPPERLEFT )
{
tr.LowerRightCorner.X -= 2;
tr.LowerRightCorner.Y = tr.UpperLeftCorner.Y + 1;
tr.UpperLeftCorner.X += 1;
Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), tr, clip);
// draw left highlight
tr = frameRect;
tr.LowerRightCorner.X = tr.UpperLeftCorner.X + 1;
tr.UpperLeftCorner.Y += 1;
Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), tr, clip);
// draw grey background
tr = frameRect;
tr.UpperLeftCorner.X += 1;
tr.UpperLeftCorner.Y += 1;
tr.LowerRightCorner.X -= 2;
Driver->draw2DRectangle(getColor(EGDC_3D_FACE), tr, clip);
// draw right middle gray shadow
tr.LowerRightCorner.X += 1;
tr.UpperLeftCorner.X = tr.LowerRightCorner.X - 1;
Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), tr, clip);
tr.LowerRightCorner.X += 1;
tr.UpperLeftCorner.X += 1;
tr.UpperLeftCorner.Y += 1;
Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), tr, clip);
}
else
{
tr.LowerRightCorner.X -= 2;
tr.UpperLeftCorner.Y = tr.LowerRightCorner.Y - 1;
tr.UpperLeftCorner.X += 1;
Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), tr, clip);
// draw left highlight
tr = frameRect;
tr.LowerRightCorner.X = tr.UpperLeftCorner.X + 1;
tr.LowerRightCorner.Y -= 1;
Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), tr, clip);
// draw grey background
tr = frameRect;
tr.UpperLeftCorner.X += 1;
tr.UpperLeftCorner.Y -= 1;
tr.LowerRightCorner.X -= 2;
tr.LowerRightCorner.Y -= 1;
Driver->draw2DRectangle(getColor(EGDC_3D_FACE), tr, clip);
// draw right middle gray shadow
tr.LowerRightCorner.X += 1;
tr.UpperLeftCorner.X = tr.LowerRightCorner.X - 1;
//tr.LowerRightCorner.Y -= 1;
Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), tr, clip);
tr.LowerRightCorner.X += 1;
tr.UpperLeftCorner.X += 1;
tr.LowerRightCorner.Y -= 1;
Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), tr, clip);
}
}
//! draws a tab control body
/** \param element: Pointer to the element which wishes to draw this. This parameter
is usually not used by ISkin, but can be used for example by more complex
implementations to find out how to draw the part exactly.
\param border: Specifies if the border should be drawn.
\param background: Specifies if the background should be drawn.
\param rect: Defining area where to draw.
\param clip: Clip area. */
void CGUISkin::draw3DTabBody(IGUIElement* element, bool border, bool background,
const core::rect<s32>& rect, const core::rect<s32>* clip, s32 tabHeight, EGUI_ALIGNMENT alignment)
{
if (!Driver)
return;
core::rect<s32> tr = rect;
if ( tabHeight == -1 )
tabHeight = getSize(gui::EGDS_BUTTON_HEIGHT);
// draw border.
if (border)
{
if ( alignment == EGUIA_UPPERLEFT )
{
// draw left hightlight
tr.UpperLeftCorner.Y += tabHeight + 2;
tr.LowerRightCorner.X = tr.UpperLeftCorner.X + 1;
Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), tr, clip);
// draw right shadow
tr.UpperLeftCorner.X = rect.LowerRightCorner.X - 1;
tr.LowerRightCorner.X = tr.UpperLeftCorner.X + 1;
Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), tr, clip);
// draw lower shadow
tr = rect;
tr.UpperLeftCorner.Y = tr.LowerRightCorner.Y - 1;
Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), tr, clip);
}
else
{
// draw left hightlight
tr.LowerRightCorner.Y -= tabHeight + 2;
tr.LowerRightCorner.X = tr.UpperLeftCorner.X + 1;
Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), tr, clip);
// draw right shadow
tr.UpperLeftCorner.X = rect.LowerRightCorner.X - 1;
tr.LowerRightCorner.X = tr.UpperLeftCorner.X + 1;
Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), tr, clip);
// draw lower shadow
tr = rect;
tr.LowerRightCorner.Y = tr.UpperLeftCorner.Y + 1;
Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), tr, clip);
}
}
if (background)
{
if ( alignment == EGUIA_UPPERLEFT )
{
tr = rect;
tr.UpperLeftCorner.Y += tabHeight + 2;
tr.LowerRightCorner.X -= 1;
tr.UpperLeftCorner.X += 1;
tr.LowerRightCorner.Y -= 1;
}
else
{
tr = rect;
tr.UpperLeftCorner.X += 1;
tr.UpperLeftCorner.Y -= 1;
tr.LowerRightCorner.X -= 1;
tr.LowerRightCorner.Y -= tabHeight + 2;
//tr.UpperLeftCorner.X += 1;
}
if (!UseGradient)
Driver->draw2DRectangle(getColor(EGDC_3D_FACE), tr, clip);
else
{
video::SColor c1 = getColor(EGDC_3D_FACE);
video::SColor c2 = getColor(EGDC_3D_SHADOW);
Driver->draw2DRectangle(tr, c1, c1, c2, c2, clip);
}
}
}
//! draws an icon, usually from the skin's sprite bank
/** \param parent: Pointer to the element which wishes to draw this icon.
This parameter is usually not used by IGUISkin, but can be used for example
by more complex implementations to find out how to draw the part exactly.
\param icon: Specifies the icon to be drawn.
\param position: The position to draw the icon
\param starttime: The time at the start of the animation
\param currenttime: The present time, used to calculate the frame number
\param loop: Whether the animation should loop or not
\param clip: Clip area. */
void CGUISkin::drawIcon(IGUIElement* element, EGUI_DEFAULT_ICON icon,
const core::position2di position,
u32 starttime, u32 currenttime,
bool loop, const core::rect<s32>* clip)
{
if (!SpriteBank)
return;
SpriteBank->draw2DSprite(Icons[icon], position, clip,
video::SColor(255,0,0,0), starttime, currenttime, loop, true);
}
EGUI_SKIN_TYPE CGUISkin::getType() const
{
return Type;
}
//! draws a 2d rectangle.
void CGUISkin::draw2DRectangle(IGUIElement* element,
const video::SColor &color, const core::rect<s32>& pos,
const core::rect<s32>* clip)
{
Driver->draw2DRectangle(color, pos, clip);
}
//! Writes attributes of the object.
//! Implement this to expose the attributes of your scene node animator for
//! scripting languages, editors, debuggers or xml serialization purposes.
void CGUISkin::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const
{
u32 i;
for (i=0; i<EGDC_COUNT; ++i)
out->addColor(GUISkinColorNames[i], Colors[i]);
for (i=0; i<EGDS_COUNT; ++i)
out->addInt(GUISkinSizeNames[i], Sizes[i]);
for (i=0; i<EGDT_COUNT; ++i)
out->addString(GUISkinTextNames[i], Texts[i].c_str());
for (i=0; i<EGDI_COUNT; ++i)
out->addInt(GUISkinIconNames[i], Icons[i]);
}
//! Reads attributes of the object.
//! Implement this to set the attributes of your scene node animator for
//! scripting languages, editors, debuggers or xml deserialization purposes.
void CGUISkin::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
u32 i;
for (i=0; i<EGDC_COUNT; ++i)
Colors[i] = in->getAttributeAsColor(GUISkinColorNames[i]);
for (i=0; i<EGDS_COUNT; ++i)
Sizes[i] = in->getAttributeAsInt(GUISkinSizeNames[i]);
for (i=0; i<EGDT_COUNT; ++i)
Texts[i] = in->getAttributeAsStringW(GUISkinTextNames[i]);
for (i=0; i<EGDI_COUNT; ++i)
Icons[i] = in->getAttributeAsInt(GUISkinIconNames[i]);
}
} // end namespace gui
} // end namespace irr
#endif // _IRR_COMPILE_WITH_GUI_
diff --git a/source/Irrlicht/CGUIWindow.cpp b/source/Irrlicht/CGUIWindow.cpp
index fb5880e..4b7801e 100644
--- a/source/Irrlicht/CGUIWindow.cpp
+++ b/source/Irrlicht/CGUIWindow.cpp
@@ -1,382 +1,391 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CGUIWindow.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include "IGUISkin.h"
#include "IGUIEnvironment.h"
#include "IVideoDriver.h"
#include "IGUIButton.h"
#include "IGUIFont.h"
#include "IGUIFontBitmap.h"
namespace irr
{
namespace gui
{
//! constructor
CGUIWindow::CGUIWindow(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect<s32> rectangle)
: IGUIWindow(environment, parent, id, rectangle), Dragging(false), IsDraggable(true), DrawBackground(true), DrawTitlebar(true), IsActive(false)
{
#ifdef _DEBUG
setDebugName("CGUIWindow");
#endif
IGUISkin* skin = 0;
if (environment)
skin = environment->getSkin();
IGUISpriteBank* sprites = 0;
video::SColor color(255,255,255,255);
s32 buttonw = 15;
if (skin)
{
buttonw = skin->getSize(EGDS_WINDOW_BUTTON_WIDTH);
sprites = skin->getSpriteBank();
color = skin->getColor(EGDC_WINDOW_SYMBOL);
}
s32 posx = RelativeRect.getWidth() - buttonw - 4;
CloseButton = Environment->addButton(core::rect<s32>(posx, 3, posx + buttonw, 3 + buttonw), this, -1,
L"", skin ? skin->getDefaultText(EGDT_WINDOW_CLOSE) : L"Close" );
CloseButton->setSubElement(true);
CloseButton->setTabStop(false);
CloseButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
if (sprites)
{
CloseButton->setSpriteBank(sprites);
CloseButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_WINDOW_CLOSE), color);
CloseButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_WINDOW_CLOSE), color);
}
posx -= buttonw + 2;
RestoreButton = Environment->addButton(core::rect<s32>(posx, 3, posx + buttonw, 3 + buttonw), this, -1,
L"", skin ? skin->getDefaultText(EGDT_WINDOW_RESTORE) : L"Restore" );
RestoreButton->setVisible(false);
RestoreButton->setSubElement(true);
RestoreButton->setTabStop(false);
RestoreButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
if (sprites)
{
RestoreButton->setSpriteBank(sprites);
RestoreButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_WINDOW_RESTORE), color);
RestoreButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_WINDOW_RESTORE), color);
}
posx -= buttonw + 2;
MinButton = Environment->addButton(core::rect<s32>(posx, 3, posx + buttonw, 3 + buttonw), this, -1,
L"", skin ? skin->getDefaultText(EGDT_WINDOW_MINIMIZE) : L"Minimize" );
MinButton->setVisible(false);
MinButton->setSubElement(true);
MinButton->setTabStop(false);
MinButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
if (sprites)
{
MinButton->setSpriteBank(sprites);
MinButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_WINDOW_MINIMIZE), color);
MinButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_WINDOW_MINIMIZE), color);
}
MinButton->grab();
RestoreButton->grab();
CloseButton->grab();
// this element is a tab group
setTabGroup(true);
setTabStop(true);
setTabOrder(-1);
updateClientRect();
}
//! destructor
CGUIWindow::~CGUIWindow()
{
if (MinButton)
MinButton->drop();
if (RestoreButton)
RestoreButton->drop();
if (CloseButton)
CloseButton->drop();
}
//! called if an event happened.
bool CGUIWindow::OnEvent(const SEvent& event)
{
if (IsEnabled)
{
switch(event.EventType)
{
case EET_GUI_EVENT:
if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST)
{
Dragging = false;
IsActive = false;
}
else
if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUSED)
{
if (Parent && ((event.GUIEvent.Caller == this) || isMyChild(event.GUIEvent.Caller)))
{
Parent->bringToFront(this);
IsActive = true;
}
else
{
IsActive = false;
}
}
else
if (event.GUIEvent.EventType == EGET_BUTTON_CLICKED)
{
if (event.GUIEvent.Caller == CloseButton)
{
if (Parent)
{
// send close event to parent
SEvent e;
e.EventType = EET_GUI_EVENT;
e.GUIEvent.Caller = this;
e.GUIEvent.Element = 0;
e.GUIEvent.EventType = EGET_ELEMENT_CLOSED;
// if the event was not absorbed
if (!Parent->OnEvent(e))
remove();
return true;
}
else
{
remove();
return true;
}
}
}
break;
case EET_MOUSE_INPUT_EVENT:
switch(event.MouseInput.Event)
{
case EMIE_LMOUSE_PRESSED_DOWN:
DragStart.X = event.MouseInput.X;
DragStart.Y = event.MouseInput.Y;
Dragging = IsDraggable;
if (Parent)
Parent->bringToFront(this);
return true;
case EMIE_LMOUSE_LEFT_UP:
Dragging = false;
return true;
case EMIE_MOUSE_MOVED:
- if ( !event.MouseInput.isLeftPressed() )
+ if (!event.MouseInput.isLeftPressed())
Dragging = false;
if (Dragging)
{
// gui window should not be dragged outside its parent
if (Parent &&
(event.MouseInput.X < Parent->getAbsolutePosition().UpperLeftCorner.X +1 ||
event.MouseInput.Y < Parent->getAbsolutePosition().UpperLeftCorner.Y +1 ||
event.MouseInput.X > Parent->getAbsolutePosition().LowerRightCorner.X -1 ||
event.MouseInput.Y > Parent->getAbsolutePosition().LowerRightCorner.Y -1))
return true;
move(core::position2d<s32>(event.MouseInput.X - DragStart.X, event.MouseInput.Y - DragStart.Y));
DragStart.X = event.MouseInput.X;
DragStart.Y = event.MouseInput.Y;
return true;
}
break;
default:
break;
}
default:
break;
}
}
return IGUIElement::OnEvent(event);
}
//! Updates the absolute position.
void CGUIWindow::updateAbsolutePosition()
{
IGUIElement::updateAbsolutePosition();
}
//! draws the element and its children
void CGUIWindow::draw()
{
- if ( IsVisible )
+ if (IsVisible)
{
IGUISkin* skin = Environment->getSkin();
// update each time because the skin is allowed to change this always.
updateClientRect();
core::rect<s32> rect = AbsoluteRect;
// draw body fast
- if ( DrawBackground )
- {
- rect = skin->draw3DWindowBackground(this, DrawTitlebar,
- skin->getColor(IsActive ? EGDC_ACTIVE_BORDER : EGDC_INACTIVE_BORDER),
- AbsoluteRect, &AbsoluteClippingRect);
-
- if (DrawTitlebar && Text.size())
- {
- rect.UpperLeftCorner.X += skin->getSize(EGDS_TITLEBARTEXT_DISTANCE_X);
- rect.UpperLeftCorner.Y += skin->getSize(EGDS_TITLEBARTEXT_DISTANCE_Y);
- rect.LowerRightCorner.X -= skin->getSize(EGDS_WINDOW_BUTTON_WIDTH) + 5;
-
- IGUIFont* font = skin->getFont(EGDF_WINDOW);
- if (font)
- {
- font->draw(Text.c_str(), rect,
- skin->getColor(IsActive ? EGDC_ACTIVE_CAPTION:EGDC_INACTIVE_CAPTION),
- false, true, &AbsoluteClippingRect);
- }
- }
- }
+ if (DrawBackground)
+ {
+ rect = skin->draw3DWindowBackground(this, DrawTitlebar,
+ skin->getColor(IsActive ? EGDC_ACTIVE_BORDER : EGDC_INACTIVE_BORDER),
+ AbsoluteRect, &AbsoluteClippingRect);
+
+ if (DrawTitlebar && Text.size())
+ {
+ rect.UpperLeftCorner.X += skin->getSize(EGDS_TITLEBARTEXT_DISTANCE_X);
+ rect.UpperLeftCorner.Y += skin->getSize(EGDS_TITLEBARTEXT_DISTANCE_Y);
+ rect.LowerRightCorner.X -= skin->getSize(EGDS_WINDOW_BUTTON_WIDTH) + 5;
+
+ IGUIFont* font = skin->getFont(EGDF_WINDOW);
+ if (font)
+ {
+ font->draw(Text.c_str(), rect,
+ skin->getColor(IsActive ? EGDC_ACTIVE_CAPTION:EGDC_INACTIVE_CAPTION),
+ false, true, &AbsoluteClippingRect);
+ }
+ }
+ }
}
IGUIElement::draw();
}
//! Returns pointer to the close button
IGUIButton* CGUIWindow::getCloseButton() const
{
return CloseButton;
}
//! Returns pointer to the minimize button
IGUIButton* CGUIWindow::getMinimizeButton() const
{
return MinButton;
}
//! Returns pointer to the maximize button
IGUIButton* CGUIWindow::getMaximizeButton() const
{
return RestoreButton;
}
+
//! Returns true if the window is draggable, false if not
bool CGUIWindow::isDraggable() const
{
return IsDraggable;
}
+
//! Sets whether the window is draggable
void CGUIWindow::setDraggable(bool draggable)
{
IsDraggable = draggable;
if (Dragging && !IsDraggable)
Dragging = false;
}
+
//! Set if the window background will be drawn
void CGUIWindow::setDrawBackground(bool draw)
{
- DrawBackground = draw;
+ DrawBackground = draw;
}
+
//! Get if the window background will be drawn
bool CGUIWindow::getDrawBackground() const
{
- return DrawBackground;
+ return DrawBackground;
}
+
//! Set if the window titlebar will be drawn
void CGUIWindow::setDrawTitlebar(bool draw)
{
- DrawTitlebar = draw;
+ DrawTitlebar = draw;
}
+
//! Get if the window titlebar will be drawn
bool CGUIWindow::getDrawTitlebar() const
{
- return DrawTitlebar;
+ return DrawTitlebar;
}
+
void CGUIWindow::updateClientRect()
{
if (! DrawBackground )
{
ClientRect = core::rect<s32>(0,0, AbsoluteRect.getWidth(), AbsoluteRect.getHeight());
return;
}
IGUISkin* skin = Environment->getSkin();
- skin->draw3DWindowBackground(this,
- DrawTitlebar,
- skin->getColor(IsActive ? EGDC_ACTIVE_BORDER : EGDC_INACTIVE_BORDER),
- AbsoluteRect, &AbsoluteClippingRect, &ClientRect);
+ skin->draw3DWindowBackground(this, DrawTitlebar,
+ skin->getColor(IsActive ? EGDC_ACTIVE_BORDER : EGDC_INACTIVE_BORDER),
+ AbsoluteRect, &AbsoluteClippingRect, &ClientRect);
ClientRect -= AbsoluteRect.UpperLeftCorner;
}
+
//! Returns the rectangle of the drawable area (without border, without titlebar and without scrollbars)
core::rect<s32> CGUIWindow::getClientRect() const
{
return ClientRect;
}
+
//! Writes attributes of the element.
void CGUIWindow::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const
{
IGUIWindow::serializeAttributes(out,options);
- out->addBool("IsDraggable", IsDraggable);
- out->addBool("DrawBackground", DrawBackground);
- out->addBool("DrawTitlebar", DrawTitlebar);
-
- // Currently we can't just serialize attributes of sub-elements.
- // To do this we either
- // a) allow further serialization after attribute serialiation (second function, callback or event)
- // b) add an IGUIElement attribute
- // c) extend the attribute system to allow attributes to have sub-attributes
- // We just serialize the most important info for now until we can do one of the above solutions.
- out->addBool("IsCloseVisible", CloseButton->isVisible());
- out->addBool("IsMinVisible", MinButton->isVisible());
- out->addBool("IsRestoreVisible", RestoreButton->isVisible());
+ out->addBool("IsDraggable", IsDraggable);
+ out->addBool("DrawBackground", DrawBackground);
+ out->addBool("DrawTitlebar", DrawTitlebar);
+
+ // Currently we can't just serialize attributes of sub-elements.
+ // To do this we either
+ // a) allow further serialization after attribute serialiation (second function, callback or event)
+ // b) add an IGUIElement attribute
+ // c) extend the attribute system to allow attributes to have sub-attributes
+ // We just serialize the most important info for now until we can do one of the above solutions.
+ out->addBool("IsCloseVisible", CloseButton->isVisible());
+ out->addBool("IsMinVisible", MinButton->isVisible());
+ out->addBool("IsRestoreVisible", RestoreButton->isVisible());
}
//! Reads attributes of the element
void CGUIWindow::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0)
{
- IGUIWindow::deserializeAttributes(in,options);
+IGUIWindow::deserializeAttributes(in,options);
- Dragging = false;
+ Dragging = false;
IsActive = false;
- IsDraggable = in->getAttributeAsBool("IsDraggable");
- DrawBackground = in->getAttributeAsBool("DrawBackground");
- DrawTitlebar = in->getAttributeAsBool("DrawTitlebar");
+ IsDraggable = in->getAttributeAsBool("IsDraggable");
+ DrawBackground = in->getAttributeAsBool("DrawBackground");
+ DrawTitlebar = in->getAttributeAsBool("DrawTitlebar");
- CloseButton->setVisible( in->getAttributeAsBool("IsCloseVisible") );
- MinButton->setVisible( in->getAttributeAsBool("IsMinVisible") );
- RestoreButton->setVisible( in->getAttributeAsBool("IsRestoreVisible") );
+ CloseButton->setVisible(in->getAttributeAsBool("IsCloseVisible"));
+ MinButton->setVisible(in->getAttributeAsBool("IsMinVisible"));
+ RestoreButton->setVisible(in->getAttributeAsBool("IsRestoreVisible"));
- updateClientRect();
+ updateClientRect();
}
+
} // end namespace gui
} // end namespace irr
#endif // _IRR_COMPILE_WITH_GUI_
|
paupawsan/Irrlicht
|
710b5395150a5f186bbc9174fb384adbfa996f48
|
Fix some warnings.
|
diff --git a/include/driverChoice.h b/include/driverChoice.h
index eede551..c3827e1 100644
--- a/include/driverChoice.h
+++ b/include/driverChoice.h
@@ -1,42 +1,42 @@
// Copyright (C) 2009-2010 Christian Stehno
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __E_DRIVER_CHOICE_H_INCLUDED__
#define __E_DRIVER_CHOICE_H_INCLUDED__
#include <iostream>
#include "EDriverTypes.h"
namespace irr
{
//! ask user for driver
static irr::video::E_DRIVER_TYPE driverChoiceConsole(bool allDrivers=true)
{
const char* const names[] = {"NullDriver","Software Renderer","Burning's Video","Direct3D 8.1","Direct3D 9.0c","OpenGL 1.x/2.x/3.x"};
printf("Please select the driver you want:\n");
irr::u32 i=0;
for (i=irr::video::EDT_COUNT; i>0; --i)
{
if (allDrivers || (irr::IrrlichtDevice::isDriverSupported(irr::video::E_DRIVER_TYPE(i-1))))
printf(" (%c) %s\n", 'a'+irr::video::EDT_COUNT-i, names[i-1]);
}
char c;
std::cin >> c;
c = irr::video::EDT_COUNT+'a'-c;
for (i=irr::video::EDT_COUNT; i>0; --i)
{
if (!(allDrivers || (irr::IrrlichtDevice::isDriverSupported(irr::video::E_DRIVER_TYPE(i-1)))))
--c;
- if (i==c)
+ if ((char)i==c)
return irr::video::E_DRIVER_TYPE(i-1);
}
return irr::video::EDT_COUNT;
}
} // end namespace irr
#endif
diff --git a/tools/GUIEditor/CGUIColorAttribute.h b/tools/GUIEditor/CGUIColorAttribute.h
index 6321f70..7d61a7b 100644
--- a/tools/GUIEditor/CGUIColorAttribute.h
+++ b/tools/GUIEditor/CGUIColorAttribute.h
@@ -1,174 +1,178 @@
#ifndef __C_GUI_COLOR_ATTRIBUTE_H_INCLUDED__
#define __C_GUI_COLOR_ATTRIBUTE_H_INCLUDED__
#include "CGUIAttribute.h"
#include "IGUIStaticText.h"
#include "IGUIScrollBar.h"
#include "IGUITabControl.h"
namespace irr
{
namespace gui
{
class CGUIColorAttribute : public CGUIAttribute
{
public:
//
CGUIColorAttribute(IGUIEnvironment* environment, IGUIElement *parent, s32 myParentID) :
CGUIAttribute(environment, parent, myParentID),
AttribSliderA(0), AttribSliderR(0), AttribSliderG(0), AttribSliderB(0),
AttribEditBox(0), AttribColor(0)
{
s32 fh = Environment->getSkin()->getFont()->getDimension(L"A").Height;
core::rect<s32> r0(getAbsolutePosition()),
r2(0, fh + 5, r0.getWidth() - 5, fh*2 + 10 ),
- r3(r2),
+ r3(r2),
r4(r2.getWidth() - 20, 3, r2.getWidth() - 3, r2.getHeight()-3);
AttribColor = Environment->addTab(r4, this, 0);
AttribColor->grab();
AttribColor->setDrawBackground(true);
AttribColor->setSubElement(true);
AttribColor->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
s32 h=2;
r2 += core::position2di(0, h*4 + Environment->getSkin()->getSize(EGDS_WINDOW_BUTTON_WIDTH)*2);
r3.LowerRightCorner.Y = r3.UpperLeftCorner.Y + Environment->getSkin()->getSize(EGDS_WINDOW_BUTTON_WIDTH)/2;
AttribSliderA = environment->addScrollBar(true, r3, this, -1);
AttribSliderA->setMax(255);
AttribSliderA->grab();
AttribSliderA->setSubElement(true);
AttribSliderA->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
r3 += core::position2di(0, r3.getHeight()+h);
AttribSliderR = environment->addScrollBar(true, r3, this, -1);
AttribSliderR->setMax(255);
AttribSliderR->grab();
AttribSliderR->setSubElement(true);
AttribSliderR->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
r3 += core::position2di(0, r3.getHeight()+h);
AttribSliderG = environment->addScrollBar(true, r3, this, -1);
AttribSliderG->setMax(255);
AttribSliderG->grab();
AttribSliderG->setSubElement(true);
AttribSliderG->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
r3 += core::position2di(0, r3.getHeight()+h);
AttribSliderB = environment->addScrollBar(true, r3, this, -1);
AttribSliderB->setMax(255);
AttribSliderB->grab();
AttribSliderB->setSubElement(true);
AttribSliderB->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
// add editbox
AttribEditBox = environment->addEditBox(
L"",
r2,
true, this, -1);
AttribEditBox->grab();
AttribEditBox->setSubElement(true);
AttribEditBox->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
}
virtual ~CGUIColorAttribute()
{
if (AttribSliderA)
AttribSliderA->drop();
if (AttribSliderR)
AttribSliderR->drop();
if (AttribSliderG)
AttribSliderG->drop();
if (AttribSliderB)
AttribSliderB->drop();
if (AttribEditBox)
AttribEditBox->drop();
if (AttribColor)
AttribColor->drop();
}
virtual void setAttrib(io::IAttributes *attribs, u32 attribIndex)
{
video::SColor col = attribs->getAttributeAsColor(attribIndex);
AttribSliderA->setPos(col.getAlpha());
AttribSliderR->setPos(col.getRed());
AttribSliderG->setPos(col.getGreen());
AttribSliderB->setPos(col.getBlue());
AttribEditBox->setText( attribs->getAttributeAsStringW(attribIndex).c_str() );
AttribColor->setBackgroundColor(col);
CGUIAttribute::setAttrib(attribs, attribIndex);
}
virtual bool OnEvent(const SEvent &e)
{
switch (e.EventType)
{
case EET_GUI_EVENT:
switch (e.GUIEvent.EventType)
{
case EGET_EDITBOX_ENTER:
case EGET_ELEMENT_FOCUS_LOST:
if (e.GUIEvent.Caller == AttribEditBox)
{
// update scrollbars from textbox
Attribs->setAttribute(Index, AttribEditBox->getText());
video::SColor col = Attribs->getAttributeAsColor(Index);
AttribSliderA->setPos(col.getAlpha());
- AttribSliderR->setPos(col.getRed());
+ AttribSliderR->setPos(col.getRed());
AttribSliderG->setPos(col.getGreen());
AttribSliderB->setPos(col.getBlue());
// update colour
AttribColor->setBackgroundColor(col);
}
break;
case EGET_SCROLL_BAR_CHANGED:
{
// update editbox from scrollbars
- video::SColor col( AttribSliderA->getPos(), AttribSliderR->getPos(),
+ video::SColor col( AttribSliderA->getPos(), AttribSliderR->getPos(),
AttribSliderG->getPos(), AttribSliderB->getPos());
Attribs->setAttribute(Index, col);
AttribEditBox->setText( Attribs->getAttributeAsStringW(Index).c_str());
// update colour
AttribColor->setBackgroundColor(col);
}
return updateAttrib();
+ default:
+ break;
}
break;
+ default:
+ break;
}
return CGUIAttribute::OnEvent(e);
}
// save the attribute and possibly post the event to its parent
virtual bool updateAttrib(bool sendEvent=true)
{
if (!Attribs)
return true;
Attribs->setAttribute(Index, AttribEditBox->getText());
AttribEditBox->setText(Attribs->getAttributeAsStringW(Index).c_str());
return CGUIAttribute::updateAttrib(sendEvent);
}
//! this shoudln't be serialized, but this is included as it's an example
virtual const c8* getTypeName() const
- {
- return "color_attribute";
+ {
+ return "color_attribute";
}
private:
IGUIScrollBar* AttribSliderA;
IGUIScrollBar* AttribSliderR;
IGUIScrollBar* AttribSliderG;
IGUIScrollBar* AttribSliderB;
IGUIEditBox* AttribEditBox;
IGUITab* AttribColor;
};
} // namespace gui
} // namespace irr
#endif
diff --git a/tools/GUIEditor/CGUIEditWindow.cpp b/tools/GUIEditor/CGUIEditWindow.cpp
index aedf1ff..18f26df 100644
--- a/tools/GUIEditor/CGUIEditWindow.cpp
+++ b/tools/GUIEditor/CGUIEditWindow.cpp
@@ -1,287 +1,293 @@
#include "CGUIEditWindow.h"
#include "IGUISkin.h"
#include "IGUIEnvironment.h"
#include "IGUIElementFactory.h"
#include "IAttributes.h"
#include "IGUIFont.h"
#include "IGUITabControl.h"
#include "CGUIEditWorkspace.h"
using namespace irr;
using namespace gui;
//! constructor
CGUIEditWindow::CGUIEditWindow(IGUIEnvironment* environment, core::rect<s32> rectangle, IGUIElement *parent)
: IGUIWindow(environment, parent, -1, rectangle),
Dragging(false), IsDraggable(true), Resizing(false), SelectedElement(0),
AttribEditor(0), OptionEditor(0), EnvEditor(0)
{
#ifdef _DEBUG
setDebugName("CGUIEditWindow");
#endif
// we can't tab out of this window
setTabGroup(true);
// we can ctrl+tab to it
setTabStop(true);
// the tab order number is auto-assigned
setTabOrder(-1);
// set window text
setText(L"GUI Editor");
// return if we have no skin.
IGUISkin *skin = environment->getSkin();
if (!skin)
return;
s32 th = skin->getSize(EGDS_WINDOW_BUTTON_WIDTH);
setRelativePosition(core::rect<s32>(50,50,250,500));
setMinSize(core::dimension2du(200,200));
IGUITabControl *TabControl = environment->addTabControl(core::rect<s32>(1,th+5,199,449), this, false, true);
TabControl->setSubElement(true);
TabControl->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT);
TabControl->addTab(L"Tools");
//L"Texture Cache Browser"
//L"Font Browser"
//L"Font Generator"
//L"Sprite Editor"
//Environment->addGUIElement("textureCacheBrowser", this);
IGUITab* EditorTab = TabControl->addTab(L"Editor");
OptionEditor = (CGUIAttributeEditor*) environment->addGUIElement("attributeEditor", EditorTab);
OptionEditor->grab();
OptionEditor->setID(EGUIEDCE_OPTION_EDITOR);
OptionEditor->setRelativePositionProportional(core::rect<f32>(0.0f, 0.0f, 1.0f, 1.0f));
OptionEditor->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT);
if (Parent && Parent->getParent() == Environment->getRootGUIElement())
{
IGUITab* EnvTab = TabControl->addTab(L"Env");
EnvEditor = (CGUIAttributeEditor*) environment->addGUIElement("attributeEditor", EnvTab);
EnvEditor->grab();
EnvEditor->setID(EGUIEDCE_ENV_EDITOR);
EnvEditor->setRelativePositionProportional(core::rect<f32>(0.0f, 0.0f, 1.0f, 1.0f));
EnvEditor->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT);
}
IGUITab* ElementTab = TabControl->addTab(L"Element");
AttribEditor = (CGUIAttributeEditor*) environment->addGUIElement("attributeEditor", ElementTab);
AttribEditor->grab();
AttribEditor->setID(EGUIEDCE_ATTRIB_EDITOR);
AttribEditor->setRelativePositionProportional(core::rect<f32>(0.0f, 0.0f, 1.0f, 1.0f));
AttribEditor->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT);
ResizeButton = environment->addButton(core::rect<s32>(199-th,449-th,199,449), this);
ResizeButton->setDrawBorder(false);
ResizeButton->setEnabled(false);
ResizeButton->setSpriteBank(skin->getSpriteBank());
ResizeButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_WINDOW_RESIZE), skin->getColor(EGDC_WINDOW_SYMBOL));
ResizeButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_WINDOW_RESIZE), skin->getColor(EGDC_WINDOW_SYMBOL));
ResizeButton->grab();
ResizeButton->setSubElement(true);
ResizeButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT);
}
//! destructor
CGUIEditWindow::~CGUIEditWindow()
{
// drop everything
if (AttribEditor)
AttribEditor->drop();
if (EnvEditor)
EnvEditor->drop();
if (OptionEditor)
OptionEditor->drop();
if (ResizeButton)
ResizeButton->drop();
}
CGUIAttributeEditor* CGUIEditWindow::getEnvironmentEditor() const
{
return EnvEditor;
}
CGUIAttributeEditor* CGUIEditWindow::getAttributeEditor() const
{
return AttribEditor;
}
CGUIAttributeEditor* CGUIEditWindow::getOptionEditor() const
{
return OptionEditor;
}
void CGUIEditWindow::setSelectedElement(IGUIElement *sel)
{
// save changes
AttribEditor->updateAttribs();
io::IAttributes* Attribs = AttribEditor->getAttribs();
if (SelectedElement && sel != SelectedElement)
{
// deserialize attributes
SelectedElement->deserializeAttributes(Attribs);
}
// clear the attributes list
Attribs->clear();
SelectedElement = sel;
// get the new attributes
if (SelectedElement)
SelectedElement->serializeAttributes(Attribs);
AttribEditor->refreshAttribs();
}
//! draws the element and its children.
//! same code as for a window
void CGUIEditWindow::draw()
{
if (!IsVisible)
return;
IGUISkin* skin = Environment->getSkin();
core::rect<s32> rect = AbsoluteRect;
// draw body fast
rect = skin->draw3DWindowBackground(this, true, skin->getColor(EGDC_ACTIVE_BORDER),
AbsoluteRect, &AbsoluteClippingRect);
if (Text.size())
{
rect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X);
rect.UpperLeftCorner.Y += skin->getSize(EGDS_TEXT_DISTANCE_Y);
rect.LowerRightCorner.X -= skin->getSize(EGDS_WINDOW_BUTTON_WIDTH) + 5;
IGUIFont* font = skin->getFont();
if (font)
font->draw(Text.c_str(), rect, skin->getColor(EGDC_ACTIVE_CAPTION), false, true, &AbsoluteClippingRect);
}
IGUIElement::draw();
}
//! called if an event happened.
bool CGUIEditWindow::OnEvent(const SEvent &event)
{
switch(event.EventType)
{
case EET_GUI_EVENT:
switch(event.GUIEvent.EventType)
{
case EGET_ELEMENT_FOCUS_LOST:
if (event.GUIEvent.Caller == this ||
event.GUIEvent.Caller == ResizeButton)
{
Dragging = false;
Resizing = false;
}
break;
+ default:
+ break;
}
break;
case EET_MOUSE_INPUT_EVENT:
switch(event.MouseInput.Event)
{
case EMIE_LMOUSE_PRESSED_DOWN:
{
DragStart.X = event.MouseInput.X;
DragStart.Y = event.MouseInput.Y;
IGUIElement* clickedElement = getElementFromPoint(DragStart);
if (clickedElement == this)
{
Dragging = IsDraggable;
//Environment->setFocus(this);
if (Parent)
Parent->bringToFront(this);
return true;
}
else if (clickedElement == ResizeButton)
{
Resizing = true;
//Environment->setFocus(this);
if (Parent)
Parent->bringToFront(this);
return true;
}
break;
}
case EMIE_LMOUSE_LEFT_UP:
if (Dragging || Resizing)
{
Dragging = false;
Resizing = false;
return true;
}
break;
case EMIE_MOUSE_MOVED:
if (Dragging || Resizing)
{
// gui window should not be dragged outside of its parent
if (Parent)
if (event.MouseInput.X < Parent->getAbsolutePosition().UpperLeftCorner.X +1 ||
event.MouseInput.Y < Parent->getAbsolutePosition().UpperLeftCorner.Y +1 ||
event.MouseInput.X > Parent->getAbsolutePosition().LowerRightCorner.X -1 ||
event.MouseInput.Y > Parent->getAbsolutePosition().LowerRightCorner.Y -1)
return true;
core::position2di diff(event.MouseInput.X - DragStart.X, event.MouseInput.Y - DragStart.Y);
if (Dragging)
{
move(diff);
DragStart.X = event.MouseInput.X;
DragStart.Y = event.MouseInput.Y;
}
else if (Resizing)
{
core::position2di dp = RelativeRect.LowerRightCorner + diff;
setRelativePosition(core::rect<s32>(RelativeRect.UpperLeftCorner, dp));
DragStart += dp - RelativeRect.LowerRightCorner + diff;
}
return true;
}
break;
+ default:
+ break;
}
+ default:
+ break;
}
return Parent ? Parent->OnEvent(event) : false;
}
bool CGUIEditWindow::isDraggable() const
{
return IsDraggable;
}
void CGUIEditWindow::setDraggable(bool draggable)
{
IsDraggable = draggable;
if (Dragging && !IsDraggable)
Dragging = false;
}
// we're supposed to supply these if we're creating an IGUIWindow
// but we don't need them so we'll just return null
//! Returns the rectangle of the drawable area (without border, without titlebar and without scrollbars)
core::rect<s32> CGUIEditWindow::getClientRect() const
{
return core::recti();
}
IGUIButton* CGUIEditWindow::getCloseButton() const {return 0;}
IGUIButton* CGUIEditWindow::getMinimizeButton() const {return 0;}
IGUIButton* CGUIEditWindow::getMaximizeButton() const {return 0;}
diff --git a/tools/GUIEditor/CGUIEditWorkspace.cpp b/tools/GUIEditor/CGUIEditWorkspace.cpp
index 7a32ab2..74290c0 100644
--- a/tools/GUIEditor/CGUIEditWorkspace.cpp
+++ b/tools/GUIEditor/CGUIEditWorkspace.cpp
@@ -1,899 +1,911 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt / Gaz Davidson
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
// Thanks to Midnight for all his testing, bug fixes and patches :)
#include "CGUIEditWorkspace.h"
#include "IGUIEnvironment.h"
#include "IVideoDriver.h"
#include "IOSOperator.h"
#include "IReadFile.h"
#include "IFileSystem.h"
#include "IXMLWriter.h"
#include "IGUISkin.h"
#include "IGUIElementFactory.h"
#include "CGUIEditWindow.h"
#include "IGUIContextMenu.h"
#include "IGUIFileOpenDialog.h"
#include "CGUIAttribute.h"
#include "CMemoryReadWriteFile.h"
namespace irr
{
namespace gui
{
//! constructor
CGUIEditWorkspace::CGUIEditWorkspace(IGUIEnvironment* environment, s32 id, IGUIElement *parent)
: IGUIElement(EGUIET_ELEMENT, environment, parent ? parent : environment->getRootGUIElement(), id, environment->getRootGUIElement()->getAbsolutePosition()),
CurrentMode(EGUIEDM_SELECT), MouseOverMode(EGUIEDM_SELECT),
GridSize(10,10), MenuCommandStart(0x3D17), DrawGrid(false), UseGrid(true),
MouseOverElement(0), SelectedElement(0), EditorWindow(0)
{
#ifdef _DEBUG
setDebugName("CGUIEditWorkspace");
#endif
// this element is never saved.
setSubElement(true);
// it resizes to fit a resizing window
setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT);
EditorWindow = (CGUIEditWindow*) Environment->addGUIElement("GUIEditWindow", this);
if (EditorWindow)
{
EditorWindow->grab();
EditorWindow->setSubElement(true);
Environment->setFocus(EditorWindow);
serializeAttributes(EditorWindow->getOptionEditor()->getAttribs());
EditorWindow->getOptionEditor()->refreshAttribs();
if (EditorWindow->getEnvironmentEditor())
{
Environment->serializeAttributes(EditorWindow->getEnvironmentEditor()->getAttribs());
EditorWindow->getEnvironmentEditor()->refreshAttribs();
}
}
}
//! destructor
CGUIEditWorkspace::~CGUIEditWorkspace()
{
if (EditorWindow)
EditorWindow->drop();
}
void CGUIEditWorkspace::setMenuCommandIDStart(s32 id)
{
MenuCommandStart = id;
}
CGUIEditWorkspace::EGUIEDIT_MODE CGUIEditWorkspace::getModeFromPos(core::position2di p)
{
if (SelectedElement)
{
core::rect<s32> r = SelectedElement->getAbsolutePosition();
- if (TLRect.isPointInside(p))
+ if (TLRect.isPointInside(p))
return EGUIEDM_RESIZE_TL;
else if (TRRect.isPointInside(p))
return EGUIEDM_RESIZE_TR;
else if (BLRect.isPointInside(p) )
return EGUIEDM_RESIZE_BL;
else if (BRRect.isPointInside(p))
return EGUIEDM_RESIZE_BR;
else if (TopRect.isPointInside(p))
return EGUIEDM_RESIZE_T;
else if (BRect.isPointInside(p))
return EGUIEDM_RESIZE_B;
else if (LRect.isPointInside(p))
return EGUIEDM_RESIZE_L;
else if (RRect.isPointInside(p))
return EGUIEDM_RESIZE_R;
else if (getEditableElementFromPoint(SelectedElement, p) == SelectedElement)
return EGUIEDM_MOVE;
- else
+ else
return EGUIEDM_SELECT;
}
return EGUIEDM_SELECT;
}
IGUIElement* CGUIEditWorkspace::getEditableElementFromPoint(IGUIElement *start, const core::position2di &point, s32 index )
{
IGUIElement* target = 0;
// we have to search from back to front.
core::list<IGUIElement*>::ConstIterator it = start->getChildren().getLast();
s32 count=0;
while(it != start->getChildren().end())
{
target = getEditableElementFromPoint((*it),point);
if (target)
{
if (!target->isSubElement() && !isMyChild(target) && target != this)
{
if (index == count)
return target;
else
count++;
}
else
target = 0;
}
--it;
}
if (start->getAbsolutePosition().isPointInside(point))
target = start;
return target;
}
void CGUIEditWorkspace::setSelectedElement(IGUIElement *sel)
{
IGUIElement* focus = Environment->getFocus();
// we only give focus back to children
if (!isMyChild(focus))
focus = 0;
if (SelectedElement != Parent)
{
if (SelectedElement != sel && EditorWindow)
{
EditorWindow->setSelectedElement(sel);
SelectedElement = sel;
}
}
else
SelectedElement = 0;
if (focus)
Environment->setFocus(focus);
else
Environment->setFocus(this);
}
IGUIElement* CGUIEditWorkspace::getSelectedElement()
{
return SelectedElement;
}
void CGUIEditWorkspace::selectNextSibling()
{
IGUIElement* p=0;
if (!SelectedElement)
p = Parent;
else
p = SelectedElement->getParent();
core::list<IGUIElement*>::ConstIterator it = p->getChildren().begin();
// find selected element
if (SelectedElement)
while (*it != SelectedElement)
++it;
if (it !=p->getChildren().end())
++it;
// find next non sub-element
while (it != p->getChildren().end() && (*it)->isSubElement())
++it;
if (it != p->getChildren().end())
setSelectedElement(*it);
}
void CGUIEditWorkspace::selectPreviousSibling()
{
IGUIElement* p=0;
if (!SelectedElement)
p = Parent;
else
p = SelectedElement->getParent();
core::list<IGUIElement*>::ConstIterator it = p->getChildren().getLast();
// find selected element
if (SelectedElement)
while (*it != SelectedElement)
--it;
if (it != p->getChildren().end())
--it;
// find next non sub-element
while (it != p->getChildren().end() && (*it)->isSubElement())
--it;
if (it != p->getChildren().end())
setSelectedElement(*it);
}
//! called if an event happened.
bool CGUIEditWorkspace::OnEvent(const SEvent &e)
{
IGUIFileOpenDialog* dialog=0;
switch(e.EventType)
{
case ATTRIBEDIT_ATTRIB_CHANGED:
{
switch (e.UserEvent.UserData1)
{
case EGUIEDCE_ATTRIB_EDITOR:
{
// update selected items attributes
if (SelectedElement)
{
SelectedElement->deserializeAttributes(EditorWindow->getAttributeEditor()->getAttribs());
}
return true;
}
case EGUIEDCE_OPTION_EDITOR:
{
// update editor options
deserializeAttributes(EditorWindow->getOptionEditor()->getAttribs());
return true;
}
case EGUIEDCE_ENV_EDITOR:
{
// update environment
Environment->deserializeAttributes(EditorWindow->getEnvironmentEditor()->getAttribs());
return true;
}
}
}
break;
case EET_KEY_INPUT_EVENT:
if (!e.KeyInput.PressedDown)
{
switch (e.KeyInput.Key)
{
case KEY_DELETE:
if (SelectedElement)
{
IGUIElement* el = SelectedElement;
setSelectedElement(0);
MouseOverElement = 0;
el->remove();
}
break;
case KEY_KEY_X:
if (e.KeyInput.Control && SelectedElement)
{
// cut
CopySelectedElementXML();
// delete element
IGUIElement *el = SelectedElement;
setSelectedElement(0);
MouseOverElement = 0;
el->remove();
}
break;
case KEY_KEY_C:
// copy
if (e.KeyInput.Control && SelectedElement)
{
CopySelectedElementXML();
}
break;
case KEY_KEY_V:
// paste
if (e.KeyInput.Control)
{
PasteXMLToSelectedElement();
}
break;
+ default:
+ break;
}
return true;
}
break;
case EET_MOUSE_INPUT_EVENT:
switch(e.MouseInput.Event)
{
case EMIE_MOUSE_WHEEL:
{
f32 wheel = e.MouseInput.Wheel;
if (wheel > 0)
selectPreviousSibling();
else
selectNextSibling();
}
break;
case EMIE_LMOUSE_PRESSED_DOWN:
{
core::position2di p = core::position2di(e.MouseInput.X,e.MouseInput.Y);
IGUIElement* newSelection = getElementFromPoint(p);
if (newSelection != this && isMyChild(newSelection) ) // redirect event
{
Environment->setFocus(newSelection);
return true;
}
// hide the gui editor
if (EditorWindow)
EditorWindow->setVisible(false);
if (CurrentMode == EGUIEDM_SELECT)
{
if (SelectedElement)
{
// start moving or dragging
CurrentMode = getModeFromPos(p);
if (CurrentMode == EGUIEDM_MOVE)
StartMovePos = SelectedElement->getAbsolutePosition().UpperLeftCorner;
DragStart = p;
SelectedArea = SelectedElement->getAbsolutePosition();
}
if (CurrentMode < EGUIEDM_MOVE)
{
// selecting an element...
MouseOverElement = getEditableElementFromPoint(Parent, p);
if (MouseOverElement == Parent)
MouseOverElement = 0;
setSelectedElement(MouseOverElement);
}
}
break;
}
case EMIE_RMOUSE_PRESSED_DOWN:
if (CurrentMode == EGUIEDM_SELECT_NEW_PARENT || CurrentMode >= EGUIEDM_MOVE)
{
// cancel dragging
CurrentMode = EGUIEDM_SELECT;
}
else
{
DragStart = core::position2di(e.MouseInput.X,e.MouseInput.Y);
// root menu
IGUIContextMenu* mnu = Environment->addContextMenu(
core::rect<s32>(e.MouseInput.X, e.MouseInput.Y, e.MouseInput.Y+100, e.MouseInput.Y+100),this);
mnu->addItem(L"File",-1,true,true);
mnu->addItem(L"Edit",-1,true,true);
mnu->addItem(L"View",-1,true,true);
mnu->addItem(SelectedElement ? L"Add child" : L"Add" ,-1,true,true);
// file menu
IGUIContextMenu* sub = mnu->getSubMenu(0);
IGUIContextMenu* sub2 =0;
sub->addItem(L"New", MenuCommandStart + EGUIEDMC_FILE_NEW );
sub->addItem(L"Load...",MenuCommandStart + EGUIEDMC_FILE_LOAD);
sub->addItem(L"Save...",MenuCommandStart + EGUIEDMC_FILE_SAVE);
// edit menu
sub = mnu->getSubMenu(1);
sub->addItem(L"Cut (ctrl+x)", MenuCommandStart + EGUIEDMC_CUT_ELEMENT, (SelectedElement != 0));
sub->addItem(L"Copy (ctrl+c)", MenuCommandStart + EGUIEDMC_COPY_ELEMENT, (SelectedElement != 0));
- sub->addItem(L"Paste (ctrl+v)", MenuCommandStart + EGUIEDMC_PASTE_ELEMENT,
+ sub->addItem(L"Paste (ctrl+v)", MenuCommandStart + EGUIEDMC_PASTE_ELEMENT,
(core::stringc(Environment->getOSOperator()->getTextFromClipboard()) != ""));
sub->addItem(L"Delete (del)", MenuCommandStart + EGUIEDMC_DELETE_ELEMENT, (SelectedElement != 0));
sub->addSeparator();
sub->addItem(L"Set parent", MenuCommandStart + EGUIEDMC_SET_PARENT, (SelectedElement != 0));
sub->addItem(L"Bring to front", MenuCommandStart + EGUIEDMC_BRING_TO_FRONT, (SelectedElement != 0));
sub->addSeparator();
sub->addItem(L"Save to XML...", MenuCommandStart + EGUIEDMC_SAVE_ELEMENT, (SelectedElement != 0));
sub = mnu->getSubMenu(2);
// view menu
if (EditorWindow)
sub->addItem(EditorWindow->isVisible() ? L"Hide window" : L"Show window", MenuCommandStart + EGUIEDMC_TOGGLE_EDITOR);
sub = mnu->getSubMenu(3);
s32 i,j,c=0;
sub->addItem(L"Default factory",-1,true, true);
// add elements from each factory
for (i=0; u32(i) < Environment->getRegisteredGUIElementFactoryCount(); ++i)
{
sub2 = sub->getSubMenu(i);
IGUIElementFactory *f = Environment->getGUIElementFactory(i);
for (j=0; j< f->getCreatableGUIElementTypeCount(); ++j)
{
sub2->addItem(core::stringw(f->getCreateableGUIElementTypeName(j)).c_str(), MenuCommandStart + EGUIEDMC_COUNT + c);
c++;
}
if (u32(i+1) < Environment->getRegisteredGUIElementFactoryCount())
{
core::stringw strFact;
strFact = L"Factory ";
strFact += i+1;
sub->addItem(strFact.c_str(),-1, true, true);
}
}
sub->addSeparator();
sub->addItem(L"From XML...", MenuCommandStart + EGUIEDMC_INSERT_XML);
// set focus to menu
Environment->setFocus(mnu);
}
break;
case EMIE_LMOUSE_LEFT_UP:
// make window visible again
if (EditorWindow)
EditorWindow->setVisible(true);
if (CurrentMode == EGUIEDM_SELECT_NEW_PARENT)
{
if (SelectedElement)
{
- MouseOverElement = getEditableElementFromPoint(Parent,
+ MouseOverElement = getEditableElementFromPoint(Parent,
core::position2di(e.MouseInput.X,e.MouseInput.Y));
if (MouseOverElement)
{
MouseOverElement->addChild(SelectedElement);
setSelectedElement(0);
setSelectedElement(SelectedElement);
}
}
CurrentMode = EGUIEDM_SELECT;
}
else if (CurrentMode >= EGUIEDM_MOVE)
{
IGUIElement *sel = SelectedElement;
// unselect
setSelectedElement(0);
// move
core::position2d<s32> p = sel->getParent()->getAbsolutePosition().UpperLeftCorner;
sel->setRelativePosition(SelectedArea - p);
// select
setSelectedElement(sel);
// reset selection mode...
CurrentMode = EGUIEDM_SELECT;
}
break;
case EMIE_MOUSE_MOVED:
// always on top
Parent->bringToFront(this);
// if selecting
if (CurrentMode == EGUIEDM_SELECT || CurrentMode == EGUIEDM_SELECT_NEW_PARENT)
{
core::position2di p = core::position2di(e.MouseInput.X,e.MouseInput.Y);
// highlight the element that the mouse is over
MouseOverElement = getEditableElementFromPoint(Parent, p);
if (MouseOverElement == Parent)
{
MouseOverElement = 0;
}
if (CurrentMode == EGUIEDM_SELECT)
{
MouseOverMode = getModeFromPos(p);
if (MouseOverMode > EGUIEDM_MOVE)
{
MouseOverElement = SelectedElement;
}
}
}
else if (CurrentMode == EGUIEDM_MOVE)
{
// get difference
core::position2di p = core::position2di(e.MouseInput.X,e.MouseInput.Y);
p -= DragStart;
// apply to top corner
p = StartMovePos + p;
if (UseGrid)
{
p.X = (p.X/GridSize.Width)*GridSize.Width;
p.Y = (p.Y/GridSize.Height)*GridSize.Height;
}
SelectedArea += p - SelectedArea.UpperLeftCorner;
}
else if (CurrentMode > EGUIEDM_MOVE)
{
// get difference from start position
core::position2di p = core::position2di(e.MouseInput.X,e.MouseInput.Y);
if (UseGrid)
{
p.X = (p.X/GridSize.Width)*GridSize.Width;
p.Y = (p.Y/GridSize.Height)*GridSize.Height;
}
switch(CurrentMode)
{
case EGUIEDM_RESIZE_T:
SelectedArea.UpperLeftCorner.Y = p.Y;
break;
case EGUIEDM_RESIZE_B:
SelectedArea.LowerRightCorner.Y = p.Y;
break;
case EGUIEDM_RESIZE_L:
SelectedArea.UpperLeftCorner.X = p.X;
break;
case EGUIEDM_RESIZE_R:
SelectedArea.LowerRightCorner.X = p.X;
break;
case EGUIEDM_RESIZE_TL:
SelectedArea.UpperLeftCorner = p;
break;
case EGUIEDM_RESIZE_TR:
SelectedArea.UpperLeftCorner.Y = p.Y;
SelectedArea.LowerRightCorner.X = p.X;
break;
case EGUIEDM_RESIZE_BL:
SelectedArea.UpperLeftCorner.X = p.X;
SelectedArea.LowerRightCorner.Y = p.Y;
break;
case EGUIEDM_RESIZE_BR:
SelectedArea.LowerRightCorner = p;
break;
+ default:
+ break;
}
}
+ break;
+ default:
break;
}
break;
case EET_GUI_EVENT:
switch(e.GUIEvent.EventType)
{
// load a gui file
case EGET_FILE_SELECTED:
dialog = (IGUIFileOpenDialog*)e.GUIEvent.Caller;
Environment->loadGUI(core::stringc(dialog->getFileName()).c_str());
break;
case EGET_MENU_ITEM_SELECTED:
-
+ {
IGUIContextMenu *menu = (IGUIContextMenu*)e.GUIEvent.Caller;
s32 cmdID = menu->getItemCommandId(menu->getSelectedItem()) - MenuCommandStart;
IGUIElement* el;
switch(cmdID)
{
//! file commands
case EGUIEDMC_FILE_NEW:
// clear all elements belonging to our parent
setSelectedElement(0);
MouseOverElement = 0;
el = Parent;
grab();
// remove all children
while(Children.end() != el->getChildren().begin())
el->removeChild(*(el->getChildren().begin()));
// attach to parent again
el->addChild(this);
drop();
break;
case EGUIEDMC_FILE_LOAD:
Environment->addFileOpenDialog(L"Please select a GUI file to open", false, this);
break;
case EGUIEDMC_FILE_SAVE:
Environment->saveGUI("guiTest.xml");
break;
//! edit menu
case EGUIEDMC_CUT_ELEMENT:
{
CopySelectedElementXML();
// delete element
el = SelectedElement;
setSelectedElement(0);
MouseOverElement = 0;
el->remove();
break;
}
case EGUIEDMC_COPY_ELEMENT:
CopySelectedElementXML();
break;
case EGUIEDMC_PASTE_ELEMENT:
PasteXMLToSelectedElement();
break;
case EGUIEDMC_DELETE_ELEMENT:
el = SelectedElement;
setSelectedElement(0);
MouseOverElement = 0;
el->remove();
break;
case EGUIEDMC_SET_PARENT:
CurrentMode = EGUIEDM_SELECT_NEW_PARENT;
break;
case EGUIEDMC_BRING_TO_FRONT:
SelectedElement->getParent()->bringToFront(SelectedElement);
break;
case EGUIEDMC_SAVE_ELEMENT:
Environment->saveGUI("guiTest.xml", SelectedElement ? SelectedElement : Environment->getRootGUIElement() );
break;
//! toggle edit window
case EGUIEDMC_TOGGLE_EDITOR:
break;
case EGUIEDMC_INSERT_XML:
Environment->loadGUI("guiTest.xml", SelectedElement ? SelectedElement : Environment->getRootGUIElement() );
break;
default:
// create element from factory?
if (cmdID >= EGUIEDMC_COUNT)
{
s32 num = cmdID - EGUIEDMC_COUNT; // get index
// loop through all factories
s32 i, c=Environment->getRegisteredGUIElementFactoryCount();
for (i=0; i<c && num > Environment->getGUIElementFactory(i)->getCreatableGUIElementTypeCount(); ++i)
{
num -= Environment->getGUIElementFactory(i)->getCreatableGUIElementTypeCount();
}
if (num < Environment->getGUIElementFactory(i)->getCreatableGUIElementTypeCount() )
{
core::stringc name = Environment->getGUIElementFactory(i)->getCreateableGUIElementTypeName(num);
IGUIElement *parentElement = SelectedElement ? SelectedElement : Environment->getRootGUIElement();
// add it
IGUIElement *newElement = Environment->getGUIElementFactory(i)->addGUIElement(name.c_str(),parentElement);
if (newElement)
{
core::position2di p = DragStart - parentElement->getAbsolutePosition().UpperLeftCorner;
newElement->setRelativePosition(core::rect<s32>(p,p+core::position2di(100,100)));
//Environment->removeFocus(newElement);
}
}
}
break;
+ }
}
return true;
+ default:
+ break;
}
break;
+
+ default:
+ break;
}
- // even if we didn't absorb the event,
+ // even if we didn't absorb the event,
// we never pass events back to the GUI we're editing!
return false;
}
//! draws the element and its children
void CGUIEditWorkspace::draw()
{
video::IVideoDriver *driver = Environment->getVideoDriver();
if (DrawGrid)
{
// draw the grid
core::rect<s32> r = getAbsolutePosition();
s32 cy = r.UpperLeftCorner.Y;
while (cy < r.LowerRightCorner.Y)
{
s32 cx = r.UpperLeftCorner.X;
while (cx < r.LowerRightCorner.X)
{
driver->draw2DRectangle(video::SColor(40,0,0,90),core::rect<s32>(cx+1,cy+1,GridSize.Width+cx,GridSize.Height+cy));
cx += GridSize.Width;
}
cy += GridSize.Height;
}
}
if (MouseOverElement &&
MouseOverElement != SelectedElement &&
MouseOverElement != Parent)
{
core::rect<s32> r = MouseOverElement->getAbsolutePosition();
driver->draw2DRectangle(video::SColor(100,0,0,255), r);
}
if (SelectedElement && CurrentMode == EGUIEDM_SELECT)
{
driver->draw2DRectangle(video::SColor(100,0,255,0),SelectedElement->getAbsolutePosition());
}
if (CurrentMode >= EGUIEDM_MOVE)
{
driver->draw2DRectangle(video::SColor(100,255,0,0),SelectedArea);
}
if ( (SelectedElement && CurrentMode >= EGUIEDM_MOVE) ||
(SelectedElement && MouseOverElement == SelectedElement && MouseOverMode >= EGUIEDM_MOVE) )
{
// draw handles for moving
EGUIEDIT_MODE m = CurrentMode;
core::rect<s32> r = SelectedArea;
if (m < EGUIEDM_MOVE)
{
m = MouseOverMode;
r = SelectedElement->getAbsolutePosition();
}
core::position2di d = core::position2di(4,4);
TLRect = core::rect<s32>(r.UpperLeftCorner, r.UpperLeftCorner + d );
TRRect = core::rect<s32>(r.LowerRightCorner.X-4, r.UpperLeftCorner.Y, r.LowerRightCorner.X, r.UpperLeftCorner.Y+4);
TopRect = core::rect<s32>(r.getCenter().X-2, r.UpperLeftCorner.Y,r.getCenter().X+2, r.UpperLeftCorner.Y+4 );
BLRect = core::rect<s32>(r.UpperLeftCorner.X, r.LowerRightCorner.Y-4, r.UpperLeftCorner.X+4, r.LowerRightCorner.Y);
LRect = core::rect<s32>(r.UpperLeftCorner.X,r.getCenter().Y-2, r.UpperLeftCorner.X+4, r.getCenter().Y+2 );
- RRect = core::rect<s32>(r.LowerRightCorner.X-4,r.getCenter().Y-2, r.LowerRightCorner.X, r.getCenter().Y+2 );
+ RRect = core::rect<s32>(r.LowerRightCorner.X-4,r.getCenter().Y-2, r.LowerRightCorner.X, r.getCenter().Y+2 );
BRRect = core::rect<s32>(r.LowerRightCorner-d, r.LowerRightCorner);
- BRect = core::rect<s32>(r.getCenter().X-2, r.LowerRightCorner.Y-4,r.getCenter().X+2, r.LowerRightCorner.Y );
+ BRect = core::rect<s32>(r.getCenter().X-2, r.LowerRightCorner.Y-4,r.getCenter().X+2, r.LowerRightCorner.Y );
// top left
if (m == EGUIEDM_RESIZE_T || m == EGUIEDM_RESIZE_L || m == EGUIEDM_RESIZE_TL || m == EGUIEDM_MOVE )
driver->draw2DRectangle(video::SColor(100,255,255,255), TLRect);
if (m == EGUIEDM_RESIZE_T || m == EGUIEDM_RESIZE_R || m == EGUIEDM_RESIZE_TR || m == EGUIEDM_MOVE )
driver->draw2DRectangle(video::SColor(100,255,255,255), TRRect);
if (m == EGUIEDM_RESIZE_T || m == EGUIEDM_MOVE )
driver->draw2DRectangle(video::SColor(100,255,255,255), TopRect);
if (m == EGUIEDM_RESIZE_L || m == EGUIEDM_RESIZE_BL || m == EGUIEDM_RESIZE_B || m == EGUIEDM_MOVE )
driver->draw2DRectangle(video::SColor(100,255,255,255), BLRect);
if (m == EGUIEDM_RESIZE_L || m == EGUIEDM_MOVE )
driver->draw2DRectangle(video::SColor(100,255,255,255), LRect);
if (m == EGUIEDM_RESIZE_R || m == EGUIEDM_MOVE )
driver->draw2DRectangle(video::SColor(100,255,255,255), RRect);
if (m == EGUIEDM_RESIZE_R || m == EGUIEDM_RESIZE_BR || m == EGUIEDM_RESIZE_B || m == EGUIEDM_MOVE )
driver->draw2DRectangle(video::SColor(100,255,255,255), BRRect );
if (m == EGUIEDM_RESIZE_B || m == EGUIEDM_MOVE )
driver->draw2DRectangle(video::SColor(100,255,255,255), BRect);
}
IGUIElement::draw();
}
void CGUIEditWorkspace::setDrawGrid(bool drawGrid)
{
DrawGrid = drawGrid;
}
void CGUIEditWorkspace::setGridSize(const core::dimension2di& gridSize)
{
GridSize = gridSize;
if (GridSize.Width < 2)
GridSize.Width = 2;
if (GridSize.Height < 2)
GridSize.Height = 2;
}
void CGUIEditWorkspace::setUseGrid(bool useGrid)
{
UseGrid = useGrid;
}
//! Removes a child.
void CGUIEditWorkspace::removeChild(IGUIElement* child)
{
IGUIElement::removeChild(child);
if (Children.empty())
remove();
}
void CGUIEditWorkspace::updateAbsolutePosition()
{
core::rect<s32> parentRect(0,0,0,0);
if (Parent)
{
parentRect = Parent->getAbsolutePosition();
RelativeRect.UpperLeftCorner.X = 0;
RelativeRect.UpperLeftCorner.Y = 0;
RelativeRect.LowerRightCorner.X = parentRect.getWidth();
RelativeRect.LowerRightCorner.Y = parentRect.getHeight();
}
IGUIElement::updateAbsolutePosition();
}
void CGUIEditWorkspace::CopySelectedElementXML()
{
core::stringc XMLText;
core::stringw wXMLText;
// create memory write file
io::CMemoryReadWriteFile* memWrite = new io::CMemoryReadWriteFile("#Clipboard#");
// save gui to mem file
io::IXMLWriter* xml = Environment->getFileSystem()->createXMLWriter(memWrite);
Environment->writeGUIElement(xml, SelectedElement);
// copy to clipboard- wide chars not supported yet :(
wXMLText = (wchar_t*)&memWrite->getData()[0];
u32 i = memWrite->getData().size()/sizeof(wchar_t);
if (wXMLText.size() > i)
wXMLText[i] = L'\0';
XMLText = wXMLText.c_str();
memWrite->drop();
xml->drop();
Environment->getOSOperator()->copyToClipboard(XMLText.c_str());
}
void CGUIEditWorkspace::PasteXMLToSelectedElement()
{
// get clipboard data
core::stringc XMLText = Environment->getOSOperator()->getTextFromClipboard();
// convert to stringw
core::stringw wXMLText = XMLText.c_str();
io::CMemoryReadWriteFile* memWrite = new io::CMemoryReadWriteFile("#Clipboard#");
io::IXMLWriter* xmlw = Environment->getFileSystem()->createXMLWriter(memWrite);
xmlw->writeXMLHeader(); // it needs one of those
xmlw->drop();
// write clipboard data
memWrite->write((void*)&wXMLText[0], wXMLText.size() * sizeof(wchar_t));
// rewind file
memWrite->seek(0, false);
// read xml
Environment->loadGUI(memWrite, SelectedElement);
// reset focus
Environment->setFocus(this);
-
+
// drop the read file
memWrite->drop();
}
void CGUIEditWorkspace::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options)
{
out->addBool("DrawGrid", DrawGrid);
out->addBool("UseGrid", UseGrid);
out->addPosition2d("GridSize", core::position2di(GridSize.Width, GridSize.Height));
out->addInt("MenuCommandStart", MenuCommandStart);
}
void CGUIEditWorkspace::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
setDrawGrid(in->getAttributeAsBool("DrawGrid"));
setUseGrid(in->getAttributeAsBool("UseGrid"));
core::position2di tmpp = in->getAttributeAsPosition2d("GridSize");
core::dimension2di tmpd(tmpp.X, tmpp.Y);
setGridSize(tmpd);
setMenuCommandIDStart(in->getAttributeAsInt("MenuCommandStart"));
}
} // end namespace gui
} // end namespace irr
diff --git a/tools/GUIEditor/CGUITextureAttribute.h b/tools/GUIEditor/CGUITextureAttribute.h
index 54aade9..58ba17e 100644
--- a/tools/GUIEditor/CGUITextureAttribute.h
+++ b/tools/GUIEditor/CGUITextureAttribute.h
@@ -1,132 +1,136 @@
#ifndef __C_GUI_TEXTURE_ATTRIBUTE_H_INCLUDED__
#define __C_GUI_TEXTURE_ATTRIBUTE_H_INCLUDED__
#include "CGUIAttribute.h"
#include "IGUIEditBox.h"
#include "IGUIImage.h"
#include "IGUIButton.h"
namespace irr
{
namespace gui
{
class CGUITextureAttribute : public CGUIAttribute
{
public:
//
CGUITextureAttribute(IGUIEnvironment* environment, IGUIElement *parent, s32 myParentID) :
CGUIAttribute(environment, parent, myParentID),
AttribEditBox(0), AttribImage(0), AttribButton(0)
{
IGUISkin* skin = Environment->getSkin();
core::rect<s32> r = getAbsolutePosition();
s32 topy = skin->getFont()->getDimension(L"A").Height + 10;
s32 h = skin->getFont()->getDimension(L"A").Height + 5;
AttribImage = environment->addImage(0, core::position2di(0, topy), false, this);
AttribImage->setRelativePosition( core::rect<s32>(0,topy, r.getWidth() - 5, 100+topy));
AttribImage->grab();
AttribImage->setSubElement(true);
AttribImage->setScaleImage(true);
AttribImage->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
-
+
topy += 105;
core::rect<s32> r2(0, topy, r.getWidth() - 15 - skin->getSize(EGDS_CHECK_BOX_WIDTH), topy + h);
core::rect<s32> br(r.getWidth() - 10 - skin->getSize(EGDS_CHECK_BOX_WIDTH), topy, r.getWidth(), topy + h);
AttribEditBox = environment->addEditBox(0, r2, true, this, -1);
AttribEditBox->grab();
AttribEditBox->setSubElement(true);
AttribEditBox->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
AttribButton = environment->addButton(br, this, -1, L"...");
AttribButton->grab();
AttribButton->setSubElement(true);
AttribButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
//AttribButton->setSpriteBank(skin->getSpriteBank());
//AttribButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_FILE), skin->getColor(EGDC_WINDOW_SYMBOL));
//AttribButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_FILE), skin->getColor(EGDC_WINDOW_SYMBOL), true);
}
virtual ~CGUITextureAttribute()
{
if (AttribEditBox)
AttribEditBox->drop();
if (AttribImage)
AttribImage->drop();
if (AttribButton)
AttribButton->drop();
}
virtual bool OnEvent(const SEvent &e)
{
if (IsEnabled)
{
switch (e.EventType)
{
case EET_GUI_EVENT:
switch (e.GUIEvent.EventType)
{
case EGET_BUTTON_CLICKED:
// button click: open file dialog
if (e.GUIEvent.Caller == AttribButton)
{
//Environment->addGUIElement("textureBrowser", Environment->getRootGUIElement());
return true;
}
break;
case EGET_FILE_SELECTED:
// file selected: change editbox value and set event
-
+
return true;
case EGET_FILE_CHOOSE_DIALOG_CANCELLED:
return true;
+ default:
+ break;
}
break;
case EET_KEY_INPUT_EVENT:
return true;
+ default:
+ break;
}
}
return CGUIAttribute::OnEvent(e);
}
virtual void setAttrib(io::IAttributes *attribs, u32 attribIndex)
{
AttribEditBox->setText(attribs->getAttributeAsStringW(attribIndex).c_str());
AttribImage->setImage(attribs->getAttributeAsTexture(Index));
CGUIAttribute::setAttrib(attribs, attribIndex);
}
//! save the attribute and possibly post the event to its parent
virtual bool updateAttrib(bool sendEvent=true)
{
if (!Attribs)
return true;
Attribs->setAttribute(Index, AttribEditBox->getText());
core::stringw tmp = Attribs->getAttributeAsStringW(Index);
AttribEditBox->setText(Attribs->getAttributeAsStringW(Index).c_str());
AttribImage->setImage(Attribs->getAttributeAsTexture(Index));
return CGUIAttribute::updateAttrib(sendEvent);
}
//! this shoudln't be serialized, but this is included as it's an example
virtual const c8* getTypeName() const { return "texture_attribute"; }
private:
IGUIEditBox* AttribEditBox;
IGUIImage* AttribImage;
IGUIButton* AttribButton;
};
} // namespace gui
} // namespace irr
#endif
diff --git a/tools/GUIEditor/CGUITextureCacheBrowser.cpp b/tools/GUIEditor/CGUITextureCacheBrowser.cpp
index 4c930fd..f95e98b 100644
--- a/tools/GUIEditor/CGUITextureCacheBrowser.cpp
+++ b/tools/GUIEditor/CGUITextureCacheBrowser.cpp
@@ -1,332 +1,336 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt / Gaz Davidson
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CGUITextureCacheBrowser.h"
#include "IGUIEnvironment.h"
#include "IGUIButton.h"
#include "IGUISkin.h"
#include "IGUIFont.h"
#include "IVideoDriver.h"
namespace irr
{
namespace gui
{
-CGUITextureCacheBrowser::CGUITextureCacheBrowser(IGUIEnvironment* environment, s32 id, IGUIElement *parent)
+CGUITextureCacheBrowser::CGUITextureCacheBrowser(IGUIEnvironment* environment, s32 id, IGUIElement *parent)
: IGUIWindow(environment, parent, id, core::rect<s32>(0,0,300,200)),
CloseButton(0), Panel(0), SelectedTexture(-1), Dragging(false), IsDraggable(true)
{
#ifdef _DEBUG
setDebugName("CGUITextureCacheBrowser");
#endif
IGUISkin* skin = 0;
IGUISpriteBank* sprites = 0;
video::SColor color(255,255,255,255);
if (environment)
skin = environment->getSkin();
-
+
s32 buttonw = 15;
if (skin)
{
buttonw = skin->getSize(EGDS_WINDOW_BUTTON_WIDTH);
sprites = skin->getSpriteBank();
color = skin->getColor(EGDC_WINDOW_SYMBOL);
}
s32 posx = RelativeRect.getWidth() - buttonw - 4;
- CloseButton = Environment->addButton(core::rect<s32>(posx, 3, posx + buttonw, 3 + buttonw), this, -1,
+ CloseButton = Environment->addButton(core::rect<s32>(posx, 3, posx + buttonw, 3 + buttonw), this, -1,
L"", skin ? skin->getDefaultText(EGDT_WINDOW_CLOSE) : L"Close" );
CloseButton->setSubElement(true);
CloseButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
if (sprites)
{
CloseButton->setSpriteBank(sprites);
CloseButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_WINDOW_CLOSE), color);
CloseButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_WINDOW_CLOSE), color);
}
CloseButton->grab();
// window title
Text = L"Texture Browser";
// panel element
Panel = new CGUIPanel(environment, this);
Panel->setRelativePosition( core::rect<s32>(1, buttonw + 5, 151, RelativeRect.getHeight() - 1));
Panel->setAlignment(EGUIA_UPPERLEFT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT);
Panel->setBorder(true);
Panel->setSubElement(true);
// some buttons
-
+
// add images from texture cache
updateImageList();
}
CGUITextureCacheBrowser::~CGUITextureCacheBrowser()
{
if (CloseButton)
CloseButton->drop();
if (Panel)
Panel->drop();
-
+
// drop images
u32 i;
for (i=0; i<Images.size(); ++i)
{
Images[i]->drop();
Images[i]->remove();
}
Images.clear();
}
void CGUITextureCacheBrowser::updateImageList()
{
if (!Panel)
return;
video::IVideoDriver* Driver = Environment->getVideoDriver();
// clear images
u32 i;
for (i=0; i<Images.size(); ++i)
{
Images[i]->drop();
Images[i]->remove();
}
Images.clear();
u32 count = (u32)Driver->getTextureCount();
s32 h = Panel->getClientArea().getWidth()-10;
s32 hw = h/2;
- core::rect<s32> pos(Panel->getClientArea().getCenter().X - Panel->getAbsolutePosition().UpperLeftCorner.X - hw, 5,
+ core::rect<s32> pos(Panel->getClientArea().getCenter().X - Panel->getAbsolutePosition().UpperLeftCorner.X - hw, 5,
Panel->getClientArea().getCenter().X - Panel->getAbsolutePosition().UpperLeftCorner.X + hw, h+5);
core::position2di moveDist(0, h+5);
for (u32 i=0; i<count; ++i)
{
core::stringw details;
video::ITexture* tex = Driver->getTextureByIndex(i);
details = L"File name: ";
details += tex->getName();
details += L"\nFormat: ";
video::ECOLOR_FORMAT cf = tex->getColorFormat();
bool alpha = false;
switch (cf)
{
case video::ECF_A1R5G5B5:
details += L"A1R5G5B5 (16-bit with 1-bit alpha channel)\n";
alpha = true;
break;
case video::ECF_R5G6B5:
details += L"R5G6B5 (16-bit, no alpha channel)\n";
break;
case video::ECF_R8G8B8:
details += L"R8G8B8 (16-bit, no alpha channel)\n";
break;
case video::ECF_A8R8G8B8:
details += L"R8G8B8 (32-bit with 8-bit alpha channel)\n";
alpha = true;
break;
default:
details += L"Unknown\n";
}
core::dimension2du osize = tex->getOriginalSize();
core::dimension2du size = tex->getOriginalSize();
details += "Size: ";
details += size.Width;
details += "x";
details += size.Height;
if (osize != size)
{
details += "\nOriginal Size: ";
details += osize.Width;
details += "x";
details += osize.Height;
}
details += L"\nMip-maps: ";
if (tex->hasMipMaps())
details += L"Yes\n";
else
details += L"No\n";
IGUIImage* img = Environment->addImage(tex, core::position2di(1,1), alpha, Panel, i);
img->grab();
Images.push_back(img);
img->setRelativePosition(pos);
img->setToolTipText(details.c_str());
img->setScaleImage(true);
img->setColor( SelectedTexture == (s32)i ? video::SColor(255,255,255,255) : video::SColor(128,128,128,128) );
pos = pos + moveDist;
}
}
void CGUITextureCacheBrowser::updateAbsolutePosition()
{
IGUIWindow::updateAbsolutePosition();
updateImageList();
}
//! called if an event happened.
bool CGUITextureCacheBrowser::OnEvent(const SEvent &event)
{
switch(event.EventType)
{
case EET_GUI_EVENT:
if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST)
{
if (event.GUIEvent.Caller == (IGUIElement*)this)
Dragging = false;
return true;
}
else
if (event.GUIEvent.EventType == EGET_BUTTON_CLICKED)
{
if (event.GUIEvent.Caller == CloseButton)
{
remove();
return true;
}
}
break;
case EET_MOUSE_INPUT_EVENT:
switch(event.MouseInput.Event)
{
case EMIE_LMOUSE_PRESSED_DOWN:
DragStart.X = event.MouseInput.X;
DragStart.Y = event.MouseInput.Y;
if (getElementFromPoint(DragStart) == this)
{
if (!Environment->hasFocus(this))
{
Dragging = IsDraggable;
//Environment->setFocus(this);
if (Parent)
Parent->bringToFront(this);
}
return true;
}
else
{
if (Panel->getAbsolutePosition().isPointInside(DragStart))
{
// select an image
IGUIElement* el = Panel->getElementFromPoint(DragStart);
if (el && el != Panel)
{
if (el->getType() == EGUIET_IMAGE)
{
setSelected(el->getID());
}
}
else
{
setSelected();
}
}
}
break;
case EMIE_LMOUSE_LEFT_UP:
Dragging = false;
//Environment->removeFocus(this);
return true;
case EMIE_MOUSE_MOVED:
if (Dragging)
{
// gui window should not be dragged outside its parent
if (Parent)
if (event.MouseInput.X < Parent->getAbsolutePosition().UpperLeftCorner.X +1 ||
event.MouseInput.Y < Parent->getAbsolutePosition().UpperLeftCorner.Y +1 ||
event.MouseInput.X > Parent->getAbsolutePosition().LowerRightCorner.X -1 ||
event.MouseInput.Y > Parent->getAbsolutePosition().LowerRightCorner.Y -1)
return true;
-
+
move(core::position2d<s32>(event.MouseInput.X - DragStart.X, event.MouseInput.Y - DragStart.Y));
DragStart.X = event.MouseInput.X;
DragStart.Y = event.MouseInput.Y;
return true;
}
break;
+ default:
+ break;
}
+ default:
+ break;
}
return Parent ? Parent->OnEvent(event) : false;
}
void CGUITextureCacheBrowser::setSelected(s32 index)
{
SelectedTexture = index;
updateImageList();
printf("Texture %d selected\n", index);
}
void CGUITextureCacheBrowser::draw()
{
if (!IsVisible)
return;
IGUISkin* skin = Environment->getSkin();
core::rect<s32> rect = AbsoluteRect;
core::rect<s32> *cl = &AbsoluteClippingRect;
// draw body fast
rect = skin->draw3DWindowBackground(this, true, skin->getColor(EGDC_ACTIVE_BORDER),
AbsoluteRect, &AbsoluteClippingRect);
// draw window text
if (Text.size())
{
rect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X);
rect.UpperLeftCorner.Y += skin->getSize(EGDS_TEXT_DISTANCE_Y);
rect.LowerRightCorner.X -= skin->getSize(EGDS_WINDOW_BUTTON_WIDTH) + 5;
IGUIFont* font = skin->getFont();
if (font)
font->draw(Text.c_str(), rect, skin->getColor(EGDC_ACTIVE_CAPTION), false, true, cl);
}
IGUIElement::draw();
}
bool CGUITextureCacheBrowser::isDraggable() const
{
return IsDraggable;
}
void CGUITextureCacheBrowser::setDraggable(bool draggable)
{
IsDraggable = draggable;
if (Dragging && !IsDraggable)
Dragging = false;
}
//! Returns the rectangle of the drawable area (without border, without titlebar and without scrollbars)
core::rect<s32> CGUITextureCacheBrowser::getClientRect() const
{
return core::recti();
}
} // namespace gui
} // namespace irr
|
paupawsan/Irrlicht
|
eb28a4ac862d03e97c7bb5d56d48bcd95336249f
|
Make sure all compiled files are found under a common directory.
|
diff --git a/source/Irrlicht/Irrlicht9.0.vcproj b/source/Irrlicht/Irrlicht9.0.vcproj
index 76d71d1..a505d3c 100644
--- a/source/Irrlicht/Irrlicht9.0.vcproj
+++ b/source/Irrlicht/Irrlicht9.0.vcproj
@@ -1,1093 +1,1093 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="Irrlicht"
ProjectGUID="{E08E042A-6C45-411B-92BE-3CC31331019F}"
RootNamespace="Irrlicht"
TargetFrameworkVersion="131072"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
- OutputDirectory="..\obj\IrrDebug"
- IntermediateDirectory="..\obj\IrrDebug"
+ OutputDirectory="obj\$(ConfigurationName)"
+ IntermediateDirectory="obj\$(ConfigurationName)"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="0"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="_DEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\..\Debug/Irrlicht.tlb"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="..\..\include;zlib"
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;IRRLICHT_EXPORTS;_CRT_SECURE_NO_DEPRECATE"
ExceptionHandling="0"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
DisableLanguageExtensions="false"
RuntimeTypeInfo="false"
PrecompiledHeaderFile=".\..\obj\IrrDebug/Irrlicht.pch"
AssemblerListingLocation=".\..\obj\IrrDebug/"
ObjectFile=".\..\obj\IrrDebug/"
ProgramDataBaseFileName=".\..\obj\IrrDebug/"
WarningLevel="3"
SuppressStartupBanner="true"
DebugInformationFormat="3"
CompileAs="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="_DEBUG"
Culture="3079"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
UseLibraryDependencyInputs="true"
AdditionalOptions="/MACHINE:I386"
AdditionalDependencies="kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib opengl32.lib winmm.lib"
OutputFile="..\..\bin\Win32-visualstudio\Irrlicht.dll"
LinkIncremental="2"
SuppressStartupBanner="true"
AdditionalLibraryDirectories=""
IgnoreDefaultLibraryNames="libci.lib"
GenerateDebugInformation="true"
ProgramDatabaseFile="..\obj\IrrDebug\Irrlicht.pdb"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
ImportLibrary="..\..\lib\Win32-visualstudio\Irrlicht.lib"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
- OutputDirectory="obj\IrrRelease"
- IntermediateDirectory="obj\IrrRelease"
+ OutputDirectory="obj\$(ConfigurationName)"
+ IntermediateDirectory="obj\$(ConfigurationName)"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="NDEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\..\Release/Irrlicht.tlb"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
InlineFunctionExpansion="1"
EnableIntrinsicFunctions="false"
AdditionalIncludeDirectories="..\..\include;zlib"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;IRRLICHT_EXPORTS;_CRT_SECURE_NO_DEPRECATE"
StringPooling="true"
ExceptionHandling="0"
RuntimeLibrary="0"
BufferSecurityCheck="false"
EnableFunctionLevelLinking="true"
PrecompiledHeaderFile=".\..\obj\IrrRelease/Irrlicht.pch"
AssemblerListingLocation=".\..\obj\IrrRelease/"
ObjectFile=".\..\obj\IrrRelease/"
ProgramDataBaseFileName=".\..\obj\IrrRelease/"
WarningLevel="3"
SuppressStartupBanner="true"
DebugInformationFormat="0"
CompileAs="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG"
Culture="3079"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalOptions="/MACHINE:I386"
AdditionalDependencies="kernel32.lib user32.lib gdi32.lib opengl32.lib winmm.lib"
OutputFile="..\..\bin\Win32-visualstudio\Irrlicht.dll"
LinkIncremental="1"
SuppressStartupBanner="true"
IgnoreDefaultLibraryNames="libci.lib"
GenerateDebugInformation="false"
ProgramDatabaseFile="..\obj\IrrRelease\Irrlicht.pdb"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
ImportLibrary="..\..\lib\Win32-visualstudio\Irrlicht.lib"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release - Fast FPU|Win32"
- OutputDirectory="$(ConfigurationName)"
- IntermediateDirectory="$(ConfigurationName)"
+ OutputDirectory="obj\$(ConfigurationName)"
+ IntermediateDirectory="obj\$(ConfigurationName)"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="NDEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\..\Release/Irrlicht.tlb"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
AdditionalIncludeDirectories="..\..\include;zlib"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;IRRLICHT_EXPORTS;_CRT_SECURE_NO_DEPRECATE"
StringPooling="true"
ExceptionHandling="0"
RuntimeLibrary="0"
BufferSecurityCheck="false"
EnableFunctionLevelLinking="true"
EnableEnhancedInstructionSet="2"
FloatingPointModel="2"
RuntimeTypeInfo="false"
PrecompiledHeaderFile=".\..\obj\IrrRelease/Irrlicht.pch"
AssemblerListingLocation=".\..\obj\IrrReleaseFastFPU/"
ObjectFile=".\..\obj\IrrReleaseFastFPU/"
ProgramDataBaseFileName=".\..\obj\IrrReleaseFastFPU/"
WarningLevel="3"
WarnAsError="false"
SuppressStartupBanner="true"
DebugInformationFormat="0"
CallingConvention="1"
CompileAs="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG"
Culture="3079"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalOptions="/MACHINE:I386"
AdditionalDependencies="kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib opengl32.lib winmm.lib"
OutputFile="..\..\bin\Win32-visualstudio\Irrlicht.dll"
LinkIncremental="1"
SuppressStartupBanner="true"
IgnoreDefaultLibraryNames="libci.lib"
GenerateDebugInformation="false"
ProgramDatabaseFile="..\obj\IrrRelease\Irrlicht.pdb"
SubSystem="2"
OptimizeReferences="2"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
ImportLibrary="..\..\lib\Win32-visualstudio\Irrlicht.lib"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Static lib - Debug|Win32"
- OutputDirectory="$(ConfigurationName)"
- IntermediateDirectory="$(ConfigurationName)"
+ OutputDirectory="obj\$(ConfigurationName)"
+ IntermediateDirectory="obj\$(ConfigurationName)"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="0"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="_DEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\..\Debug/Irrlicht.tlb"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="..\..\include;zlib"
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;_IRR_STATIC_LIB_;_CRT_SECURE_NO_DEPRECATE"
ExceptionHandling="0"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
DisableLanguageExtensions="false"
RuntimeTypeInfo="false"
PrecompiledHeaderFile=".\..\obj\IrrDebug/Irrlicht.pch"
AssemblerListingLocation=".\..\obj\IrrDebugStatic/"
ObjectFile=".\..\obj\IrrDebugStatic/"
ProgramDataBaseFileName=".\..\obj\IrrDebugStatic/"
WarningLevel="3"
SuppressStartupBanner="true"
DebugInformationFormat="3"
CompileAs="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="_DEBUG"
Culture="3079"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
AdditionalDependencies="winmm.lib"
OutputFile="..\..\lib\Win32-visualstudio\Irrlicht.lib"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Static lib - Release|Win32"
- OutputDirectory="$(ConfigurationName)"
- IntermediateDirectory="$(ConfigurationName)"
+ OutputDirectory="obj\$(ConfigurationName)"
+ IntermediateDirectory="obj\$(ConfigurationName)"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="NDEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\..\Release/Irrlicht.tlb"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
InlineFunctionExpansion="1"
EnableIntrinsicFunctions="false"
AdditionalIncludeDirectories="..\..\include;zlib"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;_IRR_STATIC_LIB_;_CRT_SECURE_NO_DEPRECATE"
StringPooling="true"
ExceptionHandling="0"
RuntimeLibrary="0"
BufferSecurityCheck="false"
EnableFunctionLevelLinking="true"
PrecompiledHeaderFile=".\..\obj\IrrRelease/Irrlicht.pch"
AssemblerListingLocation=".\..\obj\IrrReleaseStatic/"
ObjectFile=".\..\obj\IrrReleaseStatic/"
ProgramDataBaseFileName=".\..\obj\IrrReleaseStatic/"
WarningLevel="3"
SuppressStartupBanner="true"
DebugInformationFormat="0"
CompileAs="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG"
Culture="3079"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
AdditionalDependencies="winmm.lib"
OutputFile="..\..\lib\Win32-visualstudio\Irrlicht.lib"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Static lib - Release - Fast FPU|Win32"
- OutputDirectory="$(ConfigurationName)"
- IntermediateDirectory="$(ConfigurationName)"
+ OutputDirectory="obj\$(ConfigurationName)"
+ IntermediateDirectory="obj\$(ConfigurationName)"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="NDEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\..\Release/Irrlicht.tlb"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="0"
OmitFramePointers="true"
AdditionalIncludeDirectories="..\..\include;zlib"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;_IRR_STATIC_LIB_;_CRT_SECURE_NO_DEPRECATE"
StringPooling="true"
ExceptionHandling="0"
RuntimeLibrary="0"
BufferSecurityCheck="false"
EnableFunctionLevelLinking="true"
FloatingPointModel="2"
RuntimeTypeInfo="false"
PrecompiledHeaderFile=".\..\obj\IrrRelease/Irrlicht.pch"
AssemblerListingLocation=".\..\obj\IrrReleaseFastFPUStatic/"
ObjectFile=".\..\obj\IrrReleaseFastFPUStatic/"
ProgramDataBaseFileName=".\..\obj\IrrReleaseFastFPUStatic/"
WarningLevel="3"
SuppressStartupBanner="true"
DebugInformationFormat="0"
CallingConvention="1"
CompileAs="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG"
Culture="3079"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
AdditionalDependencies="winmm.lib"
OutputFile="..\..\lib\Win32-visualstudio\Irrlicht.lib"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="SDL-Debug|Win32"
- OutputDirectory="$(ConfigurationName)"
- IntermediateDirectory="$(ConfigurationName)"
+ OutputDirectory="obj\$(ConfigurationName)"
+ IntermediateDirectory="obj\$(ConfigurationName)"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="0"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="_DEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\..\Debug/Irrlicht.tlb"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="..\..\include;zlib"
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;IRRLICHT_EXPORTS;_CRT_SECURE_NO_DEPRECATE;_IRR_USE_SDL_DEVICE_=1"
ExceptionHandling="0"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
DisableLanguageExtensions="false"
RuntimeTypeInfo="false"
PrecompiledHeaderFile=".\..\obj\IrrDebug/Irrlicht.pch"
AssemblerListingLocation=".\..\obj\IrrDebug/"
ObjectFile=".\..\obj\IrrDebug/"
ProgramDataBaseFileName=".\..\obj\IrrDebug/"
WarningLevel="3"
SuppressStartupBanner="true"
DebugInformationFormat="3"
CompileAs="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="_DEBUG"
Culture="3079"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
UseLibraryDependencyInputs="true"
AdditionalOptions="/MACHINE:I386"
AdditionalDependencies="kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib opengl32.lib winmm.lib"
OutputFile="..\..\bin\Win32-visualstudio\Irrlicht.dll"
LinkIncremental="2"
SuppressStartupBanner="true"
AdditionalLibraryDirectories=""
IgnoreDefaultLibraryNames="libci.lib"
GenerateDebugInformation="true"
ProgramDatabaseFile="..\obj\IrrDebug\Irrlicht.pdb"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
ImportLibrary="..\..\lib\Win32-visualstudio\Irrlicht.lib"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="include"
>
<File
RelativePath="..\..\include\IEventReceiver.h"
>
</File>
<File
RelativePath="..\..\include\ILogger.h"
>
</File>
<File
RelativePath="..\..\include\IOSOperator.h"
>
</File>
<File
RelativePath="..\..\include\IReferenceCounted.h"
>
</File>
<File
RelativePath="..\..\include\IrrCompileConfig.h"
>
</File>
<File
RelativePath="..\..\include\irrlicht.h"
>
</File>
<File
RelativePath="..\..\include\IrrlichtDevice.h"
>
</File>
<File
RelativePath="..\..\include\irrTypes.h"
>
</File>
<File
RelativePath="..\..\include\ITimer.h"
>
</File>
<File
RelativePath="..\..\include\Keycodes.h"
>
</File>
<File
RelativePath="..\..\include\SIrrCreationParameters.h"
>
</File>
<File
RelativePath="..\..\include\SKeyMap.h"
>
</File>
<Filter
Name="video"
>
<File
RelativePath="..\..\include\EDriverTypes.h"
>
</File>
<File
RelativePath="..\..\include\IGeometryCreator.h"
>
</File>
<File
RelativePath="..\..\include\IGPUProgrammingServices.h"
>
</File>
<File
RelativePath="..\..\include\IImage.h"
>
</File>
<File
RelativePath="..\..\include\IImageLoader.h"
>
</File>
<File
RelativePath="..\..\include\IMaterialRenderer.h"
>
</File>
<File
RelativePath="..\..\include\IMaterialRendererServices.h"
>
</File>
<File
RelativePath="..\..\include\IShaderConstantSetCallBack.h"
>
</File>
<File
RelativePath="..\..\include\ITexture.h"
>
</File>
<File
RelativePath="..\..\include\IVideoDriver.h"
>
</File>
<File
RelativePath="..\..\include\IVideoModeList.h"
>
</File>
<File
RelativePath="..\..\include\S3DVertex.h"
>
</File>
<File
RelativePath="..\..\include\SColor.h"
>
</File>
<File
RelativePath="..\..\include\SExposedVideoData.h"
>
</File>
<File
RelativePath="..\..\include\SLight.h"
>
</File>
<File
RelativePath="..\..\include\SMaterial.h"
>
</File>
<File
RelativePath="..\..\include\SMaterialLayer.h"
>
</File>
</Filter>
<Filter
Name="core"
>
<File
RelativePath="..\..\include\aabbox3d.h"
>
</File>
<File
RelativePath="..\..\include\coreutil.h"
>
</File>
<File
RelativePath="..\..\include\dimension2d.h"
>
</File>
<File
RelativePath="..\..\include\heapsort.h"
>
</File>
<File
RelativePath="..\..\include\irrAllocator.h"
>
</File>
<File
RelativePath="..\..\include\irrArray.h"
>
</File>
<File
RelativePath="..\..\include\irrList.h"
>
</File>
<File
RelativePath="..\..\include\irrMap.h"
>
</File>
<File
RelativePath="..\..\include\irrMath.h"
>
</File>
<File
RelativePath="..\..\include\irrString.h"
>
</File>
<File
RelativePath="..\..\include\line2d.h"
>
</File>
<File
RelativePath="..\..\include\line3d.h"
>
</File>
<File
RelativePath="..\..\include\matrix4.h"
>
</File>
<File
RelativePath="..\..\include\plane3d.h"
>
</File>
<File
RelativePath="..\..\include\position2d.h"
>
</File>
<File
RelativePath="..\..\include\quaternion.h"
>
</File>
<File
RelativePath="..\..\include\rect.h"
>
</File>
<File
RelativePath="..\..\include\triangle3d.h"
>
</File>
<File
RelativePath="..\..\include\vector2d.h"
>
</File>
<File
RelativePath="..\..\include\vector3d.h"
>
</File>
</Filter>
<Filter
Name="io"
>
<File
RelativePath="..\..\include\EAttributes.h"
>
</File>
<File
RelativePath="..\..\include\IAttributeExchangingObject.h"
>
</File>
<File
RelativePath="..\..\include\IAttributes.h"
>
</File>
<File
RelativePath="..\..\include\IFileList.h"
>
</File>
<File
RelativePath="..\..\include\IFileSystem.h"
>
</File>
<File
RelativePath="..\..\include\IReadFile.h"
>
</File>
<File
RelativePath="..\..\include\irrXML.h"
>
</File>
<File
RelativePath="..\..\include\IWriteFile.h"
>
</File>
<File
RelativePath="..\..\include\IXMLReader.h"
>
</File>
<File
RelativePath="..\..\include\IXMLWriter.h"
>
</File>
<File
RelativePath="..\..\include\path.h"
>
</File>
</Filter>
<Filter
Name="scene"
>
<File
RelativePath="..\..\include\CDynamicMeshBuffer.h"
>
</File>
<File
RelativePath="..\..\include\CIndexBuffer.h"
>
</File>
<File
RelativePath="..\..\include\CMeshBuffer.h"
>
</File>
<File
RelativePath="..\..\include\CVertexBuffer.h"
>
</File>
<File
RelativePath="..\..\include\ECullingTypes.h"
>
</File>
<File
RelativePath="..\..\include\EDebugSceneTypes.h"
>
</File>
<File
RelativePath="..\..\include\EMeshWriterEnums.h"
>
</File>
<File
RelativePath="..\..\include\EPrimitiveTypes.h"
>
</File>
<File
RelativePath="..\..\include\ESceneNodeAnimatorTypes.h"
>
</File>
<File
RelativePath="..\..\include\ESceneNodeTypes.h"
>
</File>
<File
RelativePath="..\..\include\IAnimatedMesh.h"
>
</File>
<File
RelativePath="..\..\include\IAnimatedMeshMD2.h"
>
</File>
<File
RelativePath="..\..\include\IAnimatedMeshMS3D.h"
>
</File>
<File
RelativePath="..\..\include\IAnimatedMeshSceneNode.h"
>
</File>
<File
RelativePath="..\..\include\IBillboardSceneNode.h"
>
</File>
<File
RelativePath="..\..\include\ICameraSceneNode.h"
>
</File>
<File
RelativePath="..\..\include\IDummyTransformationSceneNode.h"
>
</File>
<File
RelativePath="..\..\include\ILightSceneNode.h"
>
</File>
<File
RelativePath="..\..\include\IMesh.h"
>
</File>
<File
RelativePath="..\..\include\IMeshBuffer.h"
>
</File>
<File
RelativePath="..\..\include\IMeshCache.h"
>
</File>
<File
RelativePath="..\..\include\IMeshLoader.h"
>
</File>
<File
RelativePath="..\..\include\IMeshManipulator.h"
>
</File>
<File
RelativePath="..\..\include\IMeshSceneNode.h"
>
</File>
<File
RelativePath="..\..\include\IMeshWriter.h"
>
</File>
<File
RelativePath="..\..\include\IMetaTriangleSelector.h"
>
</File>
<File
RelativePath="..\..\include\IParticleAffector.h"
>
</File>
<File
RelativePath="..\..\include\IParticleAnimatedMeshSceneNodeEmitter.h"
>
</File>
<File
RelativePath="..\..\include\IParticleAttractionAffector.h"
>
</File>
<File
RelativePath="..\..\include\IParticleBoxEmitter.h"
>
</File>
<File
RelativePath="..\..\include\IParticleCylinderEmitter.h"
>
</File>
<File
RelativePath="..\..\include\IParticleEmitter.h"
>
</File>
<File
RelativePath="..\..\include\IParticleFadeOutAffector.h"
>
</File>
<File
RelativePath="..\..\include\IParticleGravityAffector.h"
>
</File>
<File
RelativePath="..\..\include\IParticleMeshEmitter.h"
>
</File>
<File
RelativePath="..\..\include\IParticleRingEmitter.h"
>
</File>
<File
RelativePath="..\..\include\IParticleRotationAffector.h"
>
</File>
<File
RelativePath="..\..\include\IParticleSphereEmitter.h"
>
</File>
<File
RelativePath="..\..\include\IParticleSystemSceneNode.h"
>
</File>
|
paupawsan/Irrlicht
|
be90a888cb8b833a2f1946c4a67c66d7ff0e3ee2
|
Fix settings and interpretation of flags for SConstruct file.
|
diff --git a/source/Irrlicht/SConstruct b/source/Irrlicht/SConstruct
index 491e7d1..4ed3277 100644
--- a/source/Irrlicht/SConstruct
+++ b/source/Irrlicht/SConstruct
@@ -1,102 +1,102 @@
import os
import sys
USE_GCC = 1;
NDEBUG = 1;
-PROFILE = 1;
+PROFILE = 0;
APPLICATION_NAME = 'Irrlicht';
LIBRARIES = ['gdi32', 'opengl32', 'd3dx9d', 'winmm'];
if USE_GCC==1 and PROFILE==1:
LIBRARIES += ['gmon'];
CXXINCS = ['../../include/', 'zlib/', 'jpeglib/', 'libpng/'];
if USE_GCC==0:
env = Environment(ENV = {
'PATH': os.environ['PATH']
}, CPPPATH=CXXINCS);
else:
env = Environment(ENV = {
'PATH': os.environ['PATH']
}, tools = ['mingw'], CPPPATH=CXXINCS);
IRRMESHLOADER = ['CBSPMeshFileLoader.cpp', 'CMD2MeshFileLoader.cpp', 'CMD3MeshFileLoader.cpp', 'CMS3DMeshFileLoader.cpp', 'CB3DMeshFileLoader.cpp', 'C3DSMeshFileLoader.cpp', 'COgreMeshFileLoader.cpp', 'COBJMeshFileLoader.cpp', 'CColladaFileLoader.cpp', 'CCSMLoader.cpp', 'CDMFLoader.cpp', 'CLMTSMeshFileLoader.cpp', 'CMY3DMeshFileLoader.cpp', 'COCTLoader.cpp', 'CXMeshFileLoader.cpp', 'CIrrMeshFileLoader.cpp', 'CSTLMeshFileLoader.cpp', 'CLWOMeshFileLoader.cpp'];
IRRMESHWRITER = ['CColladaMeshWriter.cpp', 'CIrrMeshWriter.cpp', 'COBJMeshWriter.cpp', 'CSTLMeshWriter.cpp'];
IRRMESHOBJ = IRRMESHLOADER + IRRMESHWRITER + ['CSkinnedMesh.cpp', 'CBoneSceneNode.cpp', 'CMeshSceneNode.cpp', 'CAnimatedMeshSceneNode.cpp', 'CAnimatedMeshMD2.cpp', 'CAnimatedMeshMD3.cpp', 'CQ3LevelMesh.cpp', 'CQuake3ShaderSceneNode.cpp'];
IRROBJ = ['CBillboardSceneNode.cpp', 'CCameraSceneNode.cpp', 'CDummyTransformationSceneNode.cpp', 'CEmptySceneNode.cpp', 'CGeometryCreator.cpp', 'CLightSceneNode.cpp', 'CMeshManipulator.cpp', 'CMetaTriangleSelector.cpp', 'COctTreeSceneNode.cpp', 'COctTreeTriangleSelector.cpp', 'CSceneCollisionManager.cpp', 'CSceneManager.cpp', 'CShadowVolumeSceneNode.cpp', 'CSkyBoxSceneNode.cpp', 'CSkyDomeSceneNode.cpp', 'CTerrainSceneNode.cpp', 'CTerrainTriangleSelector.cpp', 'CVolumeLightSceneNode.cpp', 'CCubeSceneNode.cpp', 'CSphereSceneNode.cpp', 'CTextSceneNode.cpp', 'CTriangleBBSelector.cpp', 'CTriangleSelector.cpp', 'CWaterSurfaceSceneNode.cpp', 'CMeshCache.cpp', 'CDefaultSceneNodeAnimatorFactory.cpp', 'CDefaultSceneNodeFactory.cpp'];
IRRPARTICLEOBJ = ['CParticleAnimatedMeshSceneNodeEmitter.cpp', 'CParticleBoxEmitter.cpp', 'CParticleCylinderEmitter.cpp', 'CParticleMeshEmitter.cpp', 'CParticlePointEmitter.cpp', 'CParticleRingEmitter.cpp', 'CParticleSphereEmitter.cpp', 'CParticleAttractionAffector.cpp', 'CParticleFadeOutAffector.cpp', 'CParticleGravityAffector.cpp', 'CParticleRotationAffector.cpp', 'CParticleSystemSceneNode.cpp', 'CParticleScaleAffector.cpp'];
IRRANIMOBJ = ['CSceneNodeAnimatorCameraFPS.cpp', 'CSceneNodeAnimatorCameraMaya.cpp', 'CSceneNodeAnimatorCollisionResponse.cpp', 'CSceneNodeAnimatorDelete.cpp', 'CSceneNodeAnimatorFlyCircle.cpp', 'CSceneNodeAnimatorFlyStraight.cpp', 'CSceneNodeAnimatorFollowSpline.cpp', 'CSceneNodeAnimatorRotation.cpp', 'CSceneNodeAnimatorTexture.cpp'];
IRRDRVROBJ = ['CNullDriver.cpp', 'COpenGLDriver.cpp', 'COpenGLNormalMapRenderer.cpp', 'COpenGLParallaxMapRenderer.cpp', 'COpenGLShaderMaterialRenderer.cpp', 'COpenGLTexture.cpp', 'COpenGLSLMaterialRenderer.cpp', 'COpenGLExtensionHandler.cpp', 'CD3D8Driver.cpp', 'CD3D8NormalMapRenderer.cpp', 'CD3D8ParallaxMapRenderer.cpp', 'CD3D8ShaderMaterialRenderer.cpp', 'CD3D8Texture.cpp', 'CD3D9Driver.cpp', 'CD3D9HLSLMaterialRenderer.cpp', 'CD3D9NormalMapRenderer.cpp', 'CD3D9ParallaxMapRenderer.cpp', 'CD3D9ShaderMaterialRenderer.cpp', 'CD3D9Texture.cpp'];
IRRIMAGEOBJ = ['CColorConverter.cpp', 'CImage.cpp', 'CImageLoaderBMP.cpp', 'CImageLoaderJPG.cpp', 'CImageLoaderPCX.cpp', 'CImageLoaderPNG.cpp', 'CImageLoaderPSD.cpp', 'CImageLoaderTGA.cpp', 'CImageLoaderPPM.cpp', 'CImageLoaderWAL.cpp', 'CImageWriterBMP.cpp', 'CImageWriterJPG.cpp', 'CImageWriterPCX.cpp', 'CImageWriterPNG.cpp', 'CImageWriterPPM.cpp', 'CImageWriterPSD.cpp', 'CImageWriterTGA.cpp'];
IRRVIDEOOBJ = ['CVideoModeList.cpp', 'CFPSCounter.cpp'] + IRRDRVROBJ + IRRIMAGEOBJ;
IRRSWRENDEROBJ = ['CSoftwareDriver.cpp', 'CSoftwareTexture.cpp', 'CTRFlat.cpp', 'CTRFlatWire.cpp', 'CTRGouraud.cpp', 'CTRGouraudWire.cpp', 'CTRTextureFlat.cpp', 'CTRTextureFlatWire.cpp', 'CTRTextureGouraud.cpp', 'CTRTextureGouraudAdd.cpp', 'CTRTextureGouraudNoZ.cpp', 'CTRTextureGouraudWire.cpp', 'CZBuffer.cpp', 'CTRTextureGouraudVertexAlpha2.cpp', 'CTRTextureGouraudNoZ2.cpp', 'CTRTextureLightMap2_M2.cpp', 'CTRTextureLightMap2_M4.cpp', 'CTRTextureLightMap2_M1.cpp', 'CSoftwareDriver2.cpp', 'CSoftwareTexture2.cpp', 'CTRTextureGouraud2.cpp', 'CTRGouraud2.cpp', 'CTRGouraudAlpha2.cpp', 'CTRGouraudAlphaNoZ2.cpp', 'CTRTextureDetailMap2.cpp', 'CTRTextureGouraudAdd2.cpp', 'CTRTextureGouraudAddNoZ2.cpp', 'CTRTextureWire2.cpp', 'CTRTextureLightMap2_Add.cpp', 'CTRTextureLightMapGouraud2_M4.cpp', 'IBurningShader.cpp', 'CTRTextureBlend.cpp', 'CTRTextureGouraudAlpha.cpp', 'CTRTextureGouraudAlphaNoZ.cpp', 'CDepthBuffer.cpp', 'CBurningShader_Raster_Reference.cpp'];
IRRIOOBJ = ['CFileList.cpp', 'CFileSystem.cpp', 'CLimitReadFile.cpp', 'CMemoryReadFile.cpp', 'CReadFile.cpp', 'CWriteFile.cpp', 'CXMLReader.cpp', 'CXMLWriter.cpp', 'CZipReader.cpp', 'CPakReader.cpp', 'CNPKReader.cpp', 'irrXML.cpp', 'CAttributes.cpp', 'lzma/LzmaDec.c'];
IRROTHEROBJ = ['CIrrDeviceSDL.cpp', 'CIrrDeviceLinux.cpp', 'CIrrDeviceStub.cpp', 'CIrrDeviceWin32.cpp', 'CLogger.cpp', 'COSOperator.cpp', 'Irrlicht.cpp', 'os.cpp'];
IRRGUIOBJ = ['CGUIButton.cpp', 'CGUICheckBox.cpp', 'CGUIComboBox.cpp', 'CGUIContextMenu.cpp', 'CGUIEditBox.cpp', 'CGUIEnvironment.cpp', 'CGUIFileOpenDialog.cpp', 'CGUIFont.cpp', 'CGUIImage.cpp', 'CGUIInOutFader.cpp', 'CGUIListBox.cpp', 'CGUIMenu.cpp', 'CGUIMeshViewer.cpp', 'CGUIMessageBox.cpp', 'CGUIModalScreen.cpp', 'CGUIScrollBar.cpp', 'CGUISpinBox.cpp', 'CGUISkin.cpp', 'CGUIStaticText.cpp', 'CGUITabControl.cpp', 'CGUITable.cpp', 'CGUIToolBar.cpp', 'CGUIWindow.cpp', 'CGUIColorSelectDialog.cpp', 'CDefaultGUIElementFactory.cpp', 'CGUISpriteBank.cpp'];
ZLIB_PREFIX = 'zlib/';
ZLIBNAMES = ['adler32.c', 'compress.c', 'crc32.c', 'deflate.c', 'inffast.c', 'inflate.c', 'inftrees.c', 'trees.c', 'uncompr.c', 'zutil.c'];
ZLIBOBJ = [];
for fileName in ZLIBNAMES:
ZLIBOBJ += [ZLIB_PREFIX + fileName];
JPEGLIB_PREFIX = 'jpeglib/';
JPEGLIBNAMES = ['jaricom.c', 'jcapimin.c', 'jcapistd.c', 'jcarith.c', 'jccoefct.c', 'jccolor.c', 'jcdctmgr.c', 'jchuff.c', 'jcinit.c', 'jcmainct.c', 'jcmarker.c', 'jcmaster.c', 'jcomapi.c', 'jcparam.c', 'jcprepct.c', 'jcsample.c', 'jctrans.c', 'jdapimin.c', 'jdapistd.c', 'jdarith.c', 'jdatadst.c', 'jdatasrc.c', 'jdcoefct.c', 'jdcolor.c', 'jddctmgr.c', 'jdhuff.c', 'jdinput.c', 'jdmainct.c', 'jdmarker.c', 'jdmaster.c', 'jdmerge.c', 'jdpostct.c', 'jdsample.c', 'jdtrans.c', 'jerror.c', 'jfdctflt.c', 'jfdctfst.c', 'jfdctint.c', 'jidctflt.c', 'jidctfst.c', 'jidctint.c', 'jmemmgr.c', 'jmemnobs.c', 'jquant1.c', 'jquant2.c', 'jutils.c'];
JPEGLIBOBJ = [];
for fileName in JPEGLIBNAMES:
JPEGLIBOBJ += [JPEGLIB_PREFIX + fileName];
LIBPNG_PREFIX = 'libpng/';
LIBPNGNAMES = ['png.c', 'pngerror.c', 'pngget.c', 'pngmem.c', 'pngpread.c', 'pngread.c', 'pngrio.c', 'pngrtran.c', 'pngrutil.c', 'pngset.c', 'pngtrans.c', 'pngwio.c', 'pngwrite.c', 'pngwtran.c', 'pngwutil.c'];
LIBPNGOBJ = [];
for fileName in LIBPNGNAMES:
LIBPNGOBJ += [LIBPNG_PREFIX + fileName];
AESGLADMAN_PREFIX = 'aesGladman/';
AESGLADMANNAMES = ['aescrypt.cpp', 'aeskey.cpp', 'aestab.cpp', 'fileenc.cpp', 'hmac.cpp', 'prng.cpp', 'pwd2key.cpp', 'sha1.cpp', 'sha2.cpp'];
AESGLADMANOBJ = [];
for fileName in AESGLADMANNAMES:
AESGLADMANOBJ += [AESGLADMAN_PREFIX + fileName];
BZIP2_PREFIX = 'bzip2/';
BZIP2NAMES = ['blocksort.c', 'bzcompress.c', 'bzlib.c', 'crctable.c', 'decompress.c', 'huffman.c', 'randtable.c'];
BZIP2OBJ = [];
for fileName in BZIP2NAMES:
BZIP2OBJ += [BZIP2_PREFIX + fileName];
# Next variable is for additional scene nodes etc. of customized Irrlicht versions
EXTRAOBJ = [];
LINKOBJ = IRRMESHOBJ + IRROBJ + IRRPARTICLEOBJ + IRRANIMOBJ + IRRVIDEOOBJ + IRRSWRENDEROBJ + IRRIOOBJ + IRROTHEROBJ + IRRGUIOBJ + ZLIBOBJ + JPEGLIBOBJ + LIBPNGOBJ + AESGLADMANOBJ + EXTRAOBJ;
env.Append(LIBS = LIBRARIES, LIBPATH = CXXINCS);
CXXFLAGS = ['-Wall'];
if NDEBUG:
- CXXFLAGS += ['-g', '-D_DEBUG'];
-else:
CXXFLAGS += ['-fexpensive-optimizations', '-O3'];
+else:
+ CXXFLAGS += ['-g', '-D_DEBUG'];
if PROFILE:
CXXFLAGS += ['-pg'];
CXXFLAGS += ['-DPNG_NO_MMX_CODE', '-DPNG_NO_MNG_FEATURES', '-DIRRLICHT_EXPORTS=1', '-D_IRR_STATIC_LIB_'];
if USE_GCC:
CXXFLAGS += ['-D__GNUWIN32__=1'];
env.Append(CCFLAGS = CXXFLAGS);
IrrlichtLibrary = env.SharedLibrary("Irrlicht.dll", LINKOBJ);
|
paupawsan/Irrlicht
|
2e794c7357d748ca7ceefdcb1fa3aec77de4cc14
|
Make driver choice look like the one from the provided header file. Make a variable const.
|
diff --git a/examples/02.Quake3Map/main.cpp b/examples/02.Quake3Map/main.cpp
index 55eb19c..24aa6b6 100644
--- a/examples/02.Quake3Map/main.cpp
+++ b/examples/02.Quake3Map/main.cpp
@@ -1,206 +1,206 @@
/** Example 002 Quake3Map
This Tutorial shows how to load a Quake 3 map into the engine, create a
SceneNode for optimizing the speed of rendering, and how to create a user
controlled camera.
Please note that you should know the basics of the engine before starting this
tutorial. Just take a short look at the first tutorial, if you haven't done
this yet: http://irrlicht.sourceforge.net/tut001.html
Lets start like the HelloWorld example: We include the irrlicht header files
and an additional file to be able to ask the user for a driver type using the
console.
*/
#include <irrlicht.h>
#include <iostream>
/*
As already written in the HelloWorld example, in the Irrlicht Engine everything
can be found in the namespace 'irr'. To get rid of the irr:: in front of the
name of every class, we tell the compiler that we use that namespace from now
on, and we will not have to write that 'irr::'. There are 5 other sub
namespaces 'core', 'scene', 'video', 'io' and 'gui'. Unlike in the HelloWorld
example, we do not call 'using namespace' for these 5 other namespaces, because
in this way you will see what can be found in which namespace. But if you like,
you can also include the namespaces like in the previous example.
*/
using namespace irr;
/*
Again, to be able to use the Irrlicht.DLL file, we need to link with the
Irrlicht.lib. We could set this option in the project settings, but to make it
easy, we use a pragma comment lib:
*/
#ifdef _MSC_VER
#pragma comment(lib, "Irrlicht.lib")
#endif
/*
Ok, lets start. Again, we use the main() method as start, not the WinMain().
*/
int main()
{
/*
Like in the HelloWorld example, we create an IrrlichtDevice with
createDevice(). The difference now is that we ask the user to select
which video driver to use. The Software device might be
too slow to draw a huge Quake 3 map, but just for the fun of it, we make
this decision possible, too.
Instead of copying this whole code into your app, you can simply include
driverChoice.h from Irrlicht's include directory. The function
driverChoiceConsole does exactly the same.
*/
// ask user for driver
video::E_DRIVER_TYPE driverType;
printf("Please select the driver you want for this example:\n"\
- " (a) Direct3D 9.0c\n (b) Direct3D 8.1\n (c) OpenGL 1.5\n"\
- " (d) Software Renderer\n (e) Burning's Software Renderer\n"\
+ " (a) OpenGL 1.5\n (b) Direct3D 9.0c\n (c) Direct3D 8.1\n"\
+ " (d) Burning's Software Renderer\n (e) Software Renderer\n"\
" (f) NullDevice\n (otherKey) exit\n\n");
char i;
std::cin >> i;
switch(i)
{
- case 'a': driverType = video::EDT_DIRECT3D9;break;
- case 'b': driverType = video::EDT_DIRECT3D8;break;
- case 'c': driverType = video::EDT_OPENGL; break;
- case 'd': driverType = video::EDT_SOFTWARE; break;
- case 'e': driverType = video::EDT_BURNINGSVIDEO;break;
+ case 'a': driverType = video::EDT_OPENGL; break;
+ case 'b': driverType = video::EDT_DIRECT3D9;break;
+ case 'c': driverType = video::EDT_DIRECT3D8;break;
+ case 'd': driverType = video::EDT_BURNINGSVIDEO;break;
+ case 'e': driverType = video::EDT_SOFTWARE; break;
case 'f': driverType = video::EDT_NULL; break;
default: return 1;
}
// create device and exit if creation failed
IrrlichtDevice *device =
createDevice(driverType, core::dimension2d<u32>(640, 480));
if (device == 0)
return 1; // could not create selected driver.
/*
Get a pointer to the video driver and the SceneManager so that
we do not always have to call irr::IrrlichtDevice::getVideoDriver() and
irr::IrrlichtDevice::getSceneManager().
*/
video::IVideoDriver* driver = device->getVideoDriver();
scene::ISceneManager* smgr = device->getSceneManager();
/*
To display the Quake 3 map, we first need to load it. Quake 3 maps
are packed into .pk3 files which are nothing else than .zip files.
So we add the .pk3 file to our irr::io::IFileSystem. After it was added,
we are able to read from the files in that archive as if they are
directly stored on the disk.
*/
device->getFileSystem()->addZipFileArchive("../../media/map-20kdm2.pk3");
/*
Now we can load the mesh by calling
irr::scene::ISceneManager::getMesh(). We get a pointer returned to an
irr::scene::IAnimatedMesh. As you might know, Quake 3 maps are not
really animated, they are only a huge chunk of static geometry with
some materials attached. Hence the IAnimatedMesh consists of only one
frame, so we get the "first frame" of the "animation", which is our
quake level and create an Octree scene node with it, using
irr::scene::ISceneManager::addOctreeSceneNode().
The Octree optimizes the scene a little bit, trying to draw only geometry
which is currently visible. An alternative to the Octree would be a
irr::scene::IMeshSceneNode, which would always draw the complete
geometry of the mesh, without optimization. Try it: Use
irr::scene::ISceneManager::addMeshSceneNode() instead of
addOctreeSceneNode() and compare the primitives drawn by the video
driver. (There is a irr::video::IVideoDriver::getPrimitiveCountDrawn()
method in the irr::video::IVideoDriver class). Note that this
optimization with the Octree is only useful when drawing huge meshes
consisting of lots of geometry.
*/
scene::IAnimatedMesh* mesh = smgr->getMesh("20kdm2.bsp");
scene::ISceneNode* node = 0;
if (mesh)
node = smgr->addOctreeSceneNode(mesh->getMesh(0), 0, -1, 1024);
// node = smgr->addMeshSceneNode(mesh->getMesh(0));
/*
Because the level was not modelled around the origin (0,0,0), we
translate the whole level a little bit. This is done on
irr::scene::ISceneNode level using the methods
irr::scene::ISceneNode::setPosition() (in this case),
irr::scene::ISceneNode::setRotation(), and
irr::scene::ISceneNode::setScale().
*/
if (node)
node->setPosition(core::vector3df(-1300,-144,-1249));
/*
Now we only need a camera to look at the Quake 3 map.
We want to create a user controlled camera. There are some
cameras available in the Irrlicht engine. For example the
MayaCamera which can be controlled like the camera in Maya:
Rotate with left mouse button pressed, Zoom with both buttons pressed,
translate with right mouse button pressed. This could be created with
irr::scene::ISceneManager::addCameraSceneNodeMaya(). But for this
example, we want to create a camera which behaves like the ones in
first person shooter games (FPS) and hence use
irr::scene::ISceneManager::addCameraSceneNodeFPS().
*/
smgr->addCameraSceneNodeFPS();
/*
The mouse cursor needs not be visible, so we hide it via the
irr::IrrlichtDevice::ICursorControl.
*/
device->getCursorControl()->setVisible(false);
/*
We have done everything, so lets draw it. We also write the current
frames per second and the primitives drawn into the caption of the
window. The test for irr::IrrlichtDevice::isWindowActive() is optional,
but prevents the engine to grab the mouse cursor after task switching
when other programs are active. The call to
irr::IrrlichtDevice::yield() will avoid the busy loop to eat up all CPU
cycles when the window is not active.
*/
int lastFPS = -1;
while(device->run())
{
if (device->isWindowActive())
{
driver->beginScene(true, true, video::SColor(255,200,200,200));
smgr->drawAll();
driver->endScene();
int fps = driver->getFPS();
if (lastFPS != fps)
{
core::stringw str = L"Irrlicht Engine - Quake 3 Map example [";
str += driver->getName();
str += "] FPS:";
str += fps;
device->setWindowCaption(str.c_str());
lastFPS = fps;
}
}
else
device->yield();
}
/*
In the end, delete the Irrlicht device.
*/
device->drop();
return 0;
}
/*
That's it. Compile and play around with the program.
**/
diff --git a/source/Irrlicht/CSceneNodeAnimatorCollisionResponse.cpp b/source/Irrlicht/CSceneNodeAnimatorCollisionResponse.cpp
index 21ce37e..d194838 100644
--- a/source/Irrlicht/CSceneNodeAnimatorCollisionResponse.cpp
+++ b/source/Irrlicht/CSceneNodeAnimatorCollisionResponse.cpp
@@ -1,303 +1,303 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CSceneNodeAnimatorCollisionResponse.h"
#include "ISceneCollisionManager.h"
#include "ISceneManager.h"
#include "ICameraSceneNode.h"
#include "os.h"
namespace irr
{
namespace scene
{
//! constructor
CSceneNodeAnimatorCollisionResponse::CSceneNodeAnimatorCollisionResponse(
ISceneManager* scenemanager,
ITriangleSelector* world, ISceneNode* object,
const core::vector3df& ellipsoidRadius,
const core::vector3df& gravityPerSecond,
const core::vector3df& ellipsoidTranslation,
f32 slidingSpeed)
: Radius(ellipsoidRadius), Gravity(gravityPerSecond), Translation(ellipsoidTranslation),
World(world), Object(object), SceneManager(scenemanager), LastTime(0),
SlidingSpeed(slidingSpeed), CollisionCallback(0),
Falling(false), IsCamera(false), AnimateCameraTarget(true), CollisionOccurred(false),
FirstUpdate(true)
{
#ifdef _DEBUG
setDebugName("CSceneNodeAnimatorCollisionResponse");
#endif
if (World)
World->grab();
setNode(Object);
}
//! destructor
CSceneNodeAnimatorCollisionResponse::~CSceneNodeAnimatorCollisionResponse()
{
if (World)
World->drop();
if (CollisionCallback)
CollisionCallback->drop();
}
//! Returns if the attached scene node is falling, which means that
//! there is no blocking wall from the scene node in the direction of
//! the gravity.
bool CSceneNodeAnimatorCollisionResponse::isFalling() const
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return Falling;
}
//! Sets the radius of the ellipsoid with which collision detection and
//! response is done.
void CSceneNodeAnimatorCollisionResponse::setEllipsoidRadius(
const core::vector3df& radius)
{
Radius = radius;
FirstUpdate = true;
}
//! Returns the radius of the ellipsoid with wich the collision detection and
//! response is done.
core::vector3df CSceneNodeAnimatorCollisionResponse::getEllipsoidRadius() const
{
return Radius;
}
//! Sets the gravity of the environment.
void CSceneNodeAnimatorCollisionResponse::setGravity(const core::vector3df& gravity)
{
Gravity = gravity;
FirstUpdate = true;
}
//! Returns current vector of gravity.
core::vector3df CSceneNodeAnimatorCollisionResponse::getGravity() const
{
return Gravity;
}
//! 'Jump' the animator, by adding a jump speed opposite to its gravity
void CSceneNodeAnimatorCollisionResponse::jump(f32 jumpSpeed)
{
FallingVelocity -= (core::vector3df(Gravity).normalize()) * jumpSpeed;
Falling = true;
}
//! Sets the translation of the ellipsoid for collision detection.
void CSceneNodeAnimatorCollisionResponse::setEllipsoidTranslation(const core::vector3df &translation)
{
Translation = translation;
}
//! Returns the translation of the ellipsoid for collision detection.
core::vector3df CSceneNodeAnimatorCollisionResponse::getEllipsoidTranslation() const
{
return Translation;
}
//! Sets a triangle selector holding all triangles of the world with which
//! the scene node may collide.
void CSceneNodeAnimatorCollisionResponse::setWorld(ITriangleSelector* newWorld)
{
if (newWorld)
newWorld->grab();
if (World)
World->drop();
World = newWorld;
FirstUpdate = true;
}
//! Returns the current triangle selector containing all triangles for
//! collision detection.
ITriangleSelector* CSceneNodeAnimatorCollisionResponse::getWorld() const
{
return World;
}
void CSceneNodeAnimatorCollisionResponse::animateNode(ISceneNode* node, u32 timeMs)
{
CollisionOccurred = false;
if (node != Object)
setNode(node);
if(!Object || !World)
return;
// trigger reset
if ( timeMs == 0 )
{
FirstUpdate = true;
timeMs = LastTime;
}
if ( FirstUpdate )
{
LastPosition = Object->getPosition();
Falling = false;
LastTime = timeMs;
FallingVelocity.set ( 0, 0, 0 );
FirstUpdate = false;
}
- u32 diff = timeMs - LastTime;
+ const u32 diff = timeMs - LastTime;
LastTime = timeMs;
CollisionResultPosition = Object->getPosition();
core::vector3df vel = CollisionResultPosition - LastPosition;
FallingVelocity += Gravity * (f32)diff * 0.001f;
CollisionTriangle = RefTriangle;
CollisionPoint = core::vector3df();
CollisionResultPosition = core::vector3df();
CollisionNode = 0;
core::vector3df force = vel + FallingVelocity;
if ( AnimateCameraTarget )
{
// TODO: divide SlidingSpeed by frame time
bool f = false;
CollisionResultPosition
= SceneManager->getSceneCollisionManager()->getCollisionResultPosition(
World, LastPosition-Translation,
Radius, vel, CollisionTriangle, CollisionPoint, f,
CollisionNode, SlidingSpeed, FallingVelocity);
CollisionOccurred = (CollisionTriangle != RefTriangle);
CollisionResultPosition += Translation;
if (f)//CollisionTriangle == RefTriangle)
{
Falling = true;
}
else
{
Falling = false;
FallingVelocity.set(0, 0, 0);
}
bool collisionConsumed = false;
if (CollisionOccurred && CollisionCallback)
collisionConsumed = CollisionCallback->onCollision(*this);
if(!collisionConsumed)
Object->setPosition(CollisionResultPosition);
}
// move camera target
if (AnimateCameraTarget && IsCamera)
{
const core::vector3df pdiff = Object->getPosition() - LastPosition - vel;
ICameraSceneNode* cam = (ICameraSceneNode*)Object;
cam->setTarget(cam->getTarget() + pdiff);
}
LastPosition = Object->getPosition();
}
void CSceneNodeAnimatorCollisionResponse::setNode(ISceneNode* node)
{
Object = node;
if (Object)
{
LastPosition = Object->getPosition();
IsCamera = (Object->getType() == ESNT_CAMERA);
}
LastTime = os::Timer::getTime();
}
//! Writes attributes of the scene node animator.
void CSceneNodeAnimatorCollisionResponse::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const
{
out->addVector3d("Radius", Radius);
out->addVector3d("Gravity", Gravity);
out->addVector3d("Translation", Translation);
out->addBool("AnimateCameraTarget", AnimateCameraTarget);
}
//! Reads attributes of the scene node animator.
void CSceneNodeAnimatorCollisionResponse::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
Radius = in->getAttributeAsVector3d("Radius");
Gravity = in->getAttributeAsVector3d("Gravity");
Translation = in->getAttributeAsVector3d("Translation");
AnimateCameraTarget = in->getAttributeAsBool("AnimateCameraTarget");
}
ISceneNodeAnimator* CSceneNodeAnimatorCollisionResponse::createClone(ISceneNode* node, ISceneManager* newManager)
{
if (!newManager) newManager = SceneManager;
CSceneNodeAnimatorCollisionResponse * newAnimator =
new CSceneNodeAnimatorCollisionResponse(newManager, World, Object, Radius,
(Gravity * 1000.0f), Translation, SlidingSpeed);
return newAnimator;
}
void CSceneNodeAnimatorCollisionResponse::setCollisionCallback(ICollisionCallback* callback)
{
if ( CollisionCallback == callback )
return;
if (CollisionCallback)
CollisionCallback->drop();
CollisionCallback = callback;
if (CollisionCallback)
CollisionCallback->grab();
}
//! Should the Target react on collision ( default = true )
void CSceneNodeAnimatorCollisionResponse::setAnimateTarget ( bool enable )
{
AnimateCameraTarget = enable;
FirstUpdate = true;
}
//! Should the Target react on collision ( default = true )
bool CSceneNodeAnimatorCollisionResponse::getAnimateTarget () const
{
return AnimateCameraTarget;
}
} // end namespace scene
} // end namespace irr
|
paupawsan/Irrlicht
|
e7d4082c146448ae871ac11d15ffa4d74b0fd570
|
Documentation: Autoscrolling in IGUIListBox does not actually jump to last added item. Which is a missing feature, but at least now documented correct.
|
diff --git a/include/IGUIListBox.h b/include/IGUIListBox.h
index 64c02ac..9f53745 100644
--- a/include/IGUIListBox.h
+++ b/include/IGUIListBox.h
@@ -1,130 +1,130 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __I_GUI_LIST_BOX_H_INCLUDED__
#define __I_GUI_LIST_BOX_H_INCLUDED__
#include "IGUIElement.h"
#include "SColor.h"
namespace irr
{
namespace gui
{
class IGUISpriteBank;
//! Enumeration for listbox colors
enum EGUI_LISTBOX_COLOR
{
//! Color of text
EGUI_LBC_TEXT=0,
//! Color of selected text
EGUI_LBC_TEXT_HIGHLIGHT,
//! Color of icon
EGUI_LBC_ICON,
//! Color of selected icon
EGUI_LBC_ICON_HIGHLIGHT,
//! Not used, just counts the number of available colors
EGUI_LBC_COUNT
};
//! Default list box GUI element.
class IGUIListBox : public IGUIElement
{
public:
//! constructor
IGUIListBox(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect<s32> rectangle)
: IGUIElement(EGUIET_LIST_BOX, environment, parent, id, rectangle) {}
//! returns amount of list items
virtual u32 getItemCount() const = 0;
//! returns string of a list item. the may id be a value from 0 to itemCount-1
virtual const wchar_t* getListItem(u32 id) const = 0;
//! adds an list item, returns id of item
virtual u32 addItem(const wchar_t* text) = 0;
//! adds an list item with an icon
/** \param text Text of list entry
\param icon Sprite index of the Icon within the current sprite bank. Set it to -1 if you want no icon
\return The id of the new created item */
virtual u32 addItem(const wchar_t* text, s32 icon) = 0;
//! Removes an item from the list
virtual void removeItem(u32 index) = 0;
//! Returns the icon of an item
virtual s32 getIcon(u32 index) const = 0;
//! Sets the sprite bank which should be used to draw list icons.
/** This font is set to the sprite bank of the built-in-font by
default. A sprite can be displayed in front of every list item.
An icon is an index within the icon sprite bank. Several
default icons are available in the skin through getIcon. */
virtual void setSpriteBank(IGUISpriteBank* bank) = 0;
//! clears the list, deletes all items in the listbox
virtual void clear() = 0;
//! returns id of selected item. returns -1 if no item is selected.
virtual s32 getSelected() const = 0;
//! sets the selected item. Set this to -1 if no item should be selected
virtual void setSelected(s32 index) = 0;
//! sets the selected item. Set this to 0 if no item should be selected
virtual void setSelected(const wchar_t *item) = 0;
- //! set whether the listbox should scroll to new or newly selected items
+ //! set whether the listbox should scroll to newly selected items
virtual void setAutoScrollEnabled(bool scroll) = 0;
//! returns true if automatic scrolling is enabled, false if not.
virtual bool isAutoScrollEnabled() const = 0;
//! set all item colors at given index to color
virtual void setItemOverrideColor(u32 index, const video::SColor &color) = 0;
//! set all item colors of specified type at given index to color
virtual void setItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType, const video::SColor &color) = 0;
//! clear all item colors at index
virtual void clearItemOverrideColor(u32 index) = 0;
//! clear item color at index for given colortype
virtual void clearItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) = 0;
//! has the item at index its color overwritten?
virtual bool hasItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const = 0;
//! return the overwrite color at given item index.
virtual video::SColor getItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const = 0;
//! return the default color which is used for the given colorType
virtual video::SColor getItemDefaultColor(EGUI_LISTBOX_COLOR colorType) const = 0;
//! set the item at the given index
virtual void setItem(u32 index, const wchar_t* text, s32 icon) = 0;
//! Insert the item at the given index
/** \return The index on success or -1 on failure. */
virtual s32 insertItem(u32 index, const wchar_t* text, s32 icon) = 0;
//! Swap the items at the given indices
virtual void swapItems(u32 index1, u32 index2) = 0;
//! set global itemHeight
virtual void setItemHeight( s32 height ) = 0;
//! Sets whether to draw the background
virtual void setDrawBackground(bool draw) = 0;
};
} // end namespace gui
} // end namespace irr
#endif
diff --git a/source/Irrlicht/CGUIListBox.h b/source/Irrlicht/CGUIListBox.h
index 43c6b37..2aaa081 100644
--- a/source/Irrlicht/CGUIListBox.h
+++ b/source/Irrlicht/CGUIListBox.h
@@ -1,187 +1,187 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_GUI_LIST_BOX_H_INCLUDED__
#define __C_GUI_LIST_BOX_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include "IGUIListBox.h"
#include "irrArray.h"
namespace irr
{
namespace gui
{
class IGUIFont;
class IGUIScrollBar;
class CGUIListBox : public IGUIListBox
{
public:
//! constructor
CGUIListBox(IGUIEnvironment* environment, IGUIElement* parent,
s32 id, core::rect<s32> rectangle, bool clip=true,
bool drawBack=false, bool moveOverSelect=false);
//! destructor
virtual ~CGUIListBox();
//! returns amount of list items
virtual u32 getItemCount() const;
//! returns string of a list item. the id may be a value from 0 to itemCount-1
virtual const wchar_t* getListItem(u32 id) const;
//! adds an list item, returns id of item
virtual u32 addItem(const wchar_t* text);
//! clears the list
virtual void clear();
//! returns id of selected item. returns -1 if no item is selected.
virtual s32 getSelected() const;
//! sets the selected item. Set this to -1 if no item should be selected
virtual void setSelected(s32 id);
//! sets the selected item. Set this to -1 if no item should be selected
virtual void setSelected(const wchar_t *item);
//! called if an event happened.
virtual bool OnEvent(const SEvent& event);
//! draws the element and its children
virtual void draw();
//! adds an list item with an icon
//! \param text Text of list entry
//! \param icon Sprite index of the Icon within the current sprite bank. Set it to -1 if you want no icon
//! \return
//! returns the id of the new created item
virtual u32 addItem(const wchar_t* text, s32 icon);
//! Returns the icon of an item
virtual s32 getIcon(u32 id) const;
//! removes an item from the list
virtual void removeItem(u32 id);
//! Sets the sprite bank which should be used to draw list icons. This font is set to the sprite bank of
//! the built-in-font by default. A sprite can be displayed in front of every list item.
//! An icon is an index within the icon sprite bank. Several default icons are available in the
//! skin through getIcon
virtual void setSpriteBank(IGUISpriteBank* bank);
- //! sets if automatic scrolling is enabled or not. Default is true.
+ //! set whether the listbox should scroll to newly selected items
virtual void setAutoScrollEnabled(bool scroll);
//! returns true if automatic scrolling is enabled, false if not.
virtual bool isAutoScrollEnabled() const;
//! Update the position and size of the listbox, and update the scrollbar
virtual void updateAbsolutePosition();
//! Writes attributes of the element.
virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const;
//! Reads attributes of the element
virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options);
//! set all item colors at given index to color
virtual void setItemOverrideColor(u32 index, const video::SColor &color);
//! set all item colors of specified type at given index to color
virtual void setItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType, const video::SColor &color);
//! clear all item colors at index
virtual void clearItemOverrideColor(u32 index);
//! clear item color at index for given colortype
virtual void clearItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType);
//! has the item at index its color overwritten?
virtual bool hasItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const;
//! return the overwrite color at given item index.
virtual video::SColor getItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const;
//! return the default color which is used for the given colorType
virtual video::SColor getItemDefaultColor(EGUI_LISTBOX_COLOR colorType) const;
//! set the item at the given index
virtual void setItem(u32 index, const wchar_t* text, s32 icon);
//! Insert the item at the given index
//! Return the index on success or -1 on failure.
virtual s32 insertItem(u32 index, const wchar_t* text, s32 icon);
//! Swap the items at the given indices
virtual void swapItems(u32 index1, u32 index2);
//! set global itemHeight
virtual void setItemHeight( s32 height );
//! Sets whether to draw the background
virtual void setDrawBackground(bool draw);
private:
struct ListItem
{
ListItem() : icon(-1)
{}
core::stringw text;
s32 icon;
// A multicolor extension
struct ListItemOverrideColor
{
ListItemOverrideColor() : Use(false) {}
bool Use;
video::SColor Color;
};
ListItemOverrideColor OverrideColors[EGUI_LBC_COUNT];
};
void recalculateItemHeight();
void selectNew(s32 ypos, bool onlyHover=false);
void recalculateScrollPos();
// extracted that function to avoid copy&paste code
void recalculateItemWidth(s32 icon);
// get labels used for serialization
bool getSerializationLabels(EGUI_LISTBOX_COLOR colorType, core::stringc & useColorLabel, core::stringc & colorLabel) const;
core::array< ListItem > Items;
s32 Selected;
s32 ItemHeight;
s32 ItemHeightOverride;
s32 TotalItemHeight;
s32 ItemsIconWidth;
gui::IGUIFont* Font;
gui::IGUISpriteBank* IconBank;
gui::IGUIScrollBar* ScrollBar;
u32 selectTime;
u32 LastKeyTime;
core::stringw KeyBuffer;
bool Selecting;
bool DrawBack;
bool MoveOverSelect;
bool AutoScroll;
bool HighlightWhenNotFocused;
};
} // end namespace gui
} // end namespace irr
#endif // _IRR_COMPILE_WITH_GUI_
#endif
|
paupawsan/Irrlicht
|
70ac0921fa10bfd90b1ee8c00d59351af5140430
|
Document real behavior for EGET_LISTBOX_CHANGED and EGET_LISTBOX_SELECTED_AGAIN. The problem was mentioned by xDan and has bug-id: 2935595 It should be fixed in the future, but the current behavior is necessary for the file-open dialog at the moment, so that has to be changed first.
|
diff --git a/include/IEventReceiver.h b/include/IEventReceiver.h
index ee8bb73..0ca2245 100644
--- a/include/IEventReceiver.h
+++ b/include/IEventReceiver.h
@@ -1,483 +1,485 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __I_EVENT_RECEIVER_H_INCLUDED__
#define __I_EVENT_RECEIVER_H_INCLUDED__
#include "ILogger.h"
#include "position2d.h"
#include "Keycodes.h"
#include "irrString.h"
namespace irr
{
//! Enumeration for all event types there are.
enum EEVENT_TYPE
{
//! An event of the graphical user interface.
/** GUI events are created by the GUI environment or the GUI elements in response
to mouse or keyboard events. When a GUI element receives an event it will either
process it and return true, or pass the event to its parent. If an event is not absorbed
before it reaches the root element then it will then be passed to the user receiver. */
EET_GUI_EVENT = 0,
//! A mouse input event.
/** Mouse events are created by the device and passed to IrrlichtDevice::postEventFromUser
in response to mouse input received from the operating system.
Mouse events are first passed to the user receiver, then to the GUI environment and its elements,
then finally the input receiving scene manager where it is passed to the active camera.
*/
EET_MOUSE_INPUT_EVENT,
//! A key input event.
/** Like mouse events, keyboard events are created by the device and passed to
IrrlichtDevice::postEventFromUser. They take the same path as mouse events. */
EET_KEY_INPUT_EVENT,
//! A joystick (joypad, gamepad) input event.
/** Joystick events are created by polling all connected joysticks once per
device run() and then passing the events to IrrlichtDevice::postEventFromUser.
They take the same path as mouse events.
Windows, SDL: Implemented.
Linux: Implemented, with POV hat issues.
MacOS / Other: Not yet implemented.
*/
EET_JOYSTICK_INPUT_EVENT,
//! A log event
/** Log events are only passed to the user receiver if there is one. If they are absorbed by the
user receiver then no text will be sent to the console. */
EET_LOG_TEXT_EVENT,
//! A user event with user data.
/** This is not used by Irrlicht and can be used to send user
specific data though the system. The Irrlicht 'window handle'
can be obtained from IrrlichtDevice::getExposedVideoData()
The usage and behaviour depends on the operating system:
Windows: send a WM_USER message to the Irrlicht Window; the
wParam and lParam will be used to populate the
UserData1 and UserData2 members of the SUserEvent.
Linux: send a ClientMessage via XSendEvent to the Irrlicht
Window; the data.l[0] and data.l[1] members will be
casted to s32 and used as UserData1 and UserData2.
MacOS: Not yet implemented
*/
EET_USER_EVENT,
//! This enum is never used, it only forces the compiler to
//! compile these enumeration values to 32 bit.
EGUIET_FORCE_32_BIT = 0x7fffffff
};
//! Enumeration for all mouse input events
enum EMOUSE_INPUT_EVENT
{
//! Left mouse button was pressed down.
EMIE_LMOUSE_PRESSED_DOWN = 0,
//! Right mouse button was pressed down.
EMIE_RMOUSE_PRESSED_DOWN,
//! Middle mouse button was pressed down.
EMIE_MMOUSE_PRESSED_DOWN,
//! Left mouse button was left up.
EMIE_LMOUSE_LEFT_UP,
//! Right mouse button was left up.
EMIE_RMOUSE_LEFT_UP,
//! Middle mouse button was left up.
EMIE_MMOUSE_LEFT_UP,
//! The mouse cursor changed its position.
EMIE_MOUSE_MOVED,
//! The mouse wheel was moved. Use Wheel value in event data to find out
//! in what direction and how fast.
EMIE_MOUSE_WHEEL,
//! Left mouse button double click.
//! This event is generated after the second EMIE_LMOUSE_PRESSED_DOWN event.
EMIE_LMOUSE_DOUBLE_CLICK,
//! Right mouse button double click.
//! This event is generated after the second EMIE_RMOUSE_PRESSED_DOWN event.
EMIE_RMOUSE_DOUBLE_CLICK,
//! Middle mouse button double click.
//! This event is generated after the second EMIE_MMOUSE_PRESSED_DOWN event.
EMIE_MMOUSE_DOUBLE_CLICK,
//! Left mouse button triple click.
//! This event is generated after the third EMIE_LMOUSE_PRESSED_DOWN event.
EMIE_LMOUSE_TRIPLE_CLICK,
//! Right mouse button triple click.
//! This event is generated after the third EMIE_RMOUSE_PRESSED_DOWN event.
EMIE_RMOUSE_TRIPLE_CLICK,
//! Middle mouse button triple click.
//! This event is generated after the third EMIE_MMOUSE_PRESSED_DOWN event.
EMIE_MMOUSE_TRIPLE_CLICK,
//! No real event. Just for convenience to get number of events
EMIE_COUNT
};
//! Masks for mouse button states
enum E_MOUSE_BUTTON_STATE_MASK
{
EMBSM_LEFT = 0x01,
EMBSM_RIGHT = 0x02,
EMBSM_MIDDLE = 0x04,
//! currently only on windows
EMBSM_EXTRA1 = 0x08,
//! currently only on windows
EMBSM_EXTRA2 = 0x10,
EMBSM_FORCE_32_BIT = 0x7fffffff
};
namespace gui
{
class IGUIElement;
//! Enumeration for all events which are sendable by the gui system
enum EGUI_EVENT_TYPE
{
//! A gui element has lost its focus.
/** GUIEvent.Caller is losing the focus to GUIEvent.Element.
If the event is absorbed then the focus will not be changed. */
EGET_ELEMENT_FOCUS_LOST = 0,
//! A gui element has got the focus.
/** If the event is absorbed then the focus will not be changed. */
EGET_ELEMENT_FOCUSED,
//! The mouse cursor hovered over a gui element.
EGET_ELEMENT_HOVERED,
//! The mouse cursor left the hovered element.
EGET_ELEMENT_LEFT,
//! An element would like to close.
/** Windows and context menus use this event when they would like to close,
this can be cancelled by absorbing the event. */
EGET_ELEMENT_CLOSED,
//! A button was clicked.
EGET_BUTTON_CLICKED,
//! A scrollbar has changed its position.
EGET_SCROLL_BAR_CHANGED,
//! A checkbox has changed its check state.
EGET_CHECKBOX_CHANGED,
- //! A new item in a listbox was seleted.
+ //! A new item in a listbox was selected.
+ /** NOTE: You also get this event currently when the same item was clicked again after more than 500 ms. */
EGET_LISTBOX_CHANGED,
//! An item in the listbox was selected, which was already selected.
+ /** NOTE: You get the event currently only if the item was clicked again within 500 ms or selected by "enter" or "space". */
EGET_LISTBOX_SELECTED_AGAIN,
//! A file has been selected in the file dialog
EGET_FILE_SELECTED,
//! A directory has been selected in the file dialog
EGET_DIRECTORY_SELECTED,
//! A file open dialog has been closed without choosing a file
EGET_FILE_CHOOSE_DIALOG_CANCELLED,
//! 'Yes' was clicked on a messagebox
EGET_MESSAGEBOX_YES,
//! 'No' was clicked on a messagebox
EGET_MESSAGEBOX_NO,
//! 'OK' was clicked on a messagebox
EGET_MESSAGEBOX_OK,
//! 'Cancel' was clicked on a messagebox
EGET_MESSAGEBOX_CANCEL,
//! In an editbox 'ENTER' was pressed
EGET_EDITBOX_ENTER,
//! The text in an editbox was changed. This does not include automatic changes in text-breaking.
EGET_EDITBOX_CHANGED,
//! The marked area in an editbox was changed.
EGET_EDITBOX_MARKING_CHANGED,
//! The tab was changed in an tab control
EGET_TAB_CHANGED,
//! A menu item was selected in a (context) menu
EGET_MENU_ITEM_SELECTED,
//! The selection in a combo box has been changed
EGET_COMBO_BOX_CHANGED,
//! The value of a spin box has changed
EGET_SPINBOX_CHANGED,
//! A table has changed
EGET_TABLE_CHANGED,
EGET_TABLE_HEADER_CHANGED,
EGET_TABLE_SELECTED_AGAIN,
//! A tree view node lost selection. See IGUITreeView::getLastEventNode().
EGET_TREEVIEW_NODE_DESELECT,
//! A tree view node was selected. See IGUITreeView::getLastEventNode().
EGET_TREEVIEW_NODE_SELECT,
//! A tree view node was expanded. See IGUITreeView::getLastEventNode().
EGET_TREEVIEW_NODE_EXPAND,
//! A tree view node was collapsed. See IGUITreeView::getLastEventNode().
EGET_TREEVIEW_NODE_COLLAPS,
//! No real event. Just for convenience to get number of events
EGET_COUNT
};
} // end namespace gui
//! SEvents hold information about an event. See irr::IEventReceiver for details on event handling.
struct SEvent
{
//! Any kind of GUI event.
struct SGUIEvent
{
//! IGUIElement who called the event
gui::IGUIElement* Caller;
//! If the event has something to do with another element, it will be held here.
gui::IGUIElement* Element;
//! Type of GUI Event
gui::EGUI_EVENT_TYPE EventType;
};
//! Any kind of mouse event.
struct SMouseInput
{
//! X position of mouse cursor
s32 X;
//! Y position of mouse cursor
s32 Y;
//! mouse wheel delta, usually 1.0 or -1.0.
/** Only valid if event was EMIE_MOUSE_WHEEL */
f32 Wheel;
//! True if shift was also pressed
bool Shift:1;
//! True if ctrl was also pressed
bool Control:1;
//! A bitmap of button states. You can use isButtonPressed() to determine
//! if a button is pressed or not.
//! Currently only valid if the event was EMIE_MOUSE_MOVED
u32 ButtonStates;
//! Is the left button pressed down?
bool isLeftPressed() const { return 0 != ( ButtonStates & EMBSM_LEFT ); }
//! Is the right button pressed down?
bool isRightPressed() const { return 0 != ( ButtonStates & EMBSM_RIGHT ); }
//! Is the middle button pressed down?
bool isMiddlePressed() const { return 0 != ( ButtonStates & EMBSM_MIDDLE ); }
//! Type of mouse event
EMOUSE_INPUT_EVENT Event;
};
//! Any kind of keyboard event.
struct SKeyInput
{
//! Character corresponding to the key (0, if not a character)
wchar_t Char;
//! Key which has been pressed or released
EKEY_CODE Key;
//! If not true, then the key was left up
bool PressedDown:1;
//! True if shift was also pressed
bool Shift:1;
//! True if ctrl was also pressed
bool Control:1;
};
//! A joystick event.
/** Unlike other events, joystick events represent the result of polling
* each connected joystick once per run() of the device. Joystick events will
* not be generated by default. If joystick support is available for the
* active device, _IRR_COMPILE_WITH_JOYSTICK_EVENTS_ is defined, and
* @ref irr::IrrlichtDevice::activateJoysticks() has been called, an event of
* this type will be generated once per joystick per @ref IrrlichtDevice::run()
* regardless of whether the state of the joystick has actually changed. */
struct SJoystickEvent
{
enum
{
NUMBER_OF_BUTTONS = 32,
AXIS_X = 0, // e.g. analog stick 1 left to right
AXIS_Y, // e.g. analog stick 1 top to bottom
AXIS_Z, // e.g. throttle, or analog 2 stick 2 left to right
AXIS_R, // e.g. rudder, or analog 2 stick 2 top to bottom
AXIS_U,
AXIS_V,
NUMBER_OF_AXES
};
/** A bitmap of button states. You can use IsButtonPressed() to
( check the state of each button from 0 to (NUMBER_OF_BUTTONS - 1) */
u32 ButtonStates;
/** For AXIS_X, AXIS_Y, AXIS_Z, AXIS_R, AXIS_U and AXIS_V
* Values are in the range -32768 to 32767, with 0 representing
* the center position. You will receive the raw value from the
* joystick, and so will usually want to implement a dead zone around
* the center of the range. Axes not supported by this joystick will
* always have a value of 0. On Linux, POV hats are represented as axes,
* usually the last two active axis.
*/
s16 Axis[NUMBER_OF_AXES];
/** The POV represents the angle of the POV hat in degrees * 100,
* from 0 to 35,900. A value of 65535 indicates that the POV hat
* is centered (or not present).
* This value is only supported on Windows. On Linux, the POV hat
* will be sent as 2 axes instead. */
u16 POV;
//! The ID of the joystick which generated this event.
/** This is an internal Irrlicht index; it does not map directly
* to any particular hardware joystick. */
u8 Joystick;
//! A helper function to check if a button is pressed.
bool IsButtonPressed(u32 button) const
{
if(button >= (u32)NUMBER_OF_BUTTONS)
return false;
return (ButtonStates & (1 << button)) ? true : false;
}
};
//! Any kind of log event.
struct SLogEvent
{
//! Pointer to text which has been logged
const c8* Text;
//! Log level in which the text has been logged
ELOG_LEVEL Level;
};
//! Any kind of user event.
struct SUserEvent
{
//! Some user specified data as int
s32 UserData1;
//! Another user specified data as int
s32 UserData2;
};
EEVENT_TYPE EventType;
union
{
struct SGUIEvent GUIEvent;
struct SMouseInput MouseInput;
struct SKeyInput KeyInput;
struct SJoystickEvent JoystickEvent;
struct SLogEvent LogEvent;
struct SUserEvent UserEvent;
};
};
//! Interface of an object which can receive events.
/** Many of the engine's classes inherit IEventReceiver so they are able to
process events. Events usually start at a postEventFromUser function and are
passed down through a chain of event receivers until OnEvent returns true. See
irr::EEVENT_TYPE for a description of where each type of event starts, and the
path it takes through the system. */
class IEventReceiver
{
public:
//! Destructor
virtual ~IEventReceiver() {}
//! Called if an event happened.
/** Please take care that you should only return 'true' when you want to _prevent_ Irrlicht
* from processing the event any further. So 'true' does mean that an event is completely done.
* Therefore your return value for all unprocessed events should be 'false'.
\return True if the event was processed.
*/
virtual bool OnEvent(const SEvent& event) = 0;
};
//! Information on a joystick, returned from @ref irr::IrrlichtDevice::activateJoysticks()
struct SJoystickInfo
{
//! The ID of the joystick
/** This is an internal Irrlicht index; it does not map directly
* to any particular hardware joystick. It corresponds to the
* irr::SJoystickEvent Joystick ID. */
u8 Joystick;
//! The name that the joystick uses to identify itself.
core::stringc Name;
//! The number of buttons that the joystick has.
u32 Buttons;
//! The number of axes that the joystick has, i.e. X, Y, Z, R, U, V.
/** Note: with a Linux device, the POV hat (if any) will use two axes. These
* will be included in this count. */
u32 Axes;
//! An indication of whether the joystick has a POV hat.
/** A Windows device will identify the presence or absence or the POV hat. A
* Linux device cannot, and will always return POV_HAT_UNKNOWN. */
enum
{
//! A hat is definitely present.
POV_HAT_PRESENT,
//! A hat is definitely not present.
POV_HAT_ABSENT,
//! The presence or absence of a hat cannot be determined.
POV_HAT_UNKNOWN
} PovHat;
}; // struct SJoystickInfo
} // end namespace irr
#endif
|
paupawsan/Irrlicht
|
8487d0d02923d3228c68aa7c00959fb87a060300
|
Consistently eat events in CGUIFileOpenDialog (mentioned by squisher).
|
diff --git a/source/Irrlicht/CGUIFileOpenDialog.cpp b/source/Irrlicht/CGUIFileOpenDialog.cpp
index 8f6894e..2f22387 100644
--- a/source/Irrlicht/CGUIFileOpenDialog.cpp
+++ b/source/Irrlicht/CGUIFileOpenDialog.cpp
@@ -1,398 +1,399 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CGUIFileOpenDialog.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include <locale.h>
#include "IGUISkin.h"
#include "IGUIEnvironment.h"
#include "IVideoDriver.h"
#include "IGUIButton.h"
#include "IGUIStaticText.h"
#include "IGUIFont.h"
#include "IGUIFontBitmap.h"
#include "IFileList.h"
#include "os.h"
namespace irr
{
namespace gui
{
const s32 FOD_WIDTH = 350;
const s32 FOD_HEIGHT = 250;
//! constructor
CGUIFileOpenDialog::CGUIFileOpenDialog(const wchar_t* title,
IGUIEnvironment* environment, IGUIElement* parent, s32 id)
: IGUIFileOpenDialog(environment, parent, id,
core::rect<s32>((parent->getAbsolutePosition().getWidth()-FOD_WIDTH)/2,
(parent->getAbsolutePosition().getHeight()-FOD_HEIGHT)/2,
(parent->getAbsolutePosition().getWidth()-FOD_WIDTH)/2+FOD_WIDTH,
(parent->getAbsolutePosition().getHeight()-FOD_HEIGHT)/2+FOD_HEIGHT)),
FileNameText(0), FileList(0), Dragging(false)
{
#ifdef _DEBUG
IGUIElement::setDebugName("CGUIFileOpenDialog");
#endif
Text = title;
IGUISkin* skin = Environment->getSkin();
IGUISpriteBank* sprites = 0;
video::SColor color(255,255,255,255);
if (skin)
{
sprites = skin->getSpriteBank();
color = skin->getColor(EGDC_WINDOW_SYMBOL);
}
const s32 buttonw = environment->getSkin()->getSize(EGDS_WINDOW_BUTTON_WIDTH);
const s32 posx = RelativeRect.getWidth() - buttonw - 4;
CloseButton = Environment->addButton(core::rect<s32>(posx, 3, posx + buttonw, 3 + buttonw), this, -1,
L"", skin ? skin->getDefaultText(EGDT_WINDOW_CLOSE) : L"Close");
CloseButton->setSubElement(true);
CloseButton->setTabStop(false);
if (sprites)
{
CloseButton->setSpriteBank(sprites);
CloseButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_WINDOW_CLOSE), color);
CloseButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_WINDOW_CLOSE), color);
}
CloseButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
CloseButton->grab();
OKButton = Environment->addButton(
core::rect<s32>(RelativeRect.getWidth()-80, 30, RelativeRect.getWidth()-10, 50),
this, -1, skin ? skin->getDefaultText(EGDT_MSG_BOX_OK) : L"OK");
OKButton->setSubElement(true);
OKButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
OKButton->grab();
CancelButton = Environment->addButton(
core::rect<s32>(RelativeRect.getWidth()-80, 55, RelativeRect.getWidth()-10, 75),
this, -1, skin ? skin->getDefaultText(EGDT_MSG_BOX_CANCEL) : L"Cancel");
CancelButton->setSubElement(true);
CancelButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
CancelButton->grab();
FileBox = Environment->addListBox(core::rect<s32>(10, 55, RelativeRect.getWidth()-90, 230), this, -1, true);
FileBox->setSubElement(true);
FileBox->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT);
FileBox->grab();
FileNameText = Environment->addEditBox(0, core::rect<s32>(10, 30, RelativeRect.getWidth()-90, 50), true, this);
FileNameText->setSubElement(true);
FileNameText->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
FileNameText->grab();
FileSystem = Environment->getFileSystem();
if (FileSystem)
FileSystem->grab();
setTabGroup(true);
fillListBox();
}
//! destructor
CGUIFileOpenDialog::~CGUIFileOpenDialog()
{
if (CloseButton)
CloseButton->drop();
if (OKButton)
OKButton->drop();
if (CancelButton)
CancelButton->drop();
if (FileBox)
FileBox->drop();
if (FileNameText)
FileNameText->drop();
if (FileSystem)
FileSystem->drop();
if (FileList)
FileList->drop();
}
//! returns the filename of the selected file. Returns NULL, if no file was selected.
const wchar_t* CGUIFileOpenDialog::getFileName() const
{
return FileName.c_str();
}
//! Returns the directory of the selected file. Returns NULL, if no directory was selected.
const io::path& CGUIFileOpenDialog::getDirectoryName()
{
FileSystem->flattenFilename ( FileDirectory );
return FileDirectory;
}
//! called if an event happened.
bool CGUIFileOpenDialog::OnEvent(const SEvent& event)
{
if (IsEnabled)
{
switch(event.EventType)
{
case EET_GUI_EVENT:
switch(event.GUIEvent.EventType)
{
case EGET_ELEMENT_FOCUS_LOST:
Dragging = false;
break;
case EGET_BUTTON_CLICKED:
if (event.GUIEvent.Caller == CloseButton ||
event.GUIEvent.Caller == CancelButton)
{
sendCancelEvent();
remove();
return true;
}
else
if (event.GUIEvent.Caller == OKButton )
{
if ( FileDirectory != L"" )
{
sendSelectedEvent( EGET_DIRECTORY_SELECTED );
}
if ( FileName != L"" )
{
sendSelectedEvent( EGET_FILE_SELECTED );
remove();
return true;
}
}
break;
case EGET_LISTBOX_CHANGED:
{
s32 selected = FileBox->getSelected();
if (FileList && FileSystem)
{
if (FileList->isDirectory(selected))
{
FileName = L"";
FileDirectory = FileList->getFullFileName(selected);
}
else
{
FileDirectory = L"";
FileName = FileList->getFullFileName(selected);
}
+ return true;
}
}
break;
case EGET_LISTBOX_SELECTED_AGAIN:
{
const s32 selected = FileBox->getSelected();
if (FileList && FileSystem)
{
if (FileList->isDirectory(selected))
{
FileDirectory = FileList->getFullFileName(selected);
FileSystem->changeWorkingDirectoryTo(FileList->getFileName(selected));
fillListBox();
FileName = "";
}
else
{
FileName = FileList->getFullFileName(selected);
- return true;
}
+ return true;
}
}
break;
case EGET_EDITBOX_ENTER:
if (event.GUIEvent.Caller == FileNameText)
{
io::path dir( FileNameText->getText () );
if ( FileSystem->changeWorkingDirectoryTo( dir ) )
{
fillListBox();
FileName = L"";
}
return true;
}
break;
default:
break;
}
break;
case EET_MOUSE_INPUT_EVENT:
switch(event.MouseInput.Event)
{
case EMIE_MOUSE_WHEEL:
return FileBox->OnEvent(event);
case EMIE_LMOUSE_PRESSED_DOWN:
DragStart.X = event.MouseInput.X;
DragStart.Y = event.MouseInput.Y;
Dragging = true;
Environment->setFocus(this);
return true;
case EMIE_LMOUSE_LEFT_UP:
Dragging = false;
return true;
case EMIE_MOUSE_MOVED:
if ( !event.MouseInput.isLeftPressed () )
Dragging = false;
if (Dragging)
{
// gui window should not be dragged outside its parent
if (Parent)
if (event.MouseInput.X < Parent->getAbsolutePosition().UpperLeftCorner.X +1 ||
event.MouseInput.Y < Parent->getAbsolutePosition().UpperLeftCorner.Y +1 ||
event.MouseInput.X > Parent->getAbsolutePosition().LowerRightCorner.X -1 ||
event.MouseInput.Y > Parent->getAbsolutePosition().LowerRightCorner.Y -1)
return true;
move(core::position2d<s32>(event.MouseInput.X - DragStart.X, event.MouseInput.Y - DragStart.Y));
DragStart.X = event.MouseInput.X;
DragStart.Y = event.MouseInput.Y;
return true;
}
break;
default:
break;
}
default:
break;
}
}
return IGUIElement::OnEvent(event);
}
//! draws the element and its children
void CGUIFileOpenDialog::draw()
{
if (!IsVisible)
return;
IGUISkin* skin = Environment->getSkin();
core::rect<s32> rect = AbsoluteRect;
rect = skin->draw3DWindowBackground(this, true, skin->getColor(EGDC_ACTIVE_BORDER),
rect, &AbsoluteClippingRect);
if (Text.size())
{
rect.UpperLeftCorner.X += 2;
rect.LowerRightCorner.X -= skin->getSize(EGDS_WINDOW_BUTTON_WIDTH) + 5;
IGUIFont* font = skin->getFont(EGDF_WINDOW);
if (font)
font->draw(Text.c_str(), rect,
skin->getColor(EGDC_ACTIVE_CAPTION),
false, true, &AbsoluteClippingRect);
}
IGUIElement::draw();
}
//! fills the listbox with files.
void CGUIFileOpenDialog::fillListBox()
{
IGUISkin *skin = Environment->getSkin();
if (!FileSystem || !FileBox || !skin)
return;
if (FileList)
FileList->drop();
FileBox->clear();
FileList = FileSystem->createFileList();
core::stringw s;
#if !defined(_IRR_WINDOWS_CE_PLATFORM_)
setlocale(LC_ALL,"");
#endif
if (FileList)
{
for (u32 i=0; i < FileList->getFileCount(); ++i)
{
#ifndef _IRR_WCHAR_FILESYSTEM
const c8 *cs = (const c8 *)FileList->getFileName(i).c_str();
wchar_t *ws = new wchar_t[strlen(cs) + 1];
int len = mbstowcs(ws,cs,strlen(cs));
ws[len] = 0;
s = ws;
delete [] ws;
#else
s = FileList->getFileName(i).c_str();
#endif
FileBox->addItem(s.c_str(), skin->getIcon(FileList->isDirectory(i) ? EGDI_DIRECTORY : EGDI_FILE));
}
}
if (FileNameText)
{
#ifndef _IRR_WCHAR_FILESYSTEM
const c8 *cs = (const c8 *)FileSystem->getWorkingDirectory().c_str();
wchar_t *ws = new wchar_t[strlen(cs) + 1];
int len = mbstowcs(ws,cs,strlen(cs));
ws[len] = 0;
s = ws;
delete [] ws;
#else
s = FileSystem->getWorkingDirectory();
#endif
FileDirectory = s;
FileNameText->setText(s.c_str());
}
}
//! sends the event that the file has been selected.
void CGUIFileOpenDialog::sendSelectedEvent( EGUI_EVENT_TYPE type)
{
SEvent event;
event.EventType = EET_GUI_EVENT;
event.GUIEvent.Caller = this;
event.GUIEvent.Element = 0;
event.GUIEvent.EventType = type;
Parent->OnEvent(event);
}
//! sends the event that the file choose process has been canceld
void CGUIFileOpenDialog::sendCancelEvent()
{
SEvent event;
event.EventType = EET_GUI_EVENT;
event.GUIEvent.Caller = this;
event.GUIEvent.Element = 0;
event.GUIEvent.EventType = EGET_FILE_CHOOSE_DIALOG_CANCELLED;
Parent->OnEvent(event);
}
} // end namespace gui
} // end namespace irr
#endif // _IRR_COMPILE_WITH_GUI_
|
paupawsan/Irrlicht
|
cb7424c0b5f7484644446a091fd410570d0a821a
|
Add hint about supported zip file encryption and compression.
|
diff --git a/include/IFileSystem.h b/include/IFileSystem.h
index ed798c8..39e49ad 100644
--- a/include/IFileSystem.h
+++ b/include/IFileSystem.h
@@ -1,317 +1,319 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __I_FILE_SYSTEM_H_INCLUDED__
#define __I_FILE_SYSTEM_H_INCLUDED__
#include "IReferenceCounted.h"
#include "IXMLReader.h"
#include "IFileArchive.h"
namespace irr
{
namespace video
{
class IVideoDriver;
} // end namespace video
namespace io
{
class IReadFile;
class IWriteFile;
class IFileList;
class IXMLWriter;
class IAttributes;
//! The FileSystem manages files and archives and provides access to them.
/** It manages where files are, so that modules which use the the IO do not
need to know where every file is located. A file could be in a .zip-Archive or
as file on disk, using the IFileSystem makes no difference to this. */
class IFileSystem : public virtual IReferenceCounted
{
public:
//! Opens a file for read access.
/** \param filename: Name of file to open.
- \return Returns a pointer to the created file interface.
+ \return Pointer to the created file interface.
The returned pointer should be dropped when no longer needed.
See IReferenceCounted::drop() for more information. */
virtual IReadFile* createAndOpenFile(const path& filename) =0;
//! Creates an IReadFile interface for accessing memory like a file.
/** This allows you to use a pointer to memory where an IReadFile is requested.
\param memory: A pointer to the start of the file in memory
\param len: The length of the memory in bytes
\param fileName: The name given to this file
\param deleteMemoryWhenDropped: True if the memory should be deleted
along with the IReadFile when it is dropped.
- \return Returns a pointer to the created file interface.
+ \return Pointer to the created file interface.
The returned pointer should be dropped when no longer needed.
See IReferenceCounted::drop() for more information.
*/
virtual IReadFile* createMemoryReadFile(void* memory, s32 len, const path& fileName, bool deleteMemoryWhenDropped=false) =0;
//! Creates an IReadFile interface for accessing files inside files.
/** This is useful e.g. for archives.
\param fileName: The name given to this file
\param alreadyOpenedFile: Pointer to the enclosing file
\param pos: Start of the file inside alreadyOpenedFile
\param areaSize: The length of the file
\return A pointer to the created file interface.
The returned pointer should be dropped when no longer needed.
See IReferenceCounted::drop() for more information.
*/
virtual IReadFile* createLimitReadFile(const path& fileName,
IReadFile* alreadyOpenedFile, long pos, long areaSize) =0;
//! Creates an IWriteFile interface for accessing memory like a file.
/** This allows you to use a pointer to memory where an IWriteFile is requested.
You are responsible for allocating enough memory.
\param memory: A pointer to the start of the file in memory (allocated by you)
\param len: The length of the memory in bytes
\param fileName: The name given to this file
\param deleteMemoryWhenDropped: True if the memory should be deleted
along with the IWriteFile when it is dropped.
- \return Returns a pointer to the created file interface.
+ \return Pointer to the created file interface.
The returned pointer should be dropped when no longer needed.
See IReferenceCounted::drop() for more information.
*/
virtual IWriteFile* createMemoryWriteFile(void* memory, s32 len, const path& fileName, bool deleteMemoryWhenDropped=false) =0;
//! Opens a file for write access.
/** \param filename: Name of file to open.
\param append: If the file already exist, all write operations are
appended to the file.
- \return Returns a pointer to the created file interface. 0 is returned, if the
+ \return Pointer to the created file interface. 0 is returned, if the
file could not created or opened for writing.
The returned pointer should be dropped when no longer needed.
See IReferenceCounted::drop() for more information. */
virtual IWriteFile* createAndWriteFile(const path& filename, bool append=false) =0;
//! Adds an archive to the file system.
/** After calling this, the Irrlicht Engine will also search and open
files directly from this archive. This is useful for hiding data from
the end user, speeding up file access and making it possible to access
for example Quake3 .pk3 files, which are just renamed .zip files. By
default Irrlicht supports ZIP, PAK, TAR, PNK, and directories as
archives. You can provide your own archive types by implementing
IArchiveLoader and passing an instance to addArchiveLoader.
+ Irrlicht supports AES-encrypted zip files, and the advanced compression
+ techniques lzma and bzip2.
\param filename: Filename of the archive to add to the file system.
\param ignoreCase: If set to true, files in the archive can be accessed without
writing all letters in the right case.
\param ignorePaths: If set to true, files in the added archive can be accessed
without its complete path.
\param archiveType: If no specific E_FILE_ARCHIVE_TYPE is selected then
the type of archive will depend on the extension of the file name. If
you use a different extension then you can use this parameter to force
a specific type of archive.
\param password An optional password, which is used in case of encrypted archives.
- \return Returns true if the archive was added successfully, false if not. */
+ \return True if the archive was added successfully, false if not. */
virtual bool addFileArchive(const path& filename, bool ignoreCase=true,
bool ignorePaths=true,
E_FILE_ARCHIVE_TYPE archiveType=EFAT_UNKNOWN,
const core::stringc& password="") =0;
//! Adds an external archive loader to the engine.
/** Use this function to add support for new archive types to the
engine, for example proprietary or encrypted file storage. */
virtual void addArchiveLoader(IArchiveLoader* loader) =0;
- //! Returns the number of archives currently attached to the file system
+ //! Get the number of archives currently attached to the file system
virtual u32 getFileArchiveCount() const =0;
//! Removes an archive from the file system.
/** This will close the archive and free any file handles, but will not close resources which have already
been loaded and are now cached, for example textures and meshes.
\param index: The index of the archive to remove
- \return Returns true on success, false on failure */
+ \return True on success, false on failure */
virtual bool removeFileArchive(u32 index) =0;
//! Removes an archive from the file system.
/** This will close the archive and free any file handles, but will not
close resources which have already been loaded and are now cached, for
example textures and meshes.
\param filename The archive of the given name will be removed
- \return Returns true on success, false on failure */
+ \return True on success, false on failure */
virtual bool removeFileArchive(const path& filename) =0;
//! Changes the search order of attached archives.
/**
\param sourceIndex: The index of the archive to change
\param relative: The relative change in position, archives with a lower index are searched first */
virtual bool moveFileArchive(u32 sourceIndex, s32 relative) =0;
- //! Returns the archive at a given index.
+ //! Get the archive at a given index.
virtual IFileArchive* getFileArchive(u32 index) =0;
//! Adds a zip archive to the file system.
/** \deprecated This function is provided for compatibility
with older versions of Irrlicht and may be removed in future versions,
you should use addFileArchive instead.
After calling this, the Irrlicht Engine will search and open files directly from this archive too.
This is useful for hiding data from the end user, speeding up file access and making it possible to
access for example Quake3 .pk3 files, which are no different than .zip files.
\param filename: Filename of the zip archive to add to the file system.
\param ignoreCase: If set to true, files in the archive can be accessed without
writing all letters in the right case.
\param ignorePaths: If set to true, files in the added archive can be accessed
without its complete path.
- \return Returns true if the archive was added successfully, false if not. */
+ \return True if the archive was added successfully, false if not. */
virtual bool addZipFileArchive(const c8* filename, bool ignoreCase=true, bool ignorePaths=true)
{
return addFileArchive(filename, ignoreCase, ignorePaths, EFAT_ZIP);
}
//! Adds an unzipped archive (or basedirectory with subdirectories..) to the file system.
/** \deprecated This function is provided for compatibility
with older versions of Irrlicht and may be removed in future versions,
you should use addFileArchive instead.
Useful for handling data which will be in a zip file
\param filename: Filename of the unzipped zip archive base directory to add to the file system.
\param ignoreCase: If set to true, files in the archive can be accessed without
writing all letters in the right case.
\param ignorePaths: If set to true, files in the added archive can be accessed
without its complete path.
- \return Returns true if the archive was added successful, false if not. */
+ \return True if the archive was added successful, false if not. */
virtual bool addFolderFileArchive(const c8* filename, bool ignoreCase=true, bool ignorePaths=true)
{
return addFileArchive(filename, ignoreCase, ignorePaths, EFAT_FOLDER);
}
//! Adds a pak archive to the file system.
/** \deprecated This function is provided for compatibility
with older versions of Irrlicht and may be removed in future versions,
you should use addFileArchive instead.
After calling this, the Irrlicht Engine will search and open files directly from this archive too.
This is useful for hiding data from the end user, speeding up file access and making it possible to
access for example Quake2/KingPin/Hexen2 .pak files
\param filename: Filename of the pak archive to add to the file system.
\param ignoreCase: If set to true, files in the archive can be accessed without
writing all letters in the right case.
\param ignorePaths: If set to true, files in the added archive can be accessed
without its complete path.(should not use with Quake2 paks
- \return Returns true if the archive was added successful, false if not. */
+ \return True if the archive was added successful, false if not. */
virtual bool addPakFileArchive(const c8* filename, bool ignoreCase=true, bool ignorePaths=true)
{
return addFileArchive(filename, ignoreCase, ignorePaths, EFAT_PAK);
}
//! Get the current working directory.
/** \return Current working directory as a string. */
virtual const path& getWorkingDirectory() =0;
//! Changes the current working directory.
/** \param newDirectory: A string specifying the new working directory.
The string is operating system dependent. Under Windows it has
the form "<drive>:\<directory>\<sudirectory>\<..>". An example would be: "C:\Windows\"
\return True if successful, otherwise false. */
virtual bool changeWorkingDirectoryTo(const path& newDirectory) =0;
//! Converts a relative path to an absolute (unique) path, resolving symbolic links if required
/** \param filename Possibly relative file or directory name to query.
\result Absolute filename which points to the same file. */
virtual path getAbsolutePath(const path& filename) const =0;
- //! Returns the directory a file is located in.
+ //! Get the directory a file is located in.
/** \param filename: The file to get the directory from.
\return String containing the directory of the file. */
virtual path getFileDir(const path& filename) const =0;
- //! Returns the base part of a filename, i.e. the name without the directory part.
+ //! Get the base part of a filename, i.e. the name without the directory part.
/** If no directory is prefixed, the full name is returned.
\param filename: The file to get the basename from
\param keepExtension True if filename with extension is returned otherwise everything
after the final '.' is removed as well. */
virtual path getFileBasename(const path& filename, bool keepExtension=true) const =0;
//! flatten a path and file name for example: "/you/me/../." becomes "/you"
virtual path& flattenFilename(path& directory, const path& root="/") const =0;
//! Creates a list of files and directories in the current working directory and returns it.
/** \return a Pointer to the created IFileList is returned. After the list has been used
it has to be deleted using its IFileList::drop() method.
See IReferenceCounted::drop() for more information. */
virtual IFileList* createFileList() =0;
//! Creates an empty filelist
/** \return a Pointer to the created IFileList is returned. After the list has been used
it has to be deleted using its IFileList::drop() method.
See IReferenceCounted::drop() for more information. */
virtual IFileList* createEmptyFileList(const io::path& path, bool ignoreCase, bool ignorePaths) =0;
//! Set the active type of file system.
virtual EFileSystemType setFileListSystem(EFileSystemType listType) =0;
//! Determines if a file exists and could be opened.
/** \param filename is the string identifying the file which should be tested for existence.
- \return Returns true if file exists, and false if it does not exist or an error occured. */
+ \return True if file exists, and false if it does not exist or an error occured. */
virtual bool existFile(const path& filename) const =0;
//! Creates a XML Reader from a file which returns all parsed strings as wide characters (wchar_t*).
/** Use createXMLReaderUTF8() if you prefer char* instead of wchar_t*. See IIrrXMLReader for
more information on how to use the parser.
\return 0, if file could not be opened, otherwise a pointer to the created
IXMLReader is returned. After use, the reader
has to be deleted using its IXMLReader::drop() method.
See IReferenceCounted::drop() for more information. */
virtual IXMLReader* createXMLReader(const path& filename) =0;
//! Creates a XML Reader from a file which returns all parsed strings as wide characters (wchar_t*).
/** Use createXMLReaderUTF8() if you prefer char* instead of wchar_t*. See IIrrXMLReader for
more information on how to use the parser.
\return 0, if file could not be opened, otherwise a pointer to the created
IXMLReader is returned. After use, the reader
has to be deleted using its IXMLReader::drop() method.
See IReferenceCounted::drop() for more information. */
virtual IXMLReader* createXMLReader(IReadFile* file) =0;
//! Creates a XML Reader from a file which returns all parsed strings as ASCII/UTF-8 characters (char*).
/** Use createXMLReader() if you prefer wchar_t* instead of char*. See IIrrXMLReader for
more information on how to use the parser.
\return 0, if file could not be opened, otherwise a pointer to the created
IXMLReader is returned. After use, the reader
has to be deleted using its IXMLReaderUTF8::drop() method.
See IReferenceCounted::drop() for more information. */
virtual IXMLReaderUTF8* createXMLReaderUTF8(const path& filename) =0;
//! Creates a XML Reader from a file which returns all parsed strings as ASCII/UTF-8 characters (char*).
/** Use createXMLReader() if you prefer wchar_t* instead of char*. See IIrrXMLReader for
more information on how to use the parser.
\return 0, if file could not be opened, otherwise a pointer to the created
IXMLReader is returned. After use, the reader
has to be deleted using its IXMLReaderUTF8::drop() method.
See IReferenceCounted::drop() for more information. */
virtual IXMLReaderUTF8* createXMLReaderUTF8(IReadFile* file) =0;
//! Creates a XML Writer from a file.
/** \return 0, if file could not be opened, otherwise a pointer to the created
IXMLWriter is returned. After use, the reader
has to be deleted using its IXMLWriter::drop() method.
See IReferenceCounted::drop() for more information. */
virtual IXMLWriter* createXMLWriter(const path& filename) =0;
//! Creates a XML Writer from a file.
/** \return 0, if file could not be opened, otherwise a pointer to the created
IXMLWriter is returned. After use, the reader
has to be deleted using its IXMLWriter::drop() method.
See IReferenceCounted::drop() for more information. */
virtual IXMLWriter* createXMLWriter(IWriteFile* file) =0;
//! Creates a new empty collection of attributes, usable for serialization and more.
/** \param driver: Video driver to be used to load textures when specified as attribute values.
Can be null to prevent automatic texture loading by attributes.
\return Pointer to the created object.
If you no longer need the object, you should call IAttributes::drop().
See IReferenceCounted::drop() for more information. */
virtual IAttributes* createEmptyAttributes(video::IVideoDriver* driver=0) =0;
};
} // end namespace io
} // end namespace irr
#endif
|
paupawsan/Irrlicht
|
3232c659a752079f0f9eae531775171c5a935412
|
Avoid direct3d warning if no surface is intentionally cleared.
|
diff --git a/source/Irrlicht/CD3D8Driver.cpp b/source/Irrlicht/CD3D8Driver.cpp
index 77e4893..a92b8a4 100644
--- a/source/Irrlicht/CD3D8Driver.cpp
+++ b/source/Irrlicht/CD3D8Driver.cpp
@@ -1,957 +1,960 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "IrrCompileConfig.h"
#define _IRR_DONT_DO_MEMORY_DEBUGGING_HERE
#include "CD3D8Driver.h"
#ifdef _IRR_COMPILE_WITH_DIRECT3D_8_
#include "os.h"
#include "S3DVertex.h"
#include "CD3D8Texture.h"
#include "CImage.h"
#include "CD3D8MaterialRenderer.h"
#include "CD3D8ShaderMaterialRenderer.h"
#include "CD3D8NormalMapRenderer.h"
#include "CD3D8ParallaxMapRenderer.h"
namespace irr
{
namespace video
{
//! constructor
CD3D8Driver::CD3D8Driver(const core::dimension2d<u32>& screenSize, HWND window,
bool fullscreen, bool stencilbuffer,
io::IFileSystem* io, bool pureSoftware, bool vsync)
: CNullDriver(io, screenSize), CurrentRenderMode(ERM_NONE),
ResetRenderStates(true), Transformation3DChanged(false), StencilBuffer(stencilbuffer),
D3DLibrary(0), pID3D(0), pID3DDevice(0), PrevRenderTarget(0),
WindowId(0), SceneSourceRect(0),
LastVertexType((video::E_VERTEX_TYPE)-1), MaxTextureUnits(0), MaxUserClipPlanes(0),
MaxLightDistance(0), LastSetLight(-1), DeviceLost(false),
DriverWasReset(true)
{
#ifdef _DEBUG
setDebugName("CD3D8Driver");
#endif
printVersion();
for (u32 i=0; i<MATERIAL_MAX_TEXTURES; ++i)
CurrentTexture[i] = 0;
MaxLightDistance=sqrtf(FLT_MAX);
// create sphere map matrix
SphereMapMatrixD3D8._11 = 0.5f; SphereMapMatrixD3D8._12 = 0.0f;
SphereMapMatrixD3D8._13 = 0.0f; SphereMapMatrixD3D8._14 = 0.0f;
SphereMapMatrixD3D8._21 = 0.0f; SphereMapMatrixD3D8._22 =-0.5f;
SphereMapMatrixD3D8._23 = 0.0f; SphereMapMatrixD3D8._24 = 0.0f;
SphereMapMatrixD3D8._31 = 0.0f; SphereMapMatrixD3D8._32 = 0.0f;
SphereMapMatrixD3D8._33 = 1.0f; SphereMapMatrixD3D8._34 = 0.0f;
SphereMapMatrixD3D8._41 = 0.5f; SphereMapMatrixD3D8._42 = 0.5f;
SphereMapMatrixD3D8._43 = 0.0f; SphereMapMatrixD3D8._44 = 1.0f;
UnitMatrixD3D8 = *(D3DMATRIX*)((void*)core::IdentityMatrix.pointer());
// init direct 3d is done in the factory function
}
//! destructor
CD3D8Driver::~CD3D8Driver()
{
deleteMaterialRenders();
// drop d3d8
if (pID3DDevice)
pID3DDevice->Release();
if (pID3D)
pID3D->Release();
}
void CD3D8Driver::createMaterialRenderers()
{
// create D3D8 material renderers
addAndDropMaterialRenderer(new CD3D8MaterialRenderer_SOLID(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D8MaterialRenderer_SOLID_2_LAYER(pID3DDevice, this));
// add the same renderer for all lightmap types
CD3D8MaterialRenderer_LIGHTMAP* lmr = new CD3D8MaterialRenderer_LIGHTMAP(pID3DDevice, this);
addMaterialRenderer(lmr); // for EMT_LIGHTMAP:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_ADD:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_M2:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_M4:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_LIGHTING:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_LIGHTING_M2:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_LIGHTING_M4:
lmr->drop();
// add remaining material renderers
addAndDropMaterialRenderer(new CD3D8MaterialRenderer_DETAIL_MAP(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D8MaterialRenderer_SPHERE_MAP(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D8MaterialRenderer_REFLECTION_2_LAYER(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D8MaterialRenderer_TRANSPARENT_ADD_COLOR(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D8MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D8MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL_REF(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D8MaterialRenderer_TRANSPARENT_VERTEX_ALPHA(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D8MaterialRenderer_TRANSPARENT_REFLECTION_2_LAYER(pID3DDevice, this));
// add normal map renderers
s32 tmp = 0;
video::IMaterialRenderer* renderer = 0;
renderer = new CD3D8NormalMapRenderer(pID3DDevice, this, tmp,
MaterialRenderers[EMT_SOLID].Renderer);
renderer->drop();
renderer = new CD3D8NormalMapRenderer(pID3DDevice, this, tmp,
MaterialRenderers[EMT_TRANSPARENT_ADD_COLOR].Renderer);
renderer->drop();
renderer = new CD3D8NormalMapRenderer(pID3DDevice, this, tmp,
MaterialRenderers[EMT_TRANSPARENT_VERTEX_ALPHA].Renderer);
renderer->drop();
// add parallax map renderers
renderer = new CD3D8ParallaxMapRenderer(pID3DDevice, this, tmp,
MaterialRenderers[EMT_SOLID].Renderer);
renderer->drop();
renderer = new CD3D8ParallaxMapRenderer(pID3DDevice, this, tmp,
MaterialRenderers[EMT_TRANSPARENT_ADD_COLOR].Renderer);
renderer->drop();
renderer = new CD3D8ParallaxMapRenderer(pID3DDevice, this, tmp,
MaterialRenderers[EMT_TRANSPARENT_VERTEX_ALPHA].Renderer);
renderer->drop();
// add basic 1 texture blending
addAndDropMaterialRenderer(new CD3D8MaterialRenderer_ONETEXTURE_BLEND(pID3DDevice, this));
}
//! initialises the Direct3D API
bool CD3D8Driver::initDriver(const core::dimension2d<u32>& screenSize,
HWND hwnd, u32 bits, bool fullScreen, bool pureSoftware,
bool highPrecisionFPU, bool vsync, u8 antiAlias)
{
HRESULT hr;
typedef IDirect3D8 * (__stdcall *D3DCREATETYPE)(UINT);
#if defined( _IRR_XBOX_PLATFORM_)
D3DCREATETYPE d3dCreate = (D3DCREATETYPE) &Direct3DCreate8;
#else
D3DLibrary = LoadLibrary( __TEXT("d3d8.dll") );
if (!D3DLibrary)
{
os::Printer::log("Error, could not load d3d8.dll.", ELL_ERROR);
return false;
}
D3DCREATETYPE d3dCreate = (D3DCREATETYPE) GetProcAddress(D3DLibrary, "Direct3DCreate8");
if (!d3dCreate)
{
os::Printer::log("Error, could not get proc adress of Direct3DCreate8.", ELL_ERROR);
return false;
}
#endif
//just like pID3D = Direct3DCreate8(D3D_SDK_VERSION);
pID3D = (*d3dCreate)(D3D_SDK_VERSION);
if (!pID3D)
{
os::Printer::log("Error initializing D3D.", ELL_ERROR);
return false;
}
// print device information
D3DADAPTER_IDENTIFIER8 dai;
if (!FAILED(pID3D->GetAdapterIdentifier(D3DADAPTER_DEFAULT, D3DENUM_NO_WHQL_LEVEL, &dai)))
{
char tmp[512];
s32 Product = HIWORD(dai.DriverVersion.HighPart);
s32 Version = LOWORD(dai.DriverVersion.HighPart);
s32 SubVersion = HIWORD(dai.DriverVersion.LowPart);
s32 Build = LOWORD(dai.DriverVersion.LowPart);
sprintf(tmp, "%s %s %d.%d.%d.%d", dai.Description, dai.Driver, Product, Version,
SubVersion, Build);
os::Printer::log(tmp, ELL_INFORMATION);
}
D3DDISPLAYMODE d3ddm;
hr = pID3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm);
if (FAILED(hr))
{
os::Printer::log("Error: Could not get Adapter Display mode.", ELL_ERROR);
return false;
}
ZeroMemory(&present, sizeof(present));
present.SwapEffect = D3DSWAPEFFECT_DISCARD;
present.Windowed = TRUE;
present.BackBufferFormat = d3ddm.Format;
present.EnableAutoDepthStencil = TRUE;
if (fullScreen)
{
present.SwapEffect = D3DSWAPEFFECT_FLIP;
present.Windowed = FALSE;
present.BackBufferWidth = screenSize.Width;
present.BackBufferHeight = screenSize.Height;
present.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
present.FullScreen_PresentationInterval = vsync ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
if (bits == 32)
present.BackBufferFormat = D3DFMT_X8R8G8B8;
else
present.BackBufferFormat = D3DFMT_R5G6B5;
}
D3DDEVTYPE devtype = D3DDEVTYPE_HAL;
#ifndef _IRR_D3D_NO_SHADER_DEBUGGING
devtype = D3DDEVTYPE_REF;
#endif
// enable anti alias if possible and whished
if (antiAlias > 0)
{
if(antiAlias > 16)
antiAlias = 16;
while(antiAlias > 0)
{
if(!FAILED(pID3D->CheckDeviceMultiSampleType(D3DADAPTER_DEFAULT,
devtype , present.BackBufferFormat, !fullScreen,
(D3DMULTISAMPLE_TYPE)antiAlias)))
{
present.MultiSampleType = (D3DMULTISAMPLE_TYPE)antiAlias;
present.SwapEffect = D3DSWAPEFFECT_DISCARD;
break;
}
--antiAlias;
}
if(antiAlias==0)
os::Printer::log("Anti aliasing disabled because hardware/driver lacks necessary caps.", ELL_WARNING);
}
// check stencil buffer compatibility
if (StencilBuffer)
{
present.AutoDepthStencilFormat = D3DFMT_D24S8;
if(FAILED(pID3D->CheckDeviceFormat(D3DADAPTER_DEFAULT, devtype,
present.BackBufferFormat, D3DUSAGE_DEPTHSTENCIL,
D3DRTYPE_SURFACE, present.AutoDepthStencilFormat)))
{
#if !defined( _IRR_XBOX_PLATFORM_)
present.AutoDepthStencilFormat = D3DFMT_D24X4S4;
if(FAILED(pID3D->CheckDeviceFormat(D3DADAPTER_DEFAULT, devtype,
present.BackBufferFormat, D3DUSAGE_DEPTHSTENCIL,
D3DRTYPE_SURFACE, present.AutoDepthStencilFormat)))
{
present.AutoDepthStencilFormat = D3DFMT_D15S1;
if(FAILED(pID3D->CheckDeviceFormat(D3DADAPTER_DEFAULT, devtype,
present.BackBufferFormat, D3DUSAGE_DEPTHSTENCIL,
D3DRTYPE_SURFACE, present.AutoDepthStencilFormat)))
{
os::Printer::log("Device does not support stencilbuffer, disabling stencil buffer.", ELL_WARNING);
StencilBuffer = false;
}
}
#endif
}
else
if(FAILED(pID3D->CheckDepthStencilMatch(D3DADAPTER_DEFAULT, devtype,
present.BackBufferFormat, present.BackBufferFormat, present.AutoDepthStencilFormat)))
{
os::Printer::log("Depth-stencil format is not compatible with display format, disabling stencil buffer.", ELL_WARNING);
StencilBuffer = false;
}
}
// do not use else here to cope with flag change in previous block
if (!StencilBuffer)
{
#if !defined( _IRR_XBOX_PLATFORM_)
present.AutoDepthStencilFormat = D3DFMT_D32;
if(FAILED(pID3D->CheckDeviceFormat(D3DADAPTER_DEFAULT, devtype,
present.BackBufferFormat, D3DUSAGE_DEPTHSTENCIL,
D3DRTYPE_SURFACE, present.AutoDepthStencilFormat)))
{
present.AutoDepthStencilFormat = D3DFMT_D24X8;
if(FAILED(pID3D->CheckDeviceFormat(D3DADAPTER_DEFAULT, devtype,
present.BackBufferFormat, D3DUSAGE_DEPTHSTENCIL,
D3DRTYPE_SURFACE, present.AutoDepthStencilFormat)))
{
present.AutoDepthStencilFormat = D3DFMT_D16;
if(FAILED(pID3D->CheckDeviceFormat(D3DADAPTER_DEFAULT, devtype,
present.BackBufferFormat, D3DUSAGE_DEPTHSTENCIL,
D3DRTYPE_SURFACE, present.AutoDepthStencilFormat)))
{
os::Printer::log("Device does not support required depth buffer.", ELL_WARNING);
return false;
}
}
}
#else
present.AutoDepthStencilFormat = D3DFMT_D16;
if(FAILED(pID3D->CheckDeviceFormat(D3DADAPTER_DEFAULT, devtype,
present.BackBufferFormat, D3DUSAGE_DEPTHSTENCIL,
D3DRTYPE_SURFACE, present.AutoDepthStencilFormat)))
{
os::Printer::log("Device does not support required depth buffer.", ELL_WARNING);
return false;
}
#endif
}
// create device
#if defined( _IRR_XBOX_PLATFORM_)
DWORD fpuPrecision = 0;
#else
DWORD fpuPrecision = highPrecisionFPU ? D3DCREATE_FPU_PRESERVE : 0;
#endif
if (pureSoftware)
{
hr = pID3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_REF, hwnd,
fpuPrecision | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &present, &pID3DDevice);
if (FAILED(hr))
os::Printer::log("Was not able to create Direct3D8 software device.", ELL_ERROR);
}
else
{
hr = pID3D->CreateDevice(D3DADAPTER_DEFAULT, devtype, hwnd,
fpuPrecision | D3DCREATE_HARDWARE_VERTEXPROCESSING, &present, &pID3DDevice);
if(FAILED(hr))
hr = pID3D->CreateDevice(D3DADAPTER_DEFAULT, devtype, hwnd,
fpuPrecision | D3DCREATE_MIXED_VERTEXPROCESSING , &present, &pID3DDevice);
if(FAILED(hr))
hr = pID3D->CreateDevice(D3DADAPTER_DEFAULT, devtype, hwnd,
fpuPrecision | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &present, &pID3DDevice);
if (FAILED(hr))
os::Printer::log("Was not able to create Direct3D8 device.", ELL_ERROR);
}
if (!pID3DDevice)
{
os::Printer::log("Was not able to create Direct3D8 device.", ELL_ERROR);
return false;
}
// get caps
pID3DDevice->GetDeviceCaps(&Caps);
if (StencilBuffer &&
(!(Caps.StencilCaps & D3DSTENCILCAPS_DECRSAT) ||
!(Caps.StencilCaps & D3DSTENCILCAPS_INCRSAT) ||
!(Caps.StencilCaps & D3DSTENCILCAPS_KEEP)))
{
os::Printer::log("Device not able to use stencil buffer, disabling stencil buffer.", ELL_WARNING);
StencilBuffer = false;
}
// set default vertex shader
setVertexShader(EVT_STANDARD);
// enable antialiasing
if (antiAlias>0)
pID3DDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
// set fog mode
setFog(FogColor, FogType, FogStart, FogEnd, FogDensity, PixelFog, RangeFog);
// set exposed data
ExposedData.D3D8.D3D8 = pID3D;
ExposedData.D3D8.D3DDev8 = pID3DDevice;
ExposedData.D3D8.HWnd = hwnd;
ResetRenderStates = true;
// create materials
createMaterialRenderers();
MaxTextureUnits = core::min_((u32)Caps.MaxSimultaneousTextures, MATERIAL_MAX_TEXTURES);
MaxUserClipPlanes = (u32)Caps.MaxUserClipPlanes;
// set the renderstates
setRenderStates3DMode();
// so far so good.
return true;
}
//! applications must call this method before performing any rendering. returns false if failed.
bool CD3D8Driver::beginScene(bool backBuffer, bool zBuffer, SColor color,
const SExposedVideoData& videoData, core::rect<s32>* sourceRect)
{
CNullDriver::beginScene(backBuffer, zBuffer, color, videoData, sourceRect);
WindowId = (HWND)videoData.D3D8.HWnd;
SceneSourceRect = sourceRect;
if (!pID3DDevice)
return false;
HRESULT hr;
if (DeviceLost)
{
#ifndef _IRR_XBOX_PLATFORM_
if(FAILED(hr = pID3DDevice->TestCooperativeLevel()))
{
if (hr == D3DERR_DEVICELOST)
{
Sleep(100);
hr = pID3DDevice->TestCooperativeLevel();
if (hr == D3DERR_DEVICELOST)
return false;
}
if ((hr == D3DERR_DEVICENOTRESET) && !reset())
return false;
}
#endif
}
DWORD flags = 0;
if (backBuffer)
flags |= D3DCLEAR_TARGET;
if (zBuffer)
flags |= D3DCLEAR_ZBUFFER;
if (StencilBuffer)
flags |= D3DCLEAR_STENCIL;
- hr = pID3DDevice->Clear( 0, NULL, flags, color.color, 1.0, 0);
- if (FAILED(hr))
- os::Printer::log("Direct3D8 clear failed.", ELL_WARNING);
+ if (flags)
+ {
+ hr = pID3DDevice->Clear( 0, NULL, flags, color.color, 1.0, 0);
+ if (FAILED(hr))
+ os::Printer::log("Direct3D8 clear failed.", ELL_WARNING);
+ }
hr = pID3DDevice->BeginScene();
if (FAILED(hr))
{
os::Printer::log("Direct3D8 begin scene failed.", ELL_WARNING);
return false;
}
return true;
}
//! applications must call this method after performing any rendering. returns false if failed.
bool CD3D8Driver::endScene()
{
CNullDriver::endScene();
DriverWasReset=false;
HRESULT hr = pID3DDevice->EndScene();
if (FAILED(hr))
{
os::Printer::log("DIRECT3D8 end scene failed.", ELL_WARNING);
return false;
}
RECT* srcRct = 0;
RECT sourceRectData;
if ( SceneSourceRect)
{
srcRct = &sourceRectData;
sourceRectData.left = SceneSourceRect->UpperLeftCorner.X;
sourceRectData.top = SceneSourceRect->UpperLeftCorner.Y;
sourceRectData.right = SceneSourceRect->LowerRightCorner.X;
sourceRectData.bottom = SceneSourceRect->LowerRightCorner.Y;
}
hr = pID3DDevice->Present(srcRct, NULL, WindowId, NULL);
if (SUCCEEDED(hr))
return true;
if (hr == D3DERR_DEVICELOST)
{
DeviceLost = true;
os::Printer::log("DIRECT3D8 device lost.", ELL_WARNING);
}
else
os::Printer::log("DIRECT3D8 present failed.", ELL_WARNING);
return false;
}
//! resets the device
bool CD3D8Driver::reset()
{
u32 i;
os::Printer::log("Resetting D3D8 device.", ELL_INFORMATION);
for (i=0; i<Textures.size(); ++i)
{
if (Textures[i].Surface->isRenderTarget())
{
IDirect3DTexture8* tex = ((CD3D8Texture*)(Textures[i].Surface))->getDX8Texture();
if (tex)
tex->Release();
}
}
DriverWasReset=true;
HRESULT hr = pID3DDevice->Reset(&present);
for (i=0; i<Textures.size(); ++i)
{
if (Textures[i].Surface->isRenderTarget())
((CD3D8Texture*)(Textures[i].Surface))->createRenderTarget();
}
if (FAILED(hr))
{
if (hr == D3DERR_DEVICELOST)
{
DeviceLost = true;
os::Printer::log("Resetting failed due to device lost.", ELL_WARNING);
}
else
os::Printer::log("Resetting failed.", ELL_WARNING);
return false;
}
DeviceLost = false;
ResetRenderStates = true;
LastVertexType = (E_VERTEX_TYPE)-1;
for (i=0; i<MATERIAL_MAX_TEXTURES; ++i)
CurrentTexture[i] = 0;
setVertexShader(EVT_STANDARD);
setRenderStates3DMode();
setFog(FogColor, FogType, FogStart, FogEnd, FogDensity, PixelFog, RangeFog);
setAmbientLight(AmbientLight);
return true;
}
//! queries the features of the driver, returns true if feature is available
bool CD3D8Driver::queryFeature(E_VIDEO_DRIVER_FEATURE feature) const
{
if (!FeatureEnabled[feature])
return false;
switch (feature)
{
case EVDF_RENDER_TO_TARGET:
case EVDF_MULTITEXTURE:
case EVDF_BILINEAR_FILTER:
return true;
case EVDF_HARDWARE_TL:
return (Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) != 0;
case EVDF_MIP_MAP:
return (Caps.TextureCaps & D3DPTEXTURECAPS_MIPMAP) != 0;
case EVDF_STENCIL_BUFFER:
return StencilBuffer && Caps.StencilCaps;
case EVDF_VERTEX_SHADER_1_1:
return Caps.VertexShaderVersion >= D3DVS_VERSION(1,1);
case EVDF_VERTEX_SHADER_2_0:
return Caps.VertexShaderVersion >= D3DVS_VERSION(2,0);
case EVDF_VERTEX_SHADER_3_0:
return Caps.VertexShaderVersion >= D3DVS_VERSION(3,0);
case EVDF_PIXEL_SHADER_1_1:
return Caps.PixelShaderVersion >= D3DPS_VERSION(1,1);
case EVDF_PIXEL_SHADER_1_2:
return Caps.PixelShaderVersion >= D3DPS_VERSION(1,2);
case EVDF_PIXEL_SHADER_1_3:
return Caps.PixelShaderVersion >= D3DPS_VERSION(1,3);
case EVDF_PIXEL_SHADER_1_4:
return Caps.PixelShaderVersion >= D3DPS_VERSION(1,4);
case EVDF_PIXEL_SHADER_2_0:
return Caps.PixelShaderVersion >= D3DPS_VERSION(2,0);
case EVDF_PIXEL_SHADER_3_0:
return Caps.PixelShaderVersion >= D3DPS_VERSION(3,0);
case EVDF_TEXTURE_NSQUARE:
return (Caps.TextureCaps & D3DPTEXTURECAPS_SQUAREONLY) == 0;
case EVDF_TEXTURE_NPOT:
return (Caps.TextureCaps & D3DPTEXTURECAPS_POW2) == 0;
case EVDF_COLOR_MASK:
return (Caps.PrimitiveMiscCaps & D3DPMISCCAPS_COLORWRITEENABLE) != 0;
default:
return false;
};
}
//! sets transformation
void CD3D8Driver::setTransform(E_TRANSFORMATION_STATE state,
const core::matrix4& mat)
{
switch(state)
{
case ETS_VIEW:
pID3DDevice->SetTransform(D3DTS_VIEW, (D3DMATRIX*)((void*)mat.pointer()));
Transformation3DChanged = true;
break;
case ETS_WORLD:
pID3DDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)((void*)mat.pointer()));
Transformation3DChanged = true;
break;
case ETS_PROJECTION:
pID3DDevice->SetTransform( D3DTS_PROJECTION, (D3DMATRIX*)((void*)mat.pointer()));
Transformation3DChanged = true;
break;
case ETS_COUNT:
return;
default:
if (state-ETS_TEXTURE_0 < MATERIAL_MAX_TEXTURES)
{
pID3DDevice->SetTextureStageState( state - ETS_TEXTURE_0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2 );
pID3DDevice->SetTransform((D3DTRANSFORMSTATETYPE)(D3DTS_TEXTURE0+ ( state - ETS_TEXTURE_0 )),
(D3DMATRIX*)((void*)mat.pointer()));
}
break;
}
Matrices[state] = mat;
}
//! sets the current Texture
bool CD3D8Driver::setActiveTexture(u32 stage, const video::ITexture* texture)
{
if (CurrentTexture[stage] == texture)
return true;
if (texture && (texture->getDriverType() != EDT_DIRECT3D8))
{
os::Printer::log("Fatal Error: Tried to set a texture not owned by this driver.", ELL_ERROR);
return false;
}
CurrentTexture[stage] = texture;
if (!texture)
{
pID3DDevice->SetTexture(stage, 0);
pID3DDevice->SetTextureStageState( stage, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE );
}
else
{
pID3DDevice->SetTexture(stage, ((const CD3D8Texture*)texture)->getDX8Texture());
}
return true;
}
//! sets a material
void CD3D8Driver::setMaterial(const SMaterial& material)
{
Material = material;
OverrideMaterial.apply(Material);
for (u32 i=0; i<MaxTextureUnits; ++i)
{
setActiveTexture(i, Material.getTexture(i));
setTransform((E_TRANSFORMATION_STATE) ( ETS_TEXTURE_0 + i ),
material.getTextureMatrix(i));
}
}
//! returns a device dependent texture from a software surface (IImage)
video::ITexture* CD3D8Driver::createDeviceDependentTexture(IImage* surface,const io::path& name, void* mipmapData)
{
return new CD3D8Texture(surface, this, TextureCreationFlags, name, mipmapData);
}
//! Enables or disables a texture creation flag.
void CD3D8Driver::setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag,
bool enabled)
{
if (flag == video::ETCF_CREATE_MIP_MAPS && !queryFeature(EVDF_MIP_MAP))
enabled = false;
CNullDriver::setTextureCreationFlag(flag, enabled);
}
//! sets a render target
bool CD3D8Driver::setRenderTarget(video::ITexture* texture,
bool clearBackBuffer, bool clearZBuffer, SColor color)
{
// check for right driver type
if (texture && texture->getDriverType() != EDT_DIRECT3D8)
{
os::Printer::log("Fatal Error: Tried to set a texture not owned by this driver.", ELL_ERROR);
return false;
}
// check for valid render target
CD3D8Texture* tex = (CD3D8Texture*)texture;
if (texture && !tex->isRenderTarget())
{
os::Printer::log("Fatal Error: Tried to set a non render target texture as render target.", ELL_ERROR);
return false;
}
if (texture && (tex->getSize().Width > ScreenSize.Width ||
tex->getSize().Height > ScreenSize.Height ))
{
os::Printer::log("Error: Tried to set a render target texture which is bigger than the screen.", ELL_ERROR);
return false;
}
// check if we should set the previous RT back
bool ret = true;
if (tex == 0)
{
if (PrevRenderTarget)
{
IDirect3DSurface8* dss = 0;
pID3DDevice->GetDepthStencilSurface(&dss);
if (FAILED(pID3DDevice->SetRenderTarget(PrevRenderTarget, dss)))
{
os::Printer::log("Error: Could not set back to previous render target.", ELL_ERROR);
ret = false;
}
if (dss)
dss->Release();
CurrentRendertargetSize = core::dimension2d<u32>(0,0);
PrevRenderTarget->Release();
PrevRenderTarget = 0;
}
}
else
{
// we want to set a new target. so do this.
// store previous target
if (!PrevRenderTarget && (FAILED(pID3DDevice->GetRenderTarget(&PrevRenderTarget))))
{
os::Printer::log("Could not get previous render target.", ELL_ERROR);
return false;
}
// set new render target
IDirect3DSurface8* dss = 0;
pID3DDevice->GetDepthStencilSurface(&dss);
if (FAILED(pID3DDevice->SetRenderTarget(tex->getRenderTargetSurface(), dss)))
{
os::Printer::log("Error: Could not set render target.", ELL_ERROR);
ret = false;
}
if (dss)
dss->Release();
CurrentRendertargetSize = tex->getSize();
}
if (clearBackBuffer || clearZBuffer)
{
DWORD flags = 0;
if (clearBackBuffer)
flags |= D3DCLEAR_TARGET;
if (clearZBuffer)
flags |= D3DCLEAR_ZBUFFER;
pID3DDevice->Clear(0, NULL, flags, color.color, 1.0f, 0);
}
return ret;
}
//! Creates a render target texture.
ITexture* CD3D8Driver::addRenderTargetTexture(const core::dimension2d<u32>& size,
const io::path& name,
const ECOLOR_FORMAT format)
{
ITexture* tex = new CD3D8Texture(this, size, name);
addTexture(tex);
tex->drop();
return tex;
}
//! sets a viewport
void CD3D8Driver::setViewPort(const core::rect<s32>& area)
{
core::rect<s32> vp(area);
core::rect<s32> rendert(0,0, ScreenSize.Width, ScreenSize.Height);
vp.clipAgainst(rendert);
D3DVIEWPORT8 viewPort;
viewPort.X = vp.UpperLeftCorner.X;
viewPort.Y = vp.UpperLeftCorner.Y;
viewPort.Width = vp.getWidth();
viewPort.Height = vp.getHeight();
viewPort.MinZ = 0.0f;
viewPort.MaxZ = 1.0f;
HRESULT hr = D3DERR_INVALIDCALL;
if (vp.getHeight()>0 && vp.getWidth()>0)
hr = pID3DDevice->SetViewport(&viewPort);
if (FAILED(hr))
os::Printer::log("Failed setting the viewport.", ELL_WARNING);
ViewPort = vp;
}
//! gets the area of the current viewport
const core::rect<s32>& CD3D8Driver::getViewPort() const
{
return ViewPort;
}
//! draws a vertex primitive list
void CD3D8Driver::drawVertexPrimitiveList(const void* vertices,
u32 vertexCount, const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType,
E_INDEX_TYPE iType)
{
if (!checkPrimitiveCount(primitiveCount))
return;
CNullDriver::drawVertexPrimitiveList(vertices, vertexCount, indexList, primitiveCount, vType, pType,iType);
if (!vertexCount || !primitiveCount)
return;
draw2D3DVertexPrimitiveList(vertices, vertexCount, indexList, primitiveCount,
vType, pType, iType, true);
}
//! draws a vertex primitive list in 2d
void CD3D8Driver::draw2DVertexPrimitiveList(const void* vertices,
u32 vertexCount, const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType,
E_INDEX_TYPE iType)
{
if (!checkPrimitiveCount(primitiveCount))
return;
CNullDriver::draw2DVertexPrimitiveList(vertices, vertexCount, indexList, primitiveCount, vType, pType,iType);
if (!vertexCount || !primitiveCount)
return;
draw2D3DVertexPrimitiveList(vertices, vertexCount, indexList, primitiveCount,
vType, pType, iType, false);
}
void CD3D8Driver::draw2D3DVertexPrimitiveList(const void* vertices,
u32 vertexCount, const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType,
E_INDEX_TYPE iType, bool is3D)
{
setVertexShader(vType);
const u32 stride = getVertexPitchFromType(vType);
D3DFORMAT indexType=D3DFMT_UNKNOWN;
switch (iType)
{
case (EIT_16BIT):
{
indexType=D3DFMT_INDEX16;
break;
}
case (EIT_32BIT):
{
indexType=D3DFMT_INDEX32;
break;
}
}
if (is3D)
{
if (!setRenderStates3DMode())
return;
}
else
{
if (Material.MaterialType==EMT_ONETEXTURE_BLEND)
{
E_BLEND_FACTOR srcFact;
E_BLEND_FACTOR dstFact;
E_MODULATE_FUNC modulo;
u32 alphaSource;
unpack_texureBlendFunc ( srcFact, dstFact, modulo, alphaSource, Material.MaterialTypeParam);
setRenderStates2DMode(alphaSource&video::EAS_VERTEX_COLOR, (Material.getTexture(0) != 0), (alphaSource&video::EAS_TEXTURE) != 0);
}
else
setRenderStates2DMode(Material.MaterialType==EMT_TRANSPARENT_VERTEX_ALPHA, (Material.getTexture(0) != 0), Material.MaterialType==EMT_TRANSPARENT_ALPHA_CHANNEL);
}
switch (pType)
{
case scene::EPT_POINT_SPRITES:
case scene::EPT_POINTS:
{
f32 tmp=Material.Thickness/getScreenSize().Height;
if (pType==scene::EPT_POINT_SPRITES)
pID3DDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
pID3DDevice->SetRenderState(D3DRS_POINTSCALEENABLE, TRUE);
pID3DDevice->SetRenderState(D3DRS_POINTSIZE, *(DWORD*)(&tmp));
tmp=1.0f;
pID3DDevice->SetRenderState(D3DRS_POINTSCALE_A, *(DWORD*)(&tmp));
pID3DDevice->SetRenderState(D3DRS_POINTSCALE_B, *(DWORD*)(&tmp));
pID3DDevice->SetRenderState(D3DRS_POINTSIZE_MIN, *(DWORD*)(&tmp));
tmp=0.0f;
pID3DDevice->SetRenderState(D3DRS_POINTSCALE_C, *(DWORD*)(&tmp));
pID3DDevice->DrawIndexedPrimitiveUP(D3DPT_POINTLIST, 0, vertexCount,
primitiveCount, indexList, indexType, vertices, stride);
pID3DDevice->SetRenderState(D3DRS_POINTSCALEENABLE, FALSE);
if (pType==scene::EPT_POINT_SPRITES)
pID3DDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, FALSE);
}
break;
case scene::EPT_LINE_STRIP:
pID3DDevice->DrawIndexedPrimitiveUP(D3DPT_LINESTRIP, 0, vertexCount,
primitiveCount, indexList, indexType, vertices, stride);
break;
case scene::EPT_LINE_LOOP:
{
pID3DDevice->DrawIndexedPrimitiveUP(D3DPT_LINESTRIP, 0, vertexCount,
primitiveCount, indexList, indexType, vertices, stride);
u16 tmpIndices[] = {0, primitiveCount};
pID3DDevice->DrawIndexedPrimitiveUP(D3DPT_LINELIST, 0, vertexCount,
1, tmpIndices, indexType, vertices, stride);
}
break;
case scene::EPT_LINES:
pID3DDevice->DrawIndexedPrimitiveUP(D3DPT_LINELIST, 0, vertexCount,
diff --git a/source/Irrlicht/CD3D9Driver.cpp b/source/Irrlicht/CD3D9Driver.cpp
index 89ef971..4efb4e2 100644
--- a/source/Irrlicht/CD3D9Driver.cpp
+++ b/source/Irrlicht/CD3D9Driver.cpp
@@ -4,1027 +4,1030 @@
#define _IRR_DONT_DO_MEMORY_DEBUGGING_HERE
#include "CD3D9Driver.h"
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
#include "os.h"
#include "S3DVertex.h"
#include "CD3D9Texture.h"
#include "CImage.h"
#include "CD3D9MaterialRenderer.h"
#include "CD3D9ShaderMaterialRenderer.h"
#include "CD3D9NormalMapRenderer.h"
#include "CD3D9ParallaxMapRenderer.h"
#include "CD3D9HLSLMaterialRenderer.h"
namespace irr
{
namespace video
{
//! constructor
CD3D9Driver::CD3D9Driver(const core::dimension2d<u32>& screenSize, HWND window,
bool fullscreen, bool stencilbuffer,
io::IFileSystem* io, bool pureSoftware)
: CNullDriver(io, screenSize), CurrentRenderMode(ERM_NONE),
ResetRenderStates(true), Transformation3DChanged(false),
StencilBuffer(stencilbuffer), AntiAliasing(0),
D3DLibrary(0), pID3D(0), pID3DDevice(0), PrevRenderTarget(0),
WindowId(0), SceneSourceRect(0),
LastVertexType((video::E_VERTEX_TYPE)-1), VendorID(0),
MaxTextureUnits(0), MaxUserClipPlanes(0),
MaxLightDistance(0.f), LastSetLight(-1), Cached2DModeSignature(0),
ColorFormat(ECF_A8R8G8B8), DeviceLost(false),
Fullscreen(fullscreen), DriverWasReset(true), AlphaToCoverageSupport(false)
{
#ifdef _DEBUG
setDebugName("CD3D9Driver");
#endif
printVersion();
for (u32 i=0; i<MATERIAL_MAX_TEXTURES; ++i)
{
CurrentTexture[i] = 0;
LastTextureMipMapsAvailable[i] = false;
}
MaxLightDistance = sqrtf(FLT_MAX);
// create sphere map matrix
SphereMapMatrixD3D9._11 = 0.5f; SphereMapMatrixD3D9._12 = 0.0f;
SphereMapMatrixD3D9._13 = 0.0f; SphereMapMatrixD3D9._14 = 0.0f;
SphereMapMatrixD3D9._21 = 0.0f; SphereMapMatrixD3D9._22 =-0.5f;
SphereMapMatrixD3D9._23 = 0.0f; SphereMapMatrixD3D9._24 = 0.0f;
SphereMapMatrixD3D9._31 = 0.0f; SphereMapMatrixD3D9._32 = 0.0f;
SphereMapMatrixD3D9._33 = 1.0f; SphereMapMatrixD3D9._34 = 0.0f;
SphereMapMatrixD3D9._41 = 0.5f; SphereMapMatrixD3D9._42 = 0.5f;
SphereMapMatrixD3D9._43 = 0.0f; SphereMapMatrixD3D9._44 = 1.0f;
core::matrix4 mat;
UnitMatrixD3D9 = *(D3DMATRIX*)((void*)mat.pointer());
// init direct 3d is done in the factory function
}
//! destructor
CD3D9Driver::~CD3D9Driver()
{
deleteMaterialRenders();
deleteAllTextures();
// drop the main depth buffer
DepthBuffers[0]->drop();
// drop d3d9
if (pID3DDevice)
pID3DDevice->Release();
if (pID3D)
pID3D->Release();
}
void CD3D9Driver::createMaterialRenderers()
{
// create D3D9 material renderers
addAndDropMaterialRenderer(new CD3D9MaterialRenderer_SOLID(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D9MaterialRenderer_SOLID_2_LAYER(pID3DDevice, this));
// add the same renderer for all lightmap types
CD3D9MaterialRenderer_LIGHTMAP* lmr = new CD3D9MaterialRenderer_LIGHTMAP(pID3DDevice, this);
addMaterialRenderer(lmr); // for EMT_LIGHTMAP:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_ADD:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_M2:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_M4:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_LIGHTING:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_LIGHTING_M2:
addMaterialRenderer(lmr); // for EMT_LIGHTMAP_LIGHTING_M4:
lmr->drop();
// add remaining fixed function pipeline material renderers
addAndDropMaterialRenderer(new CD3D9MaterialRenderer_DETAIL_MAP(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D9MaterialRenderer_SPHERE_MAP(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D9MaterialRenderer_REFLECTION_2_LAYER(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D9MaterialRenderer_TRANSPARENT_ADD_COLOR(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D9MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D9MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL_REF(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D9MaterialRenderer_TRANSPARENT_VERTEX_ALPHA(pID3DDevice, this));
addAndDropMaterialRenderer(new CD3D9MaterialRenderer_TRANSPARENT_REFLECTION_2_LAYER(pID3DDevice, this));
// add normal map renderers
s32 tmp = 0;
video::IMaterialRenderer* renderer = 0;
renderer = new CD3D9NormalMapRenderer(pID3DDevice, this, tmp,
MaterialRenderers[EMT_SOLID].Renderer);
renderer->drop();
renderer = new CD3D9NormalMapRenderer(pID3DDevice, this, tmp,
MaterialRenderers[EMT_TRANSPARENT_ADD_COLOR].Renderer);
renderer->drop();
renderer = new CD3D9NormalMapRenderer(pID3DDevice, this, tmp,
MaterialRenderers[EMT_TRANSPARENT_VERTEX_ALPHA].Renderer);
renderer->drop();
// add parallax map renderers
renderer = new CD3D9ParallaxMapRenderer(pID3DDevice, this, tmp,
MaterialRenderers[EMT_SOLID].Renderer);
renderer->drop();
renderer = new CD3D9ParallaxMapRenderer(pID3DDevice, this, tmp,
MaterialRenderers[EMT_TRANSPARENT_ADD_COLOR].Renderer);
renderer->drop();
renderer = new CD3D9ParallaxMapRenderer(pID3DDevice, this, tmp,
MaterialRenderers[EMT_TRANSPARENT_VERTEX_ALPHA].Renderer);
renderer->drop();
// add basic 1 texture blending
addAndDropMaterialRenderer(new CD3D9MaterialRenderer_ONETEXTURE_BLEND(pID3DDevice, this));
}
//! initialises the Direct3D API
bool CD3D9Driver::initDriver(const core::dimension2d<u32>& screenSize,
HWND hwnd, u32 bits, bool fullScreen, bool pureSoftware,
bool highPrecisionFPU, bool vsync, u8 antiAlias)
{
HRESULT hr;
Fullscreen = fullScreen;
CurrentDepthBufferSize = screenSize;
if (!pID3D)
{
D3DLibrary = LoadLibrary( __TEXT("d3d9.dll") );
if (!D3DLibrary)
{
os::Printer::log("Error, could not load d3d9.dll.", ELL_ERROR);
return false;
}
typedef IDirect3D9 * (__stdcall *D3DCREATETYPE)(UINT);
D3DCREATETYPE d3dCreate = (D3DCREATETYPE) GetProcAddress(D3DLibrary, "Direct3DCreate9");
if (!d3dCreate)
{
os::Printer::log("Error, could not get proc adress of Direct3DCreate9.", ELL_ERROR);
return false;
}
//just like pID3D = Direct3DCreate9(D3D_SDK_VERSION);
pID3D = (*d3dCreate)(D3D_SDK_VERSION);
if (!pID3D)
{
os::Printer::log("Error initializing D3D.", ELL_ERROR);
return false;
}
}
// print device information
D3DADAPTER_IDENTIFIER9 dai;
if (!FAILED(pID3D->GetAdapterIdentifier(D3DADAPTER_DEFAULT, 0, &dai)))
{
char tmp[512];
s32 Product = HIWORD(dai.DriverVersion.HighPart);
s32 Version = LOWORD(dai.DriverVersion.HighPart);
s32 SubVersion = HIWORD(dai.DriverVersion.LowPart);
s32 Build = LOWORD(dai.DriverVersion.LowPart);
sprintf(tmp, "%s %s %d.%d.%d.%d", dai.Description, dai.Driver, Product, Version,
SubVersion, Build);
os::Printer::log(tmp, ELL_INFORMATION);
// Assign vendor name based on vendor id.
VendorID= static_cast<u16>(dai.VendorId);
switch(dai.VendorId)
{
case 0x1002 : VendorName = "ATI Technologies Inc."; break;
case 0x10DE : VendorName = "NVIDIA Corporation"; break;
case 0x102B : VendorName = "Matrox Electronic Systems Ltd."; break;
case 0x121A : VendorName = "3dfx Interactive Inc"; break;
case 0x5333 : VendorName = "S3 Graphics Co., Ltd."; break;
case 0x8086 : VendorName = "Intel Corporation"; break;
default: VendorName = "Unknown VendorId: ";VendorName += (u32)dai.VendorId; break;
}
}
D3DDISPLAYMODE d3ddm;
hr = pID3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm);
if (FAILED(hr))
{
os::Printer::log("Error: Could not get Adapter Display mode.", ELL_ERROR);
return false;
}
ZeroMemory(&present, sizeof(present));
present.BackBufferCount = 1;
present.EnableAutoDepthStencil = TRUE;
if (vsync)
present.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
else
present.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
if (fullScreen)
{
present.BackBufferWidth = screenSize.Width;
present.BackBufferHeight = screenSize.Height;
// request 32bit mode if user specified 32 bit, added by Thomas Stuefe
if (bits == 32)
present.BackBufferFormat = D3DFMT_X8R8G8B8;
else
present.BackBufferFormat = D3DFMT_R5G6B5;
present.SwapEffect = D3DSWAPEFFECT_FLIP;
present.Windowed = FALSE;
present.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
}
else
{
present.BackBufferFormat = d3ddm.Format;
present.SwapEffect = D3DSWAPEFFECT_DISCARD;
present.Windowed = TRUE;
}
UINT adapter = D3DADAPTER_DEFAULT;
D3DDEVTYPE devtype = D3DDEVTYPE_HAL;
#ifndef _IRR_D3D_NO_SHADER_DEBUGGING
devtype = D3DDEVTYPE_REF;
#elif defined(_IRR_USE_NVIDIA_PERFHUD_)
for (UINT adapter_i = 0; adapter_i < pID3D->GetAdapterCount(); ++adapter_i)
{
D3DADAPTER_IDENTIFIER9 identifier;
pID3D->GetAdapterIdentifier(adapter_i,0,&identifier);
if (strstr(identifier.Description,"PerfHUD") != 0)
{
adapter = adapter_i;
devtype = D3DDEVTYPE_REF;
break;
}
}
#endif
// enable anti alias if possible and desired
if (antiAlias > 0)
{
if(antiAlias > 16)
antiAlias = 16;
DWORD qualityLevels = 0;
while(antiAlias > 0)
{
if(SUCCEEDED(pID3D->CheckDeviceMultiSampleType(adapter,
devtype, present.BackBufferFormat, !fullScreen,
(D3DMULTISAMPLE_TYPE)antiAlias, &qualityLevels)))
{
present.MultiSampleType = (D3DMULTISAMPLE_TYPE)antiAlias;
present.MultiSampleQuality = qualityLevels-1;
present.SwapEffect = D3DSWAPEFFECT_DISCARD;
break;
}
--antiAlias;
}
if(antiAlias==0)
{
os::Printer::log("Anti aliasing disabled because hardware/driver lacks necessary caps.", ELL_WARNING);
}
}
AntiAliasing = antiAlias;
// check stencil buffer compatibility
if (StencilBuffer)
{
present.AutoDepthStencilFormat = D3DFMT_D24S8;
if(FAILED(pID3D->CheckDeviceFormat(adapter, devtype,
present.BackBufferFormat, D3DUSAGE_DEPTHSTENCIL,
D3DRTYPE_SURFACE, present.AutoDepthStencilFormat)))
{
present.AutoDepthStencilFormat = D3DFMT_D24X4S4;
if(FAILED(pID3D->CheckDeviceFormat(adapter, devtype,
present.BackBufferFormat, D3DUSAGE_DEPTHSTENCIL,
D3DRTYPE_SURFACE, present.AutoDepthStencilFormat)))
{
present.AutoDepthStencilFormat = D3DFMT_D15S1;
if(FAILED(pID3D->CheckDeviceFormat(adapter, devtype,
present.BackBufferFormat, D3DUSAGE_DEPTHSTENCIL,
D3DRTYPE_SURFACE, present.AutoDepthStencilFormat)))
{
os::Printer::log("Device does not support stencilbuffer, disabling stencil buffer.", ELL_WARNING);
StencilBuffer = false;
}
}
}
else
if(FAILED(pID3D->CheckDepthStencilMatch(adapter, devtype,
present.BackBufferFormat, present.BackBufferFormat, present.AutoDepthStencilFormat)))
{
os::Printer::log("Depth-stencil format is not compatible with display format, disabling stencil buffer.", ELL_WARNING);
StencilBuffer = false;
}
}
// do not use else here to cope with flag change in previous block
if (!StencilBuffer)
{
present.AutoDepthStencilFormat = D3DFMT_D32;
if(FAILED(pID3D->CheckDeviceFormat(adapter, devtype,
present.BackBufferFormat, D3DUSAGE_DEPTHSTENCIL,
D3DRTYPE_SURFACE, present.AutoDepthStencilFormat)))
{
present.AutoDepthStencilFormat = D3DFMT_D24X8;
if(FAILED(pID3D->CheckDeviceFormat(adapter, devtype,
present.BackBufferFormat, D3DUSAGE_DEPTHSTENCIL,
D3DRTYPE_SURFACE, present.AutoDepthStencilFormat)))
{
present.AutoDepthStencilFormat = D3DFMT_D16;
if(FAILED(pID3D->CheckDeviceFormat(adapter, devtype,
present.BackBufferFormat, D3DUSAGE_DEPTHSTENCIL,
D3DRTYPE_SURFACE, present.AutoDepthStencilFormat)))
{
os::Printer::log("Device does not support required depth buffer.", ELL_WARNING);
return false;
}
}
}
}
// create device
DWORD fpuPrecision = highPrecisionFPU ? D3DCREATE_FPU_PRESERVE : 0;
if (pureSoftware)
{
hr = pID3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_REF, hwnd,
fpuPrecision | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &present, &pID3DDevice);
if (FAILED(hr))
os::Printer::log("Was not able to create Direct3D9 software device.", ELL_ERROR);
}
else
{
hr = pID3D->CreateDevice(adapter, devtype, hwnd,
fpuPrecision | D3DCREATE_HARDWARE_VERTEXPROCESSING, &present, &pID3DDevice);
if(FAILED(hr))
hr = pID3D->CreateDevice(adapter, devtype, hwnd,
fpuPrecision | D3DCREATE_MIXED_VERTEXPROCESSING , &present, &pID3DDevice);
if(FAILED(hr))
hr = pID3D->CreateDevice(adapter, devtype, hwnd,
fpuPrecision | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &present, &pID3DDevice);
if (FAILED(hr))
os::Printer::log("Was not able to create Direct3D9 device.", ELL_ERROR);
}
if (!pID3DDevice)
{
os::Printer::log("Was not able to create DIRECT3D9 device.", ELL_ERROR);
return false;
}
// get caps
pID3DDevice->GetDeviceCaps(&Caps);
// disable stencilbuffer if necessary
if (StencilBuffer &&
(!(Caps.StencilCaps & D3DSTENCILCAPS_DECRSAT) ||
!(Caps.StencilCaps & D3DSTENCILCAPS_INCRSAT) ||
!(Caps.StencilCaps & D3DSTENCILCAPS_KEEP)))
{
os::Printer::log("Device not able to use stencil buffer, disabling stencil buffer.", ELL_WARNING);
StencilBuffer = false;
}
// set default vertex shader
setVertexShader(EVT_STANDARD);
// set fog mode
setFog(FogColor, FogType, FogStart, FogEnd, FogDensity, PixelFog, RangeFog);
// set exposed data
ExposedData.D3D9.D3D9 = pID3D;
ExposedData.D3D9.D3DDev9 = pID3DDevice;
ExposedData.D3D9.HWnd = hwnd;
ResetRenderStates = true;
// create materials
createMaterialRenderers();
MaxTextureUnits = core::min_((u32)Caps.MaxSimultaneousTextures, MATERIAL_MAX_TEXTURES);
MaxUserClipPlanes = (u32)Caps.MaxUserClipPlanes;
if (VendorID==0x10DE)//NVidia
AlphaToCoverageSupport = (pID3D->CheckDeviceFormat(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,
D3DFMT_X8R8G8B8, 0,D3DRTYPE_SURFACE,
(D3DFORMAT)MAKEFOURCC('A', 'T', 'O', 'C')) == S_OK);
else if (VendorID==0x1002)//ATI
AlphaToCoverageSupport = true; // TODO: Check unknown
#if 0
AlphaToCoverageSupport = (pID3D->CheckDeviceFormat(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,
D3DFMT_X8R8G8B8, 0,D3DRTYPE_SURFACE,
(D3DFORMAT)MAKEFOURCC('A','2','M','1')) == S_OK);
#endif
// set the renderstates
setRenderStates3DMode();
// store the screen's depth buffer
DepthBuffers.push_back(new SDepthSurface());
if (SUCCEEDED(pID3DDevice->GetDepthStencilSurface(&(DepthBuffers[0]->Surface))))
{
D3DSURFACE_DESC desc;
DepthBuffers[0]->Surface->GetDesc(&desc);
DepthBuffers[0]->Size.set(desc.Width, desc.Height);
}
else
{
os::Printer::log("Was not able to get main depth buffer.", ELL_ERROR);
return false;
}
D3DColorFormat = D3DFMT_A8R8G8B8;
IDirect3DSurface9* bb=0;
if (SUCCEEDED(pID3DDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &bb)))
{
D3DSURFACE_DESC desc;
bb->GetDesc(&desc);
D3DColorFormat = desc.Format;
if (D3DColorFormat == D3DFMT_X8R8G8B8)
D3DColorFormat = D3DFMT_A8R8G8B8;
bb->Release();
}
ColorFormat = getColorFormatFromD3DFormat(D3DColorFormat);
// so far so good.
return true;
}
//! applications must call this method before performing any rendering. returns false if failed.
bool CD3D9Driver::beginScene(bool backBuffer, bool zBuffer, SColor color,
const SExposedVideoData& videoData, core::rect<s32>* sourceRect)
{
CNullDriver::beginScene(backBuffer, zBuffer, color, videoData, sourceRect);
WindowId = (HWND)videoData.D3D9.HWnd;
SceneSourceRect = sourceRect;
if (!pID3DDevice)
return false;
HRESULT hr;
if (DeviceLost)
{
if (FAILED(hr = pID3DDevice->TestCooperativeLevel()))
{
if (hr == D3DERR_DEVICELOST)
{
Sleep(100);
hr = pID3DDevice->TestCooperativeLevel();
if (hr == D3DERR_DEVICELOST)
return false;
}
if ((hr == D3DERR_DEVICENOTRESET) && !reset())
return false;
}
}
DWORD flags = 0;
if (backBuffer)
flags |= D3DCLEAR_TARGET;
if (zBuffer)
flags |= D3DCLEAR_ZBUFFER;
if (StencilBuffer)
flags |= D3DCLEAR_STENCIL;
- hr = pID3DDevice->Clear( 0, NULL, flags, color.color, 1.0, 0);
- if (FAILED(hr))
- os::Printer::log("DIRECT3D9 clear failed.", ELL_WARNING);
+ if (flags)
+ {
+ hr = pID3DDevice->Clear( 0, NULL, flags, color.color, 1.0, 0);
+ if (FAILED(hr))
+ os::Printer::log("DIRECT3D9 clear failed.", ELL_WARNING);
+ }
hr = pID3DDevice->BeginScene();
if (FAILED(hr))
{
os::Printer::log("DIRECT3D9 begin scene failed.", ELL_WARNING);
return false;
}
return true;
}
//! applications must call this method after performing any rendering. returns false if failed.
bool CD3D9Driver::endScene()
{
CNullDriver::endScene();
DriverWasReset=false;
HRESULT hr = pID3DDevice->EndScene();
if (FAILED(hr))
{
os::Printer::log("DIRECT3D9 end scene failed.", ELL_WARNING);
return false;
}
RECT* srcRct = 0;
RECT sourceRectData;
if ( SceneSourceRect )
{
srcRct = &sourceRectData;
sourceRectData.left = SceneSourceRect->UpperLeftCorner.X;
sourceRectData.top = SceneSourceRect->UpperLeftCorner.Y;
sourceRectData.right = SceneSourceRect->LowerRightCorner.X;
sourceRectData.bottom = SceneSourceRect->LowerRightCorner.Y;
}
hr = pID3DDevice->Present(srcRct, NULL, WindowId, NULL);
if (SUCCEEDED(hr))
return true;
if (hr == D3DERR_DEVICELOST)
{
DeviceLost = true;
os::Printer::log("Present failed", "DIRECT3D9 device lost.", ELL_WARNING);
}
#ifdef D3DERR_DEVICEREMOVED
else if (hr == D3DERR_DEVICEREMOVED)
{
os::Printer::log("Present failed", "Device removed.", ELL_WARNING);
}
#endif
else if (hr == D3DERR_INVALIDCALL)
{
os::Printer::log("Present failed", "Invalid Call", ELL_WARNING);
}
else
os::Printer::log("DIRECT3D9 present failed.", ELL_WARNING);
return false;
}
//! queries the features of the driver, returns true if feature is available
bool CD3D9Driver::queryFeature(E_VIDEO_DRIVER_FEATURE feature) const
{
if (!FeatureEnabled[feature])
return false;
switch (feature)
{
case EVDF_MULTITEXTURE:
case EVDF_BILINEAR_FILTER:
return true;
case EVDF_RENDER_TO_TARGET:
return Caps.NumSimultaneousRTs > 0;
case EVDF_HARDWARE_TL:
return (Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) != 0;
case EVDF_MIP_MAP:
return (Caps.TextureCaps & D3DPTEXTURECAPS_MIPMAP) != 0;
case EVDF_MIP_MAP_AUTO_UPDATE:
// always return false because a lot of drivers claim they do
// this but actually don't do this at all.
return false; //(Caps.Caps2 & D3DCAPS2_CANAUTOGENMIPMAP) != 0;
case EVDF_STENCIL_BUFFER:
return StencilBuffer && Caps.StencilCaps;
case EVDF_VERTEX_SHADER_1_1:
return Caps.VertexShaderVersion >= D3DVS_VERSION(1,1);
case EVDF_VERTEX_SHADER_2_0:
return Caps.VertexShaderVersion >= D3DVS_VERSION(2,0);
case EVDF_VERTEX_SHADER_3_0:
return Caps.VertexShaderVersion >= D3DVS_VERSION(3,0);
case EVDF_PIXEL_SHADER_1_1:
return Caps.PixelShaderVersion >= D3DPS_VERSION(1,1);
case EVDF_PIXEL_SHADER_1_2:
return Caps.PixelShaderVersion >= D3DPS_VERSION(1,2);
case EVDF_PIXEL_SHADER_1_3:
return Caps.PixelShaderVersion >= D3DPS_VERSION(1,3);
case EVDF_PIXEL_SHADER_1_4:
return Caps.PixelShaderVersion >= D3DPS_VERSION(1,4);
case EVDF_PIXEL_SHADER_2_0:
return Caps.PixelShaderVersion >= D3DPS_VERSION(2,0);
case EVDF_PIXEL_SHADER_3_0:
return Caps.PixelShaderVersion >= D3DPS_VERSION(3,0);
case EVDF_HLSL:
return Caps.VertexShaderVersion >= D3DVS_VERSION(1,1);
case EVDF_TEXTURE_NSQUARE:
return (Caps.TextureCaps & D3DPTEXTURECAPS_SQUAREONLY) == 0;
case EVDF_TEXTURE_NPOT:
return (Caps.TextureCaps & D3DPTEXTURECAPS_POW2) == 0;
case EVDF_COLOR_MASK:
return (Caps.PrimitiveMiscCaps & D3DPMISCCAPS_COLORWRITEENABLE) != 0;
case EVDF_MULTIPLE_RENDER_TARGETS:
return Caps.NumSimultaneousRTs > 1;
case EVDF_MRT_COLOR_MASK:
return (Caps.PrimitiveMiscCaps & D3DPMISCCAPS_INDEPENDENTWRITEMASKS) != 0;
case EVDF_MRT_BLEND:
return (Caps.PrimitiveMiscCaps & D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING) != 0;
default:
return false;
};
}
//! sets transformation
void CD3D9Driver::setTransform(E_TRANSFORMATION_STATE state,
const core::matrix4& mat)
{
Transformation3DChanged = true;
switch(state)
{
case ETS_VIEW:
pID3DDevice->SetTransform(D3DTS_VIEW, (D3DMATRIX*)((void*)mat.pointer()));
break;
case ETS_WORLD:
pID3DDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)((void*)mat.pointer()));
break;
case ETS_PROJECTION:
pID3DDevice->SetTransform( D3DTS_PROJECTION, (D3DMATRIX*)((void*)mat.pointer()));
break;
case ETS_COUNT:
return;
default:
if (state-ETS_TEXTURE_0 < MATERIAL_MAX_TEXTURES)
{
if (mat.isIdentity())
pID3DDevice->SetTextureStageState( state - ETS_TEXTURE_0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE );
else
{
pID3DDevice->SetTextureStageState( state - ETS_TEXTURE_0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2 );
pID3DDevice->SetTransform((D3DTRANSFORMSTATETYPE)(D3DTS_TEXTURE0+ ( state - ETS_TEXTURE_0 )),
(D3DMATRIX*)((void*)mat.pointer()));
}
}
break;
}
Matrices[state] = mat;
}
//! sets the current Texture
bool CD3D9Driver::setActiveTexture(u32 stage, const video::ITexture* texture)
{
if (CurrentTexture[stage] == texture)
return true;
if (texture && texture->getDriverType() != EDT_DIRECT3D9)
{
os::Printer::log("Fatal Error: Tried to set a texture not owned by this driver.", ELL_ERROR);
return false;
}
CurrentTexture[stage] = texture;
if (!texture)
{
pID3DDevice->SetTexture(stage, 0);
pID3DDevice->SetTextureStageState( stage, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE );
}
else
{
pID3DDevice->SetTexture(stage, ((const CD3D9Texture*)texture)->getDX9Texture());
}
return true;
}
//! sets a material
void CD3D9Driver::setMaterial(const SMaterial& material)
{
Material = material;
OverrideMaterial.apply(Material);
for (u32 i=0; i<MaxTextureUnits; ++i)
{
setActiveTexture(i, Material.getTexture(i));
setTransform((E_TRANSFORMATION_STATE) ( ETS_TEXTURE_0 + i ),
material.getTextureMatrix(i));
}
}
//! returns a device dependent texture from a software surface (IImage)
video::ITexture* CD3D9Driver::createDeviceDependentTexture(IImage* surface,const io::path& name, void* mipmapData)
{
return new CD3D9Texture(surface, this, TextureCreationFlags, name, mipmapData);
}
//! Enables or disables a texture creation flag.
void CD3D9Driver::setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag,
bool enabled)
{
if (flag == video::ETCF_CREATE_MIP_MAPS && !queryFeature(EVDF_MIP_MAP))
enabled = false;
CNullDriver::setTextureCreationFlag(flag, enabled);
}
//! sets a render target
bool CD3D9Driver::setRenderTarget(video::ITexture* texture,
bool clearBackBuffer, bool clearZBuffer, SColor color)
{
// check for right driver type
if (texture && texture->getDriverType() != EDT_DIRECT3D9)
{
os::Printer::log("Fatal Error: Tried to set a texture not owned by this driver.", ELL_ERROR);
return false;
}
// check for valid render target
if (texture && !texture->isRenderTarget())
{
os::Printer::log("Fatal Error: Tried to set a non render target texture as render target.", ELL_ERROR);
return false;
}
CD3D9Texture* tex = static_cast<CD3D9Texture*>(texture);
// check if we should set the previous RT back
bool ret = true;
if (tex == 0)
{
if (PrevRenderTarget)
{
if (FAILED(pID3DDevice->SetRenderTarget(0, PrevRenderTarget)))
{
os::Printer::log("Error: Could not set back to previous render target.", ELL_ERROR);
ret = false;
}
if (FAILED(pID3DDevice->SetDepthStencilSurface(DepthBuffers[0]->Surface)))
{
os::Printer::log("Error: Could not set main depth buffer.", ELL_ERROR);
}
CurrentRendertargetSize = core::dimension2d<u32>(0,0);
PrevRenderTarget->Release();
PrevRenderTarget = 0;
}
}
else
{
// we want to set a new target. so do this.
// store previous target
if (!PrevRenderTarget)
{
if (FAILED(pID3DDevice->GetRenderTarget(0, &PrevRenderTarget)))
{
os::Printer::log("Could not get previous render target.", ELL_ERROR);
return false;
}
}
// set new render target
if (FAILED(pID3DDevice->SetRenderTarget(0, tex->getRenderTargetSurface())))
{
os::Printer::log("Error: Could not set render target.", ELL_ERROR);
return false;
}
CurrentRendertargetSize = tex->getSize();
if (FAILED(pID3DDevice->SetDepthStencilSurface(tex->DepthSurface->Surface)))
{
os::Printer::log("Error: Could not set new depth buffer.", ELL_ERROR);
}
}
if (clearBackBuffer || clearZBuffer)
{
DWORD flags = 0;
if (clearBackBuffer)
flags |= D3DCLEAR_TARGET;
if (clearZBuffer)
flags |= D3DCLEAR_ZBUFFER;
pID3DDevice->Clear(0, NULL, flags, color.color, 1.0f, 0);
}
return ret;
}
//! Sets multiple render targets
bool CD3D9Driver::setRenderTarget(const core::array<video::IRenderTarget>& targets,
bool clearBackBuffer, bool clearZBuffer, SColor color)
{
if (targets.size()==0)
return setRenderTarget(0, clearBackBuffer, clearZBuffer, color);
u32 maxMultipleRTTs = core::min_(4u, targets.size());
for (u32 i = 0; i < maxMultipleRTTs; ++i)
{
if (targets[i].TargetType != ERT_RENDER_TEXTURE || !targets[i].RenderTexture)
{
maxMultipleRTTs = i;
os::Printer::log("Missing texture for MRT.", ELL_WARNING);
break;
}
// check for right driver type
if (targets[i].RenderTexture->getDriverType() != EDT_DIRECT3D9)
{
maxMultipleRTTs = i;
os::Printer::log("Tried to set a texture not owned by this driver.", ELL_WARNING);
break;
}
// check for valid render target
if (!targets[i].RenderTexture->isRenderTarget())
{
maxMultipleRTTs = i;
os::Printer::log("Tried to set a non render target texture as render target.", ELL_WARNING);
break;
}
// check for valid size
if (targets[0].RenderTexture->getSize() != targets[i].RenderTexture->getSize())
{
maxMultipleRTTs = i;
os::Printer::log("Render target texture has wrong size.", ELL_WARNING);
break;
}
}
if (maxMultipleRTTs==0)
{
os::Printer::log("Fatal Error: No valid MRT found.", ELL_ERROR);
return false;
}
CD3D9Texture* tex = static_cast<CD3D9Texture*>(targets[0].RenderTexture);
// check if we should set the previous RT back
bool ret = true;
// we want to set a new target. so do this.
// store previous target
if (!PrevRenderTarget)
{
if (FAILED(pID3DDevice->GetRenderTarget(0, &PrevRenderTarget)))
{
os::Printer::log("Could not get previous render target.", ELL_ERROR);
return false;
}
}
// set new render target
D3DRENDERSTATETYPE colorWrite[4]={D3DRS_COLORWRITEENABLE, D3DRS_COLORWRITEENABLE1, D3DRS_COLORWRITEENABLE2, D3DRS_COLORWRITEENABLE3};
for (u32 i = 0; i < maxMultipleRTTs; ++i)
{
if (FAILED(pID3DDevice->SetRenderTarget(i, static_cast<CD3D9Texture*>(targets[i].RenderTexture)->getRenderTargetSurface())))
{
os::Printer::log("Error: Could not set render target.", ELL_ERROR);
return false;
}
if (i<4 && (i==0 || queryFeature(EVDF_MRT_COLOR_MASK)))
{
const DWORD flag =
((targets[i].ColorMask & ECP_RED)?D3DCOLORWRITEENABLE_RED:0) |
((targets[i].ColorMask & ECP_GREEN)?D3DCOLORWRITEENABLE_GREEN:0) |
((targets[i].ColorMask & ECP_BLUE)?D3DCOLORWRITEENABLE_BLUE:0) |
((targets[i].ColorMask & ECP_ALPHA)?D3DCOLORWRITEENABLE_ALPHA:0);
pID3DDevice->SetRenderState(colorWrite[i], flag);
}
}
CurrentRendertargetSize = tex->getSize();
if (FAILED(pID3DDevice->SetDepthStencilSurface(tex->DepthSurface->Surface)))
{
os::Printer::log("Error: Could not set new depth buffer.", ELL_ERROR);
}
if (clearBackBuffer || clearZBuffer)
{
DWORD flags = 0;
if (clearBackBuffer)
flags |= D3DCLEAR_TARGET;
if (clearZBuffer)
flags |= D3DCLEAR_ZBUFFER;
pID3DDevice->Clear(0, NULL, flags, color.color, 1.0f, 0);
}
return ret;
}
//! sets a viewport
void CD3D9Driver::setViewPort(const core::rect<s32>& area)
{
core::rect<s32> vp = area;
core::rect<s32> rendert(0,0, getCurrentRenderTargetSize().Width, getCurrentRenderTargetSize().Height);
vp.clipAgainst(rendert);
D3DVIEWPORT9 viewPort;
viewPort.X = vp.UpperLeftCorner.X;
viewPort.Y = vp.UpperLeftCorner.Y;
viewPort.Width = vp.getWidth();
viewPort.Height = vp.getHeight();
viewPort.MinZ = 0.0f;
viewPort.MaxZ = 1.0f;
HRESULT hr = D3DERR_INVALIDCALL;
if (vp.getHeight()>0 && vp.getWidth()>0)
hr = pID3DDevice->SetViewport(&viewPort);
if (FAILED(hr))
os::Printer::log("Failed setting the viewport.", ELL_WARNING);
ViewPort = vp;
}
//! gets the area of the current viewport
const core::rect<s32>& CD3D9Driver::getViewPort() const
{
return ViewPort;
}
bool CD3D9Driver::updateVertexHardwareBuffer(SHWBufferLink_d3d9 *hwBuffer)
{
if (!hwBuffer)
return false;
const scene::IMeshBuffer* mb = hwBuffer->MeshBuffer;
const void* vertices=mb->getVertices();
const u32 vertexCount=mb->getVertexCount();
const E_VERTEX_TYPE vType=mb->getVertexType();
const u32 vertexSize = getVertexPitchFromType(vType);
void* pLockedBuffer = 0;
if (!hwBuffer->vertexBuffer || vertexSize * vertexCount > hwBuffer->vertexBufferSize)
{
DWORD flags = 0;
u32 vertexSize;
DWORD FVF;
// Get the vertex sizes and cvf
switch (vType)
{
case EVT_STANDARD:
vertexSize = sizeof(S3DVertex);
FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_TEX1;
break;
case EVT_2TCOORDS:
vertexSize = sizeof(S3DVertex2TCoords);
FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_TEX2;
break;
case EVT_TANGENTS:
vertexSize = sizeof(S3DVertexTangents);
FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_TEX3;
break;
default:
return false;
}
flags = D3DUSAGE_WRITEONLY; // SIO2: Default to D3DUSAGE_WRITEONLY
if(hwBuffer->Mapped_Vertex != scene::EHM_STATIC)
flags |= D3DUSAGE_DYNAMIC;
pID3DDevice->CreateVertexBuffer(vertexCount * vertexSize, flags, FVF, D3DPOOL_DEFAULT, &hwBuffer->vertexBuffer, NULL);
if(!hwBuffer->vertexBuffer)
return false;
flags = 0; // SIO2: Reset flags before Lock
if(hwBuffer->Mapped_Vertex != scene::EHM_STATIC)
flags = D3DLOCK_DISCARD;
|
paupawsan/Irrlicht
|
d0003484378edef54859b5c92e560a9c128b0cf8
|
Ensure that createMeshWith* always creates unique vertices. Slightly refactored the tangent creation, which is now also possible on demand.
|
diff --git a/examples/11.PerPixelLighting/main.cpp b/examples/11.PerPixelLighting/main.cpp
index 3e3b25f..72f7461 100644
--- a/examples/11.PerPixelLighting/main.cpp
+++ b/examples/11.PerPixelLighting/main.cpp
@@ -1,485 +1,485 @@
/** Example 011 Per-Pixel Lighting
This tutorial shows how to use one of the built in more complex materials in
irrlicht: Per pixel lighted surfaces using normal maps and parallax mapping. It
will also show how to use fog and moving particle systems. And don't panic: You
dont need any experience with shaders to use these materials in Irrlicht.
At first, we need to include all headers and do the stuff we always do, like in
nearly all other tutorials.
*/
#include <irrlicht.h>
#include "driverChoice.h"
using namespace irr;
#ifdef _MSC_VER
#pragma comment(lib, "Irrlicht.lib")
#endif
/*
For this example, we need an event receiver, to make it possible for the user
to switch between the three available material types. In addition, the event
receiver will create some small GUI window which displays what material is
currently being used. There is nothing special done in this class, so maybe you
want to skip reading it.
*/
class MyEventReceiver : public IEventReceiver
{
public:
MyEventReceiver(scene::ISceneNode* room,
gui::IGUIEnvironment* env, video::IVideoDriver* driver)
{
// store pointer to room so we can change its drawing mode
Room = room;
Driver = driver;
// set a nicer font
gui::IGUISkin* skin = env->getSkin();
gui::IGUIFont* font = env->getFont("../../media/fonthaettenschweiler.bmp");
if (font)
skin->setFont(font);
// add window and listbox
gui::IGUIWindow* window = env->addWindow(
core::rect<s32>(460,375,630,470), false, L"Use 'E' + 'R' to change");
ListBox = env->addListBox(
core::rect<s32>(2,22,165,88), window);
ListBox->addItem(L"Diffuse");
ListBox->addItem(L"Bump mapping");
ListBox->addItem(L"Parallax mapping");
ListBox->setSelected(1);
// create problem text
ProblemText = env->addStaticText(
L"Your hardware or this renderer is not able to use the "\
L"needed shaders for this material. Using fall back materials.",
core::rect<s32>(150,20,470,80));
ProblemText->setOverrideColor(video::SColor(100,255,255,255));
// set start material (prefer parallax mapping if available)
video::IMaterialRenderer* renderer =
Driver->getMaterialRenderer(video::EMT_PARALLAX_MAP_SOLID);
if (renderer && renderer->getRenderCapability() == 0)
ListBox->setSelected(2);
// set the material which is selected in the listbox
setMaterial();
}
bool OnEvent(const SEvent& event)
{
// check if user presses the key 'E' or 'R'
if (event.EventType == irr::EET_KEY_INPUT_EVENT &&
!event.KeyInput.PressedDown && Room && ListBox)
{
// change selected item in listbox
int sel = ListBox->getSelected();
if (event.KeyInput.Key == irr::KEY_KEY_R)
++sel;
else
if (event.KeyInput.Key == irr::KEY_KEY_E)
--sel;
else
return false;
if (sel > 2) sel = 0;
if (sel < 0) sel = 2;
ListBox->setSelected(sel);
// set the material which is selected in the listbox
setMaterial();
}
return false;
}
private:
// sets the material of the room mesh the the one set in the
// list box.
void setMaterial()
{
video::E_MATERIAL_TYPE type = video::EMT_SOLID;
// change material setting
switch(ListBox->getSelected())
{
case 0: type = video::EMT_SOLID;
break;
case 1: type = video::EMT_NORMAL_MAP_SOLID;
break;
case 2: type = video::EMT_PARALLAX_MAP_SOLID;
break;
}
Room->setMaterialType(type);
/*
We need to add a warning if the materials will not be able to
be displayed 100% correctly. This is no problem, they will be
renderered using fall back materials, but at least the user
should know that it would look better on better hardware. We
simply check if the material renderer is able to draw at full
quality on the current hardware. The
IMaterialRenderer::getRenderCapability() returns 0 if this is
the case.
*/
video::IMaterialRenderer* renderer = Driver->getMaterialRenderer(type);
// display some problem text when problem
if (!renderer || renderer->getRenderCapability() != 0)
ProblemText->setVisible(true);
else
ProblemText->setVisible(false);
}
private:
gui::IGUIStaticText* ProblemText;
gui::IGUIListBox* ListBox;
scene::ISceneNode* Room;
video::IVideoDriver* Driver;
};
/*
Now for the real fun. We create an Irrlicht Device and start to setup the scene.
*/
int main()
{
// let user select driver type
video::E_DRIVER_TYPE driverType = video::EDT_DIRECT3D9;
printf("Please select the driver you want for this example:\n"\
" (a) Direct3D 9.0c\n (b) Direct3D 8.1\n (c) OpenGL 1.5\n"\
" (d) Software Renderer\n (e) Burning's Software Renderer\n"\
" (f) NullDevice\n (otherKey) exit\n\n");
char i;
std::cin >> i;
switch(i)
{
case 'a': driverType = video::EDT_DIRECT3D9;break;
case 'b': driverType = video::EDT_DIRECT3D8;break;
case 'c': driverType = video::EDT_OPENGL; break;
case 'd': driverType = video::EDT_SOFTWARE; break;
case 'e': driverType = video::EDT_BURNINGSVIDEO;break;
case 'f': driverType = video::EDT_NULL; break;
default: return 0;
}
// create device
IrrlichtDevice* device = createDevice(driverType,
core::dimension2d<u32>(640, 480));
if (device == 0)
return 1; // could not create selected driver.
/*
Before we start with the interesting stuff, we do some simple things:
Store pointers to the most important parts of the engine (video driver,
scene manager, gui environment) to safe us from typing too much, add an
irrlicht engine logo to the window and a user controlled first person
shooter style camera. Also, we let the engine know that it should store
all textures in 32 bit. This necessary because for parallax mapping, we
need 32 bit textures.
*/
video::IVideoDriver* driver = device->getVideoDriver();
scene::ISceneManager* smgr = device->getSceneManager();
gui::IGUIEnvironment* env = device->getGUIEnvironment();
driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);
// add irrlicht logo
env->addImage(driver->getTexture("../../media/irrlichtlogo2.png"),
core::position2d<s32>(10,10));
// add camera
scene::ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS();
camera->setPosition(core::vector3df(-200,200,-200));
// disable mouse cursor
device->getCursorControl()->setVisible(false);
/*
Because we want the whole scene to look a little bit scarier, we add
some fog to it. This is done by a call to IVideoDriver::setFog(). There
you can set various fog settings. In this example, we use pixel fog,
because it will work well with the materials we'll use in this example.
Please note that you will have to set the material flag EMF_FOG_ENABLE
to 'true' in every scene node which should be affected by this fog.
*/
driver->setFog(video::SColor(0,138,125,81), video::EFT_FOG_LINEAR, 250, 1000, .003f, true, false);
/*
To be able to display something interesting, we load a mesh from a .3ds
file which is a room I modeled with anim8or. It is the same room as
from the specialFX example. Maybe you remember from that tutorial, I am
no good modeler at all and so I totally messed up the texture mapping
in this model, but we can simply repair it with the
IMeshManipulator::makePlanarTextureMapping() method.
*/
scene::IAnimatedMesh* roomMesh = smgr->getMesh(
"../../media/room.3ds");
scene::ISceneNode* room = 0;
if (roomMesh)
{
smgr->getMeshManipulator()->makePlanarTextureMapping(
roomMesh->getMesh(0), 0.003f);
/*
Now for the first exciting thing: If we successfully loaded the
mesh we need to apply textures to it. Because we want this room
to be displayed with a very cool material, we have to do a
little bit more than just set the textures. Instead of only
loading a color map as usual, we also load a height map which
is simply a grayscale texture. From this height map, we create
a normal map which we will set as second texture of the room.
If you already have a normal map, you could directly set it,
but I simply didn't find a nice normal map for this texture.
The normal map texture is being generated by the
makeNormalMapTexture method of the VideoDriver. The second
parameter specifies the height of the heightmap. If you set it
to a bigger value, the map will look more rocky.
*/
video::ITexture* normalMap =
driver->getTexture("../../media/rockwall_height.bmp");
if (normalMap)
driver->makeNormalMapTexture(normalMap, 9.0f);
/*
But just setting color and normal map is not everything. The
material we want to use needs some additional informations per
vertex like tangents and binormals. Because we are too lazy to
calculate that information now, we let Irrlicht do this for us.
That's why we call IMeshManipulator::createMeshWithTangents().
It creates a mesh copy with tangents and binormals from another
mesh. After we've done that, we simply create a standard
mesh scene node with this mesh copy, set color and normal map
and adjust some other material settings. Note that we set
EMF_FOG_ENABLE to true to enable fog in the room.
*/
- scene::IMesh* tangentMesh = smgr->getMeshManipulator()->createMeshWithTangents(
- roomMesh->getMesh(0));
+ scene::IMesh* tangentMesh = smgr->getMeshManipulator()->
+ createMeshWithTangents(roomMesh->getMesh(0));
room = smgr->addMeshSceneNode(tangentMesh);
room->setMaterialTexture(0,
driver->getTexture("../../media/rockwall.jpg"));
room->setMaterialTexture(1, normalMap);
room->getMaterial(0).SpecularColor.set(0,0,0,0);
room->setMaterialFlag(video::EMF_FOG_ENABLE, true);
room->setMaterialType(video::EMT_PARALLAX_MAP_SOLID);
// adjust height for parallax effect
room->getMaterial(0).MaterialTypeParam = 0.035f;
// drop mesh because we created it with a create.. call.
tangentMesh->drop();
}
/*
After we've created a room shaded by per pixel lighting, we add a
sphere into it with the same material, but we'll make it transparent.
In addition, because the sphere looks somehow like a familiar planet,
we make it rotate. The procedure is similar as before. The difference
is that we are loading the mesh from an .x file which already contains
a color map so we do not need to load it manually. But the sphere is a
little bit too small for our needs, so we scale it by the factor 50.
*/
// add earth sphere
scene::IAnimatedMesh* earthMesh = smgr->getMesh("../../media/earth.x");
if (earthMesh)
{
//perform various task with the mesh manipulator
scene::IMeshManipulator *manipulator = smgr->getMeshManipulator();
// create mesh copy with tangent informations from original earth.x mesh
scene::IMesh* tangentSphereMesh =
manipulator->createMeshWithTangents(earthMesh->getMesh(0));
// set the alpha value of all vertices to 200
manipulator->setVertexColorAlpha(tangentSphereMesh, 200);
// scale the mesh by factor 50
core::matrix4 m;
m.setScale ( core::vector3df(50,50,50) );
manipulator->transformMesh( tangentSphereMesh, m );
scene::ISceneNode *sphere = smgr->addMeshSceneNode(tangentSphereMesh);
sphere->setPosition(core::vector3df(-70,130,45));
// load heightmap, create normal map from it and set it
video::ITexture* earthNormalMap = driver->getTexture("../../media/earthbump.jpg");
if (earthNormalMap)
{
driver->makeNormalMapTexture(earthNormalMap, 20.0f);
sphere->setMaterialTexture(1, earthNormalMap);
sphere->setMaterialType(video::EMT_NORMAL_MAP_TRANSPARENT_VERTEX_ALPHA);
}
// adjust material settings
sphere->setMaterialFlag(video::EMF_FOG_ENABLE, true);
// add rotation animator
scene::ISceneNodeAnimator* anim =
smgr->createRotationAnimator(core::vector3df(0,0.1f,0));
sphere->addAnimator(anim);
anim->drop();
// drop mesh because we created it with a create.. call.
tangentSphereMesh->drop();
}
/*
Per pixel lighted materials only look cool when there are moving
lights. So we add some. And because moving lights alone are so boring,
we add billboards to them, and a whole particle system to one of them.
We start with the first light which is red and has only the billboard
attached.
*/
// add light 1 (nearly red)
scene::ILightSceneNode* light1 =
smgr->addLightSceneNode(0, core::vector3df(0,0,0),
video::SColorf(0.5f, 1.0f, 0.5f, 0.0f), 800.0f);
light1->setDebugDataVisible ( scene::EDS_BBOX );
// add fly circle animator to light 1
scene::ISceneNodeAnimator* anim =
smgr->createFlyCircleAnimator (core::vector3df(50,300,0),190.0f, -0.003f);
light1->addAnimator(anim);
anim->drop();
// attach billboard to the light
scene::ISceneNode* bill =
smgr->addBillboardSceneNode(light1, core::dimension2d<f32>(60, 60));
bill->setMaterialFlag(video::EMF_LIGHTING, false);
bill->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
bill->setMaterialTexture(0, driver->getTexture("../../media/particlered.bmp"));
/*
Now the same again, with the second light. The difference is that we
add a particle system to it too. And because the light moves, the
particles of the particlesystem will follow. If you want to know more
about how particle systems are created in Irrlicht, take a look at the
specialFx example. Maybe you will have noticed that we only add 2
lights, this has a simple reason: The low end version of this material
was written in ps1.1 and vs1.1, which doesn't allow more lights. You
could add a third light to the scene, but it won't be used to shade the
walls. But of course, this will change in future versions of Irrlicht
where higher versions of pixel/vertex shaders will be implemented too.
*/
// add light 2 (gray)
scene::ISceneNode* light2 =
smgr->addLightSceneNode(0, core::vector3df(0,0,0),
video::SColorf(1.0f, 0.2f, 0.2f, 0.0f), 800.0f);
// add fly circle animator to light 2
anim = smgr->createFlyCircleAnimator(core::vector3df(0,150,0), 200.0f,
0.001f, core::vector3df(0.2f, 0.9f, 0.f));
light2->addAnimator(anim);
anim->drop();
// attach billboard to light
bill = smgr->addBillboardSceneNode(light2, core::dimension2d<f32>(120, 120));
bill->setMaterialFlag(video::EMF_LIGHTING, false);
bill->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
bill->setMaterialTexture(0, driver->getTexture("../../media/particlewhite.bmp"));
// add particle system
scene::IParticleSystemSceneNode* ps =
smgr->addParticleSystemSceneNode(false, light2);
// create and set emitter
scene::IParticleEmitter* em = ps->createBoxEmitter(
core::aabbox3d<f32>(-3,0,-3,3,1,3),
core::vector3df(0.0f,0.03f,0.0f),
80,100,
video::SColor(0,255,255,255), video::SColor(0,255,255,255),
400,1100);
em->setMinStartSize(core::dimension2d<f32>(30.0f, 40.0f));
em->setMaxStartSize(core::dimension2d<f32>(30.0f, 40.0f));
ps->setEmitter(em);
em->drop();
// create and set affector
scene::IParticleAffector* paf = ps->createFadeOutParticleAffector();
ps->addAffector(paf);
paf->drop();
// adjust some material settings
ps->setMaterialFlag(video::EMF_LIGHTING, false);
ps->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
ps->setMaterialTexture(0, driver->getTexture("../../media/fireball.bmp"));
ps->setMaterialType(video::EMT_TRANSPARENT_VERTEX_ALPHA);
MyEventReceiver receiver(room, env, driver);
device->setEventReceiver(&receiver);
/*
Finally, draw everything. That's it.
*/
int lastFPS = -1;
while(device->run())
if (device->isWindowActive())
{
driver->beginScene(true, true, 0);
smgr->drawAll();
env->drawAll();
driver->endScene();
int fps = driver->getFPS();
if (lastFPS != fps)
{
core::stringw str = L"Per pixel lighting example - Irrlicht Engine [";
str += driver->getName();
str += "] FPS:";
str += fps;
device->setWindowCaption(str.c_str());
lastFPS = fps;
}
}
device->drop();
return 0;
}
/*
**/
diff --git a/include/IMeshManipulator.h b/include/IMeshManipulator.h
index f3ab3a0..fda04ad 100644
--- a/include/IMeshManipulator.h
+++ b/include/IMeshManipulator.h
@@ -1,327 +1,338 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __I_MESH_MANIPULATOR_H_INCLUDED__
#define __I_MESH_MANIPULATOR_H_INCLUDED__
#include "IReferenceCounted.h"
#include "vector3d.h"
#include "aabbox3d.h"
#include "matrix4.h"
#include "IAnimatedMesh.h"
#include "IMeshBuffer.h"
#include "SVertexManipulator.h"
namespace irr
{
namespace scene
{
struct SMesh;
//! An interface for easy manipulation of meshes.
/** Scale, set alpha value, flip surfaces, and so on. This exists for
fixing problems with wrong imported or exported meshes quickly after
loading. It is not intended for doing mesh modifications and/or
animations during runtime.
*/
class IMeshManipulator : public virtual IReferenceCounted
{
public:
//! Flips the direction of surfaces.
/** Changes backfacing triangles to frontfacing
triangles and vice versa.
\param mesh Mesh on which the operation is performed. */
virtual void flipSurfaces(IMesh* mesh) const = 0;
//! Sets the alpha vertex color value of the whole mesh to a new value.
/** \param mesh Mesh on which the operation is performed.
\param alpha New alpha value. Must be a value between 0 and 255. */
void setVertexColorAlpha(IMesh* mesh, s32 alpha) const
{
apply(scene::SVertexColorSetAlphaManipulator(alpha), mesh);
}
//! Sets the colors of all vertices to one color
/** \param mesh Mesh on which the operation is performed.
\param color New color. */
void setVertexColors(IMesh* mesh, video::SColor color) const
{
apply(scene::SVertexColorSetManipulator(color), mesh);
}
//! Recalculates all normals of the mesh.
/** \param mesh: Mesh on which the operation is performed.
\param smooth: If the normals shall be smoothed.
\param angleWeighted: If the normals shall be smoothed in relation to their angles. More expensive, but also higher precision. */
virtual void recalculateNormals(IMesh* mesh, bool smooth = false, bool angleWeighted = false) const = 0;
//! Recalculates all normals of the mesh buffer.
/** \param buffer: Mesh buffer on which the operation is performed.
\param smooth: If the normals shall be smoothed.
\param angleWeighted: If the normals shall be smoothed in relation to their angles. More expensive, but also higher precision. */
virtual void recalculateNormals(IMeshBuffer* buffer, bool smooth = false, bool angleWeighted = false) const = 0;
+ //! Recalculates tangents, requires a tangent mesh
+ /** \param mesh Mesh on which the operation is performed.
+ \param recalculateNormals If the normals shall be recalculated, otherwise original normals of the mesh are used unchanged.
+ \param smooth If the normals shall be smoothed.
+ \param angleWeighted If the normals shall be smoothed in relation to their angles. More expensive, but also higher precision.
+ */
+ virtual void recalculateTangents(IMesh* mesh,
+ bool recalculateNormals=false, bool smooth=false,
+ bool angleWeighted=false) const=0;
+
//! Scales the actual mesh, not a scene node.
/** \param mesh Mesh on which the operation is performed.
\param factor Scale factor for each axis. */
void scale(IMesh* mesh, const core::vector3df& factor) const
{
apply(SVertexPositionScaleManipulator(factor), mesh, true);
}
//! Scales the actual meshbuffer, not a scene node.
/** \param buffer Meshbuffer on which the operation is performed.
\param factor Scale factor for each axis. */
void scale(IMeshBuffer* buffer, const core::vector3df& factor) const
{
apply(SVertexPositionScaleManipulator(factor), buffer, true);
}
//! Scales the actual mesh, not a scene node.
/** \deprecated Use scale() instead
\param mesh Mesh on which the operation is performed.
\param factor Scale factor for each axis. */
void scaleMesh(IMesh* mesh, const core::vector3df& factor) const {return scale(mesh,factor);}
//! Scale the texture coords of a mesh.
/** \param mesh Mesh on which the operation is performed.
\param factor Vector which defines the scale for each axis.
\param level Number of texture coord, starting from 1. Support for level 2 exists for LightMap buffers. */
void scaleTCoords(scene::IMesh* mesh, const core::vector2df& factor, u32 level=1) const
{
apply(SVertexTCoordsScaleManipulator(factor, level), mesh);
}
//! Scale the texture coords of a meshbuffer.
/** \param buffer Meshbuffer on which the operation is performed.
\param factor Vector which defines the scale for each axis.
\param level Number of texture coord, starting from 1. Support for level 2 exists for LightMap buffers. */
void scaleTCoords(scene::IMeshBuffer* buffer, const core::vector2df& factor, u32 level=1) const
{
apply(SVertexTCoordsScaleManipulator(factor, level), buffer);
}
//! Applies a transformation to a mesh
/** \param mesh Mesh on which the operation is performed.
\param m transformation matrix. */
void transform(IMesh* mesh, const core::matrix4& m) const
{
apply(SVertexPositionTransformManipulator(m), mesh, true);
}
//! Applies a transformation to a meshbuffer
/** \param buffer Meshbuffer on which the operation is performed.
\param m transformation matrix. */
void transform(IMeshBuffer* buffer, const core::matrix4& m) const
{
apply(SVertexPositionTransformManipulator(m), buffer, true);
}
//! Applies a transformation to a mesh
/** \deprecated Use transform() instead
\param mesh Mesh on which the operation is performed.
\param m transformation matrix. */
virtual void transformMesh(IMesh* mesh, const core::matrix4& m) const {return transform(mesh,m);}
//! Clones a static IMesh into a modifiable SMesh.
/** All meshbuffers in the returned SMesh
are of type SMeshBuffer or SMeshBufferLightMap.
\param mesh Mesh to copy.
\return Cloned mesh. If you no longer need the
cloned mesh, you should call SMesh::drop(). See
IReferenceCounted::drop() for more information. */
virtual SMesh* createMeshCopy(IMesh* mesh) const = 0;
//! Creates a planar texture mapping on the mesh
/** \param mesh: Mesh on which the operation is performed.
\param resolution: resolution of the planar mapping. This is
the value specifying which is the relation between world space
and texture coordinate space. */
virtual void makePlanarTextureMapping(IMesh* mesh, f32 resolution=0.001f) const =0;
//! Creates a planar texture mapping on the meshbuffer
/** \param meshbuffer: Buffer on which the operation is performed.
\param resolution: resolution of the planar mapping. This is
the value specifying which is the relation between world space
and texture coordinate space. */
virtual void makePlanarTextureMapping(scene::IMeshBuffer* meshbuffer, f32 resolution=0.001f) const =0;
//! Creates a planar texture mapping on the meshbuffer
/** This method is currently implemented towards the LWO planar mapping. A more general biasing might be required.
\param buffer Buffer on which the operation is performed.
\param resolutionS Resolution of the planar mapping in horizontal direction. This is the ratio between object space and texture space.
\param resolutionT Resolution of the planar mapping in vertical direction. This is the ratio between object space and texture space.
\param axis The axis along which the texture is projected. The allowed values are 0 (X), 1(Y), and 2(Z).
\param offset Vector added to the vertex positions (in object coordinates).
*/
virtual void makePlanarTextureMapping(scene::IMeshBuffer* buffer, f32 resolutionS, f32 resolutionT, u8 axis, const core::vector3df& offset) const =0;
//! Creates a copy of the mesh, which will only consist of S3DVertexTangents vertices.
/** This is useful if you want to draw tangent space normal
mapped geometry because it calculates the tangent and binormal
data which is needed there.
\param mesh Input mesh
\param recalculateNormals The normals are recalculated if set,
otherwise the original ones are kept. Note that keeping the
normals may introduce inaccurate tangents if the normals are
very different to those calculated from the faces.
\param smooth The normals/tangents are smoothed across the
meshbuffer's faces if this flag is set.
\param angleWeighted Improved smoothing calculation used
+ \param recalculateTangents Whether are actually calculated, or just the mesh with proper type is created.
\return Mesh consisting only of S3DVertexTangents vertices. If
you no longer need the cloned mesh, you should call
IMesh::drop(). See IReferenceCounted::drop() for more
information. */
- virtual IMesh* createMeshWithTangents(IMesh* mesh, bool recalculateNormals=false, bool smooth=false, bool angleWeighted=false) const = 0;
+ virtual IMesh* createMeshWithTangents(IMesh* mesh, bool recalculateNormals=false, bool smooth=false, bool angleWeighted=false, bool recalculateTangents=true) const = 0;
//! Creates a copy of the mesh, which will only consist of S3DVertex2TCoord vertices.
/** \param mesh Input mesh
\return Mesh consisting only of S3DVertex2TCoord vertices. If
you no longer need the cloned mesh, you should call
IMesh::drop(). See IReferenceCounted::drop() for more
information. */
virtual IMesh* createMeshWith2TCoords(IMesh* mesh) const = 0;
//! Creates a copy of the mesh, which will only consist of S3DVertex vertices.
/** \param mesh Input mesh
\return Mesh consisting only of S3DVertex vertices. If
you no longer need the cloned mesh, you should call
IMesh::drop(). See IReferenceCounted::drop() for more
information. */
virtual IMesh* createMeshWith1TCoords(IMesh* mesh) const = 0;
//! Creates a copy of a mesh with all vertices unwelded
/** \param mesh Input mesh
\return Mesh consisting only of unique faces. All vertices
which were previously shared are now duplicated. If you no
longer need the cloned mesh, you should call IMesh::drop(). See
IReferenceCounted::drop() for more information. */
virtual IMesh* createMeshUniquePrimitives(IMesh* mesh) const = 0;
//! Creates a copy of a mesh with vertices welded
/** \param mesh Input mesh
\param tolerance The threshold for vertex comparisons.
\return Mesh without redundant vertices. If you no longer need
the cloned mesh, you should call IMesh::drop(). See
IReferenceCounted::drop() for more information. */
virtual IMesh* createMeshWelded(IMesh* mesh, f32 tolerance=core::ROUNDING_ERROR_f32) const = 0;
//! Get amount of polygons in mesh.
/** \param mesh Input mesh
\return Number of polygons in mesh. */
virtual s32 getPolyCount(IMesh* mesh) const = 0;
//! Get amount of polygons in mesh.
/** \param mesh Input mesh
\return Number of polygons in mesh. */
virtual s32 getPolyCount(IAnimatedMesh* mesh) const = 0;
//! Create a new AnimatedMesh and adds the mesh to it
/** \param mesh Input mesh
\param type The type of the animated mesh to create.
\return Newly created animated mesh with mesh as its only
content. When you don't need the animated mesh anymore, you
should call IAnimatedMesh::drop(). See
IReferenceCounted::drop() for more information. */
virtual IAnimatedMesh * createAnimatedMesh(IMesh* mesh,
scene::E_ANIMATED_MESH_TYPE type = scene::EAMT_UNKNOWN) const = 0;
//! Apply a manipulator on the Meshbuffer
/** \param func A functor defining the mesh manipulation.
\param buffer The Meshbuffer to apply the manipulator to.
\param boundingBoxUpdate Specifies if the bounding box should be updated during manipulation.
\return True if the functor was successfully applied, else false. */
template <typename Functor>
bool apply(const Functor& func, IMeshBuffer* buffer, bool boundingBoxUpdate=false) const
{
return apply_(func, buffer, boundingBoxUpdate, func);
}
//! Apply a manipulator on the Mesh
/** \param func A functor defining the mesh manipulation.
\param mesh The Mesh to apply the manipulator to.
\param boundingBoxUpdate Specifies if the bounding box should be updated during manipulation.
\return True if the functor was successfully applied, else false. */
template <typename Functor>
bool apply(const Functor& func, IMesh* mesh, bool boundingBoxUpdate=false) const
{
if (!mesh)
return true;
bool result = true;
core::aabbox3df bufferbox;
for (u32 i=0; i<mesh->getMeshBufferCount(); ++i)
{
result &= apply(func, mesh->getMeshBuffer(i), boundingBoxUpdate);
if (boundingBoxUpdate)
{
if (0==i)
bufferbox.reset(mesh->getMeshBuffer(i)->getBoundingBox());
else
bufferbox.addInternalBox(mesh->getMeshBuffer(i)->getBoundingBox());
}
}
if (boundingBoxUpdate)
mesh->setBoundingBox(bufferbox);
return result;
}
protected:
//! Apply a manipulator based on the type of the functor
/** \param func A functor defining the mesh manipulation.
\param buffer The Meshbuffer to apply the manipulator to.
\param boundingBoxUpdate Specifies if the bounding box should be updated during manipulation.
\param typeTest Unused parameter, which handles the proper call selection based on the type of the Functor which is passed in two times.
\return True if the functor was successfully applied, else false. */
template <typename Functor>
bool apply_(const Functor& func, IMeshBuffer* buffer, bool boundingBoxUpdate, const IVertexManipulator& typeTest) const
{
if (!buffer)
return true;
core::aabbox3df bufferbox;
for (u32 i=0; i<buffer->getVertexCount(); ++i)
{
switch (buffer->getVertexType())
{
case video::EVT_STANDARD:
{
video::S3DVertex* verts = (video::S3DVertex*)buffer->getVertices();
func(verts[i]);
}
break;
case video::EVT_2TCOORDS:
{
video::S3DVertex2TCoords* verts = (video::S3DVertex2TCoords*)buffer->getVertices();
func(verts[i]);
}
break;
case video::EVT_TANGENTS:
{
video::S3DVertexTangents* verts = (video::S3DVertexTangents*)buffer->getVertices();
func(verts[i]);
}
break;
}
if (boundingBoxUpdate)
{
if (0==i)
bufferbox.reset(buffer->getPosition(0));
else
bufferbox.addInternalPoint(buffer->getPosition(i));
}
}
if (boundingBoxUpdate)
buffer->setBoundingBox(bufferbox);
return true;
}
};
} // end namespace scene
} // end namespace irr
#endif
diff --git a/source/Irrlicht/CMeshManipulator.cpp b/source/Irrlicht/CMeshManipulator.cpp
index 732b367..066dbf4 100644
--- a/source/Irrlicht/CMeshManipulator.cpp
+++ b/source/Irrlicht/CMeshManipulator.cpp
@@ -1,1089 +1,1111 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CMeshManipulator.h"
#include "SMesh.h"
#include "CMeshBuffer.h"
#include "SAnimatedMesh.h"
#include "os.h"
#include "irrMap.h"
namespace irr
{
namespace scene
{
static inline core::vector3df getAngleWeight(const core::vector3df& v1,
const core::vector3df& v2,
const core::vector3df& v3)
{
// Calculate this triangle's weight for each of its three vertices
// start by calculating the lengths of its sides
const f32 a = v2.getDistanceFromSQ(v3);
const f32 asqrt = sqrtf(a);
const f32 b = v1.getDistanceFromSQ(v3);
const f32 bsqrt = sqrtf(b);
const f32 c = v1.getDistanceFromSQ(v2);
const f32 csqrt = sqrtf(c);
// use them to find the angle at each vertex
return core::vector3df(
acosf((b + c - a) / (2.f * bsqrt * csqrt)),
acosf((-b + c + a) / (2.f * asqrt * csqrt)),
acosf((b - c + a) / (2.f * bsqrt * asqrt)));
}
//! Flips the direction of surfaces. Changes backfacing triangles to frontfacing
//! triangles and vice versa.
//! \param mesh: Mesh on which the operation is performed.
void CMeshManipulator::flipSurfaces(scene::IMesh* mesh) const
{
if (!mesh)
return;
const u32 bcount = mesh->getMeshBufferCount();
for (u32 b=0; b<bcount; ++b)
{
IMeshBuffer* buffer = mesh->getMeshBuffer(b);
const u32 idxcnt = buffer->getIndexCount();
u16* idx = buffer->getIndices();
s32 tmp;
for (u32 i=0; i<idxcnt; i+=3)
{
tmp = idx[i+1];
idx[i+1] = idx[i+2];
idx[i+2] = tmp;
}
}
}
//! Recalculates all normals of the mesh buffer.
/** \param buffer: Mesh buffer on which the operation is performed. */
void CMeshManipulator::recalculateNormals(IMeshBuffer* buffer, bool smooth, bool angleWeighted) const
{
if (!buffer)
return;
const u32 vtxcnt = buffer->getVertexCount();
const u32 idxcnt = buffer->getIndexCount();
const u16* idx = buffer->getIndices();
if (!smooth)
{
for (u32 i=0; i<idxcnt; i+=3)
{
const core::vector3df& v1 = buffer->getPosition(idx[i+0]);
const core::vector3df& v2 = buffer->getPosition(idx[i+1]);
const core::vector3df& v3 = buffer->getPosition(idx[i+2]);
const core::vector3df normal = core::plane3d<f32>(v1, v2, v3).Normal;
buffer->getNormal(idx[i+0]) = normal;
buffer->getNormal(idx[i+1]) = normal;
buffer->getNormal(idx[i+2]) = normal;
}
}
else
{
u32 i;
for ( i = 0; i!= vtxcnt; ++i )
buffer->getNormal(i).set( 0.f, 0.f, 0.f );
for ( i=0; i<idxcnt; i+=3)
{
const core::vector3df& v1 = buffer->getPosition(idx[i+0]);
const core::vector3df& v2 = buffer->getPosition(idx[i+1]);
const core::vector3df& v3 = buffer->getPosition(idx[i+2]);
core::vector3df normal = core::plane3d<f32>(v1, v2, v3).Normal;
if (angleWeighted)
normal *= getAngleWeight(v1,v2,v3);
buffer->getNormal(idx[i+0]) += normal;
buffer->getNormal(idx[i+1]) += normal;
buffer->getNormal(idx[i+2]) += normal;
}
for ( i = 0; i!= vtxcnt; ++i )
buffer->getNormal(i).normalize();
}
}
//! Recalculates all normals of the mesh.
//! \param mesh: Mesh on which the operation is performed.
void CMeshManipulator::recalculateNormals(scene::IMesh* mesh, bool smooth, bool angleWeighted) const
{
if (!mesh)
return;
const u32 bcount = mesh->getMeshBufferCount();
for ( u32 b=0; b<bcount; ++b)
recalculateNormals(mesh->getMeshBuffer(b), smooth, angleWeighted);
}
+//! Recalculates tangents, requires a tangent mesh
+void CMeshManipulator::recalculateTangents(IMesh* mesh, bool recalculateNormals, bool smooth, bool angleWeighted) const
+{
+ if (!mesh || !mesh->getMeshBufferCount() || (mesh->getMeshBuffer(0)->getVertexType()!= video::EVT_TANGENTS))
+ return;
+
+ const u32 meshBufferCount = mesh->getMeshBufferCount();
+ for (u32 b=0; b<meshBufferCount; ++b)
+ {
+ IMeshBuffer* clone = mesh->getMeshBuffer(b);
+ const u32 vtxCnt = clone->getVertexCount();
+ const u32 idxCnt = clone->getIndexCount();
+
+ u16* idx = clone->getIndices();
+ video::S3DVertexTangents* v =
+ (video::S3DVertexTangents*)clone->getVertices();
+
+ if (smooth)
+ {
+ u32 i;
+
+ for ( i = 0; i!= vtxCnt; ++i )
+ {
+ if (recalculateNormals)
+ v[i].Normal.set( 0.f, 0.f, 0.f );
+ v[i].Tangent.set( 0.f, 0.f, 0.f );
+ v[i].Binormal.set( 0.f, 0.f, 0.f );
+ }
+
+ //Each vertex gets the sum of the tangents and binormals from the faces around it
+ for ( i=0; i<idxCnt; i+=3)
+ {
+ // if this triangle is degenerate, skip it!
+ if (v[idx[i+0]].Pos == v[idx[i+1]].Pos ||
+ v[idx[i+0]].Pos == v[idx[i+2]].Pos ||
+ v[idx[i+1]].Pos == v[idx[i+2]].Pos
+ /*||
+ v[idx[i+0]].TCoords == v[idx[i+1]].TCoords ||
+ v[idx[i+0]].TCoords == v[idx[i+2]].TCoords ||
+ v[idx[i+1]].TCoords == v[idx[i+2]].TCoords */
+ )
+ continue;
+
+ //Angle-weighted normals look better, but are slightly more CPU intensive to calculate
+ core::vector3df weight(1.f,1.f,1.f);
+ if (angleWeighted)
+ weight = getAngleWeight(v[i+0].Pos,v[i+1].Pos,v[i+2].Pos);
+ core::vector3df localNormal;
+ core::vector3df localTangent;
+ core::vector3df localBinormal;
+
+ calculateTangents(
+ localNormal,
+ localTangent,
+ localBinormal,
+ v[idx[i+0]].Pos,
+ v[idx[i+1]].Pos,
+ v[idx[i+2]].Pos,
+ v[idx[i+0]].TCoords,
+ v[idx[i+1]].TCoords,
+ v[idx[i+2]].TCoords);
+
+ if (recalculateNormals)
+ v[idx[i+0]].Normal += localNormal * weight.X;
+ v[idx[i+0]].Tangent += localTangent * weight.X;
+ v[idx[i+0]].Binormal += localBinormal * weight.X;
+
+ calculateTangents(
+ localNormal,
+ localTangent,
+ localBinormal,
+ v[idx[i+1]].Pos,
+ v[idx[i+2]].Pos,
+ v[idx[i+0]].Pos,
+ v[idx[i+1]].TCoords,
+ v[idx[i+2]].TCoords,
+ v[idx[i+0]].TCoords);
+
+ if (recalculateNormals)
+ v[idx[i+1]].Normal += localNormal * weight.Y;
+ v[idx[i+1]].Tangent += localTangent * weight.Y;
+ v[idx[i+1]].Binormal += localBinormal * weight.Y;
+
+ calculateTangents(
+ localNormal,
+ localTangent,
+ localBinormal,
+ v[idx[i+2]].Pos,
+ v[idx[i+0]].Pos,
+ v[idx[i+1]].Pos,
+ v[idx[i+2]].TCoords,
+ v[idx[i+0]].TCoords,
+ v[idx[i+1]].TCoords);
+
+ if (recalculateNormals)
+ v[idx[i+2]].Normal += localNormal * weight.Z;
+ v[idx[i+2]].Tangent += localTangent * weight.Z;
+ v[idx[i+2]].Binormal += localBinormal * weight.Z;
+ }
+
+ // Normalize the tangents and binormals
+ if (recalculateNormals)
+ {
+ for ( i = 0; i!= vtxCnt; ++i )
+ v[i].Normal.normalize();
+ }
+ for ( i = 0; i!= vtxCnt; ++i )
+ {
+ v[i].Tangent.normalize();
+ v[i].Binormal.normalize();
+ }
+ }
+ else
+ {
+ core::vector3df localNormal;
+ for (u32 i=0; i<idxCnt; i+=3)
+ {
+ calculateTangents(
+ localNormal,
+ v[idx[i+0]].Tangent,
+ v[idx[i+0]].Binormal,
+ v[idx[i+0]].Pos,
+ v[idx[i+1]].Pos,
+ v[idx[i+2]].Pos,
+ v[idx[i+0]].TCoords,
+ v[idx[i+1]].TCoords,
+ v[idx[i+2]].TCoords);
+ if (recalculateNormals)
+ v[idx[i+0]].Normal=localNormal;
+
+ calculateTangents(
+ localNormal,
+ v[idx[i+1]].Tangent,
+ v[idx[i+1]].Binormal,
+ v[idx[i+1]].Pos,
+ v[idx[i+2]].Pos,
+ v[idx[i+0]].Pos,
+ v[idx[i+1]].TCoords,
+ v[idx[i+2]].TCoords,
+ v[idx[i+0]].TCoords);
+ if (recalculateNormals)
+ v[idx[i+1]].Normal=localNormal;
+
+ calculateTangents(
+ localNormal,
+ v[idx[i+2]].Tangent,
+ v[idx[i+2]].Binormal,
+ v[idx[i+2]].Pos,
+ v[idx[i+0]].Pos,
+ v[idx[i+1]].Pos,
+ v[idx[i+2]].TCoords,
+ v[idx[i+0]].TCoords,
+ v[idx[i+1]].TCoords);
+ if (recalculateNormals)
+ v[idx[i+2]].Normal=localNormal;
+ }
+ }
+ }
+}
+
+
//! Clones a static IMesh into a modifyable SMesh.
SMesh* CMeshManipulator::createMeshCopy(scene::IMesh* mesh) const
{
if (!mesh)
return 0;
SMesh* clone = new SMesh();
const u32 meshBufferCount = mesh->getMeshBufferCount();
for ( u32 b=0; b<meshBufferCount; ++b)
{
switch(mesh->getMeshBuffer(b)->getVertexType())
{
case video::EVT_STANDARD:
{
SMeshBuffer* buffer = new SMeshBuffer();
const u32 vcount = mesh->getMeshBuffer(b)->getVertexCount();
buffer->Vertices.reallocate(vcount);
video::S3DVertex* vertices = (video::S3DVertex*)mesh->getMeshBuffer(b)->getVertices();
for (u32 i=0; i < vcount; ++i)
buffer->Vertices.push_back(vertices[i]);
const u32 icount = mesh->getMeshBuffer(b)->getIndexCount();
buffer->Indices.reallocate(icount);
u16* indices = mesh->getMeshBuffer(b)->getIndices();
for (u32 i=0; i < icount; ++i)
buffer->Indices.push_back(indices[i]);
clone->addMeshBuffer(buffer);
buffer->drop();
}
break;
case video::EVT_2TCOORDS:
{
SMeshBufferLightMap* buffer = new SMeshBufferLightMap();
const u32 vcount = mesh->getMeshBuffer(b)->getVertexCount();
buffer->Vertices.reallocate(vcount);
video::S3DVertex2TCoords* vertices = (video::S3DVertex2TCoords*)mesh->getMeshBuffer(b)->getVertices();
for (u32 i=0; i < vcount; ++i)
buffer->Vertices.push_back(vertices[i]);
const u32 icount = mesh->getMeshBuffer(b)->getIndexCount();
buffer->Indices.reallocate(icount);
u16* indices = mesh->getMeshBuffer(b)->getIndices();
for (u32 i=0; i < icount; ++i)
buffer->Indices.push_back(indices[i]);
clone->addMeshBuffer(buffer);
buffer->drop();
}
break;
case video::EVT_TANGENTS:
{
SMeshBufferTangents* buffer = new SMeshBufferTangents();
const u32 vcount = mesh->getMeshBuffer(b)->getVertexCount();
buffer->Vertices.reallocate(vcount);
video::S3DVertexTangents* vertices = (video::S3DVertexTangents*)mesh->getMeshBuffer(b)->getVertices();
for (u32 i=0; i < vcount; ++i)
buffer->Vertices.push_back(vertices[i]);
const u32 icount = mesh->getMeshBuffer(b)->getIndexCount();
buffer->Indices.reallocate(icount);
u16* indices = mesh->getMeshBuffer(b)->getIndices();
for (u32 i=0; i < icount; ++i)
buffer->Indices.push_back(indices[i]);
clone->addMeshBuffer(buffer);
buffer->drop();
}
break;
}// end switch
}// end for all mesh buffers
clone->BoundingBox = mesh->getBoundingBox();
return clone;
}
//! Creates a planar texture mapping on the mesh
void CMeshManipulator::makePlanarTextureMapping(scene::IMesh* mesh, f32 resolution=0.01f) const
{
if (!mesh)
return;
const u32 bcount = mesh->getMeshBufferCount();
for ( u32 b=0; b<bcount; ++b)
{
makePlanarTextureMapping(mesh->getMeshBuffer(b), resolution);
}
}
//! Creates a planar texture mapping on the meshbuffer
void CMeshManipulator::makePlanarTextureMapping(scene::IMeshBuffer* buffer, f32 resolution) const
{
u32 idxcnt = buffer->getIndexCount();
u16* idx = buffer->getIndices();
for (u32 i=0; i<idxcnt; i+=3)
{
core::plane3df p(buffer->getPosition(idx[i+0]), buffer->getPosition(idx[i+1]), buffer->getPosition(idx[i+2]));
p.Normal.X = fabsf(p.Normal.X);
p.Normal.Y = fabsf(p.Normal.Y);
p.Normal.Z = fabsf(p.Normal.Z);
// calculate planar mapping worldspace coordinates
if (p.Normal.X > p.Normal.Y && p.Normal.X > p.Normal.Z)
{
for (u32 o=0; o!=3; ++o)
{
buffer->getTCoords(idx[i+o]).X = buffer->getPosition(idx[i+o]).Y * resolution;
buffer->getTCoords(idx[i+o]).Y = buffer->getPosition(idx[i+o]).Z * resolution;
}
}
else
if (p.Normal.Y > p.Normal.X && p.Normal.Y > p.Normal.Z)
{
for (u32 o=0; o!=3; ++o)
{
buffer->getTCoords(idx[i+o]).X = buffer->getPosition(idx[i+o]).X * resolution;
buffer->getTCoords(idx[i+o]).Y = buffer->getPosition(idx[i+o]).Z * resolution;
}
}
else
{
for (u32 o=0; o!=3; ++o)
{
buffer->getTCoords(idx[i+o]).X = buffer->getPosition(idx[i+o]).X * resolution;
buffer->getTCoords(idx[i+o]).Y = buffer->getPosition(idx[i+o]).Y * resolution;
}
}
}
}
//! Creates a planar texture mapping on the meshbuffer
void CMeshManipulator::makePlanarTextureMapping(scene::IMeshBuffer* buffer, f32 resolutionS, f32 resolutionT, u8 axis, const core::vector3df& offset) const
{
u32 idxcnt = buffer->getIndexCount();
u16* idx = buffer->getIndices();
for (u32 i=0; i<idxcnt; i+=3)
{
// calculate planar mapping worldspace coordinates
if (axis==0)
{
for (u32 o=0; o!=3; ++o)
{
buffer->getTCoords(idx[i+o]).X = 0.5f+(buffer->getPosition(idx[i+o]).Z + offset.Z) * resolutionS;
buffer->getTCoords(idx[i+o]).Y = 0.5f-(buffer->getPosition(idx[i+o]).Y + offset.Y) * resolutionT;
}
}
else if (axis==1)
{
for (u32 o=0; o!=3; ++o)
{
buffer->getTCoords(idx[i+o]).X = 0.5f+(buffer->getPosition(idx[i+o]).X + offset.X) * resolutionS;
buffer->getTCoords(idx[i+o]).Y = 1.f-(buffer->getPosition(idx[i+o]).Z + offset.Z) * resolutionT;
}
}
else if (axis==2)
{
for (u32 o=0; o!=3; ++o)
{
buffer->getTCoords(idx[i+o]).X = 0.5f+(buffer->getPosition(idx[i+o]).X + offset.X) * resolutionS;
buffer->getTCoords(idx[i+o]).Y = 0.5f-(buffer->getPosition(idx[i+o]).Y + offset.Y) * resolutionT;
}
}
}
}
//! Creates a copy of the mesh, which will only consist of unique primitives
IMesh* CMeshManipulator::createMeshUniquePrimitives(IMesh* mesh) const
{
if (!mesh)
return 0;
SMesh* clone = new SMesh();
const u32 meshBufferCount = mesh->getMeshBufferCount();
for ( u32 b=0; b<meshBufferCount; ++b)
{
const s32 idxCnt = mesh->getMeshBuffer(b)->getIndexCount();
const u16* idx = mesh->getMeshBuffer(b)->getIndices();
switch(mesh->getMeshBuffer(b)->getVertexType())
{
case video::EVT_STANDARD:
{
SMeshBuffer* buffer = new SMeshBuffer();
buffer->Material = mesh->getMeshBuffer(b)->getMaterial();
video::S3DVertex* v =
(video::S3DVertex*)mesh->getMeshBuffer(b)->getVertices();
buffer->Vertices.reallocate(idxCnt);
buffer->Indices.reallocate(idxCnt);
for (s32 i=0; i<idxCnt; i += 3)
{
buffer->Vertices.push_back( v[idx[i + 0 ]] );
buffer->Vertices.push_back( v[idx[i + 1 ]] );
buffer->Vertices.push_back( v[idx[i + 2 ]] );
buffer->Indices.push_back( i + 0 );
buffer->Indices.push_back( i + 1 );
buffer->Indices.push_back( i + 2 );
}
buffer->setBoundingBox(mesh->getMeshBuffer(b)->getBoundingBox());
clone->addMeshBuffer(buffer);
buffer->drop();
}
break;
case video::EVT_2TCOORDS:
{
SMeshBufferLightMap* buffer = new SMeshBufferLightMap();
buffer->Material = mesh->getMeshBuffer(b)->getMaterial();
video::S3DVertex2TCoords* v =
(video::S3DVertex2TCoords*)mesh->getMeshBuffer(b)->getVertices();
buffer->Vertices.reallocate(idxCnt);
buffer->Indices.reallocate(idxCnt);
for (s32 i=0; i<idxCnt; i += 3)
{
buffer->Vertices.push_back( v[idx[i + 0 ]] );
buffer->Vertices.push_back( v[idx[i + 1 ]] );
buffer->Vertices.push_back( v[idx[i + 2 ]] );
buffer->Indices.push_back( i + 0 );
buffer->Indices.push_back( i + 1 );
buffer->Indices.push_back( i + 2 );
}
buffer->setBoundingBox(mesh->getMeshBuffer(b)->getBoundingBox());
clone->addMeshBuffer(buffer);
buffer->drop();
}
break;
case video::EVT_TANGENTS:
{
SMeshBufferTangents* buffer = new SMeshBufferTangents();
buffer->Material = mesh->getMeshBuffer(b)->getMaterial();
video::S3DVertexTangents* v =
(video::S3DVertexTangents*)mesh->getMeshBuffer(b)->getVertices();
buffer->Vertices.reallocate(idxCnt);
buffer->Indices.reallocate(idxCnt);
for (s32 i=0; i<idxCnt; i += 3)
{
buffer->Vertices.push_back( v[idx[i + 0 ]] );
buffer->Vertices.push_back( v[idx[i + 1 ]] );
buffer->Vertices.push_back( v[idx[i + 2 ]] );
buffer->Indices.push_back( i + 0 );
buffer->Indices.push_back( i + 1 );
buffer->Indices.push_back( i + 2 );
}
buffer->setBoundingBox(mesh->getMeshBuffer(b)->getBoundingBox());
clone->addMeshBuffer(buffer);
buffer->drop();
}
break;
}// end switch
}// end for all mesh buffers
clone->BoundingBox = mesh->getBoundingBox();
return clone;
}
//! Creates a copy of a mesh, which will have identical vertices welded together
IMesh* CMeshManipulator::createMeshWelded(IMesh *mesh, f32 tolerance) const
{
SMesh* clone = new SMesh();
clone->BoundingBox = mesh->getBoundingBox();
core::array<u16> redirects;
for (u32 b=0; b<mesh->getMeshBufferCount(); ++b)
{
// reset redirect list
redirects.set_used(mesh->getMeshBuffer(b)->getVertexCount());
u16* indices = 0;
u32 indexCount = 0;
core::array<u16>* outIdx = 0;
switch(mesh->getMeshBuffer(b)->getVertexType())
{
case video::EVT_STANDARD:
{
SMeshBuffer* buffer = new SMeshBuffer();
buffer->BoundingBox = mesh->getMeshBuffer(b)->getBoundingBox();
buffer->Material = mesh->getMeshBuffer(b)->getMaterial();
clone->addMeshBuffer(buffer);
buffer->drop();
video::S3DVertex* v =
(video::S3DVertex*)mesh->getMeshBuffer(b)->getVertices();
u32 vertexCount = mesh->getMeshBuffer(b)->getVertexCount();
indices = mesh->getMeshBuffer(b)->getIndices();
indexCount = mesh->getMeshBuffer(b)->getIndexCount();
outIdx = &buffer->Indices;
buffer->Vertices.reallocate(vertexCount);
for (u32 i=0; i < vertexCount; ++i)
{
bool found = false;
for (u32 j=0; j < i; ++j)
{
if ( v[i].Pos.equals( v[j].Pos, tolerance) &&
v[i].Normal.equals( v[j].Normal, tolerance) &&
v[i].TCoords.equals( v[j].TCoords ) &&
(v[i].Color == v[j].Color) )
{
redirects[i] = redirects[j];
found = true;
break;
}
}
if (!found)
{
redirects[i] = buffer->Vertices.size();
buffer->Vertices.push_back(v[i]);
}
}
break;
}
case video::EVT_2TCOORDS:
{
SMeshBufferLightMap* buffer = new SMeshBufferLightMap();
buffer->BoundingBox = mesh->getMeshBuffer(b)->getBoundingBox();
buffer->Material = mesh->getMeshBuffer(b)->getMaterial();
clone->addMeshBuffer(buffer);
buffer->drop();
video::S3DVertex2TCoords* v =
(video::S3DVertex2TCoords*)mesh->getMeshBuffer(b)->getVertices();
u32 vertexCount = mesh->getMeshBuffer(b)->getVertexCount();
indices = mesh->getMeshBuffer(b)->getIndices();
indexCount = mesh->getMeshBuffer(b)->getIndexCount();
outIdx = &buffer->Indices;
buffer->Vertices.reallocate(vertexCount);
for (u32 i=0; i < vertexCount; ++i)
{
bool found = false;
for (u32 j=0; j < i; ++j)
{
if ( v[i].Pos.equals( v[j].Pos, tolerance) &&
v[i].Normal.equals( v[j].Normal, tolerance) &&
v[i].TCoords.equals( v[j].TCoords ) &&
v[i].TCoords2.equals( v[j].TCoords2 ) &&
(v[i].Color == v[j].Color) )
{
redirects[i] = redirects[j];
found = true;
break;
}
}
if (!found)
{
redirects[i] = buffer->Vertices.size();
buffer->Vertices.push_back(v[i]);
}
}
break;
}
case video::EVT_TANGENTS:
{
SMeshBufferTangents* buffer = new SMeshBufferTangents();
buffer->BoundingBox = mesh->getMeshBuffer(b)->getBoundingBox();
buffer->Material = mesh->getMeshBuffer(b)->getMaterial();
clone->addMeshBuffer(buffer);
buffer->drop();
video::S3DVertexTangents* v =
(video::S3DVertexTangents*)mesh->getMeshBuffer(b)->getVertices();
u32 vertexCount = mesh->getMeshBuffer(b)->getVertexCount();
indices = mesh->getMeshBuffer(b)->getIndices();
indexCount = mesh->getMeshBuffer(b)->getIndexCount();
outIdx = &buffer->Indices;
buffer->Vertices.reallocate(vertexCount);
for (u32 i=0; i < vertexCount; ++i)
{
bool found = false;
for (u32 j=0; j < i; ++j)
{
if ( v[i].Pos.equals( v[j].Pos, tolerance) &&
v[i].Normal.equals( v[j].Normal, tolerance) &&
v[i].TCoords.equals( v[j].TCoords ) &&
v[i].Tangent.equals( v[j].Tangent, tolerance ) &&
v[i].Binormal.equals( v[j].Binormal, tolerance ) &&
(v[i].Color == v[j].Color) )
{
redirects[i] = redirects[j];
found = true;
break;
}
}
if (!found)
{
redirects[i] = buffer->Vertices.size();
buffer->Vertices.push_back(v[i]);
}
}
break;
}
default:
os::Printer::log("Cannot create welded mesh, vertex type unsupported", ELL_ERROR);
break;
}
// write the buffer's index list
core::array<u16> &Indices = *outIdx;
Indices.set_used(indexCount);
for (u32 i=0; i<indexCount; ++i)
{
Indices[i] = redirects[ indices[i] ];
}
}
return clone;
}
//! Creates a copy of the mesh, which will only consist of S3DVertexTangents vertices.
-IMesh* CMeshManipulator::createMeshWithTangents(IMesh* mesh, bool recalculateNormals, bool smooth, bool angleWeighted) const
+IMesh* CMeshManipulator::createMeshWithTangents(IMesh* mesh, bool recalculateNormals, bool smooth, bool angleWeighted, bool calculateTangents) const
{
if (!mesh)
return 0;
// copy mesh and fill data into SMeshBufferTangents
SMesh* clone = new SMesh();
const u32 meshBufferCount = mesh->getMeshBufferCount();
- u32 b;
- for (b=0; b<meshBufferCount; ++b)
+ for (u32 b=0; b<meshBufferCount; ++b)
{
- const u32 idxCnt = mesh->getMeshBuffer(b)->getIndexCount();
- const u16* idx = mesh->getMeshBuffer(b)->getIndices();
+ const IMeshBuffer* original = mesh->getMeshBuffer(b);
+ const u32 idxCnt = original->getIndexCount();
+ const u16* idx = original->getIndices();
SMeshBufferTangents* buffer = new SMeshBufferTangents();
- buffer->Material = mesh->getMeshBuffer(b)->getMaterial();
+
+ buffer->Material = original->getMaterial();
+ buffer->Vertices.reallocate(idxCnt);
+ buffer->Indices.set_used(idxCnt);
+
+ core::map<video::S3DVertexTangents, int> vertMap;
+ int vertLocation;
// copy vertices
- buffer->Vertices.reallocate(idxCnt);
- switch(mesh->getMeshBuffer(b)->getVertexType())
+ const video::E_VERTEX_TYPE vType = original->getVertexType();
+ video::S3DVertexTangents vNew;
+ for (u32 i=0; i<idxCnt; ++i)
{
- case video::EVT_STANDARD:
+ switch(vType)
{
- video::S3DVertex* v =
- (video::S3DVertex*)mesh->getMeshBuffer(b)->getVertices();
-
- for (u32 i=0; i<idxCnt; ++i)
- buffer->Vertices.push_back(
- video::S3DVertexTangents(
- v[idx[i]].Pos, v[idx[i]].Normal, v[idx[i]].Color, v[idx[i]].TCoords));
+ case video::EVT_STANDARD:
+ {
+ const video::S3DVertex* v =
+ (const video::S3DVertex*)original->getVertices();
+ vNew = video::S3DVertexTangents(
+ v[idx[i]].Pos, v[idx[i]].Normal, v[idx[i]].Color, v[idx[i]].TCoords);
+ }
+ break;
+ case video::EVT_2TCOORDS:
+ {
+ const video::S3DVertex2TCoords* v =
+ (const video::S3DVertex2TCoords*)original->getVertices();
+ vNew = video::S3DVertexTangents(
+ v[idx[i]].Pos, v[idx[i]].Normal, v[idx[i]].Color, v[idx[i]].TCoords);
+ }
+ break;
+ case video::EVT_TANGENTS:
+ {
+ const video::S3DVertexTangents* v =
+ (const video::S3DVertexTangents*)original->getVertices();
+ vNew = v[idx[i]];
+ }
+ break;
}
- break;
- case video::EVT_2TCOORDS:
+ core::map<video::S3DVertexTangents, int>::Node* n = vertMap.find(vNew);
+ if (n)
{
- video::S3DVertex2TCoords* v =
- (video::S3DVertex2TCoords*)mesh->getMeshBuffer(b)->getVertices();
-
- for (u32 i=0; i<idxCnt; ++i)
- buffer->Vertices.push_back(video::S3DVertexTangents(
- v[idx[i]].Pos, v[idx[i]].Normal, v[idx[i]].Color, v[idx[i]].TCoords));
+ vertLocation = n->getValue();
}
- break;
- case video::EVT_TANGENTS:
+ else
{
- video::S3DVertexTangents* v =
- (video::S3DVertexTangents*)mesh->getMeshBuffer(b)->getVertices();
-
- for (u32 i=0; i<idxCnt; ++i)
- buffer->Vertices.push_back(v[idx[i]]);
+ vertLocation = buffer->Vertices.size();
+ buffer->Vertices.push_back(vNew);
+ vertMap.insert(vNew, vertLocation);
}
- break;
- }
-
- // create new indices
-
- buffer->Indices.set_used(idxCnt);
- for (u32 i=0; i<idxCnt; ++i)
- buffer->Indices[i] = i;
- //buffer->setBoundingBox(mesh->getMeshBuffer(b)->getBoundingBox());
- buffer->recalculateBoundingBox ();
+ // create new indices
+ buffer->Indices[i] = vertLocation;
+ }
+ buffer->recalculateBoundingBox();
// add new buffer
clone->addMeshBuffer(buffer);
buffer->drop();
}
- clone->recalculateBoundingBox ();
- //clone->BoundingBox = mesh->getBoundingBox();
-
- // now calculate tangents
- for (b=0; b<meshBufferCount; ++b)
- {
- const u32 vtxCnt = mesh->getMeshBuffer(b)->getVertexCount();
- const u32 idxCnt = clone->getMeshBuffer(b)->getIndexCount();
-
- u16* idx = clone->getMeshBuffer(b)->getIndices();
- video::S3DVertexTangents* v =
- (video::S3DVertexTangents*)clone->getMeshBuffer(b)->getVertices();
-
- if (smooth)
- {
- u32 i;
-
- for ( i = 0; i!= vtxCnt; ++i )
- {
- if (recalculateNormals)
- v[i].Normal.set( 0.f, 0.f, 0.f );
- v[i].Tangent.set( 0.f, 0.f, 0.f );
- v[i].Binormal.set( 0.f, 0.f, 0.f );
- }
-
- //Each vertex gets the sum of the tangents and binormals from the faces around it
- for ( i=0; i<idxCnt; i+=3)
- {
- // if this triangle is degenerate, skip it!
- if (v[idx[i+0]].Pos == v[idx[i+1]].Pos ||
- v[idx[i+0]].Pos == v[idx[i+2]].Pos ||
- v[idx[i+1]].Pos == v[idx[i+2]].Pos
- /*||
- v[idx[i+0]].TCoords == v[idx[i+1]].TCoords ||
- v[idx[i+0]].TCoords == v[idx[i+2]].TCoords ||
- v[idx[i+1]].TCoords == v[idx[i+2]].TCoords */
- )
- continue;
-
- //Angle-weighted normals look better, but are slightly more CPU intensive to calculate
- core::vector3df weight(1.f,1.f,1.f);
- if (angleWeighted)
- weight = getAngleWeight(v[i+0].Pos,v[i+1].Pos,v[i+2].Pos);
- core::vector3df localNormal;
- core::vector3df localTangent;
- core::vector3df localBinormal;
-
- calculateTangents(
- localNormal,
- localTangent,
- localBinormal,
- v[idx[i+0]].Pos,
- v[idx[i+1]].Pos,
- v[idx[i+2]].Pos,
- v[idx[i+0]].TCoords,
- v[idx[i+1]].TCoords,
- v[idx[i+2]].TCoords);
-
- if (recalculateNormals)
- v[idx[i+0]].Normal += localNormal * weight.X;
- v[idx[i+0]].Tangent += localTangent * weight.X;
- v[idx[i+0]].Binormal += localBinormal * weight.X;
-
- calculateTangents(
- localNormal,
- localTangent,
- localBinormal,
- v[idx[i+1]].Pos,
- v[idx[i+2]].Pos,
- v[idx[i+0]].Pos,
- v[idx[i+1]].TCoords,
- v[idx[i+2]].TCoords,
- v[idx[i+0]].TCoords);
-
- if (recalculateNormals)
- v[idx[i+1]].Normal += localNormal * weight.Y;
- v[idx[i+1]].Tangent += localTangent * weight.Y;
- v[idx[i+1]].Binormal += localBinormal * weight.Y;
-
- calculateTangents(
- localNormal,
- localTangent,
- localBinormal,
- v[idx[i+2]].Pos,
- v[idx[i+0]].Pos,
- v[idx[i+1]].Pos,
- v[idx[i+2]].TCoords,
- v[idx[i+0]].TCoords,
- v[idx[i+1]].TCoords);
-
- if (recalculateNormals)
- v[idx[i+2]].Normal += localNormal * weight.Z;
- v[idx[i+2]].Tangent += localTangent * weight.Z;
- v[idx[i+2]].Binormal += localBinormal * weight.Z;
- }
-
- // Normalize the tangents and binormals
- if (recalculateNormals)
- {
- for ( i = 0; i!= vtxCnt; ++i )
- v[i].Normal.normalize();
- }
- for ( i = 0; i!= vtxCnt; ++i )
- {
- v[i].Tangent.normalize();
- v[i].Binormal.normalize();
- }
- }
- else
- {
- core::vector3df localNormal;
- for (u32 i=0; i<idxCnt; i+=3)
- {
- calculateTangents(
- localNormal,
- v[idx[i+0]].Tangent,
- v[idx[i+0]].Binormal,
- v[idx[i+0]].Pos,
- v[idx[i+1]].Pos,
- v[idx[i+2]].Pos,
- v[idx[i+0]].TCoords,
- v[idx[i+1]].TCoords,
- v[idx[i+2]].TCoords);
- if (recalculateNormals)
- v[idx[i+0]].Normal=localNormal;
-
- calculateTangents(
- localNormal,
- v[idx[i+1]].Tangent,
- v[idx[i+1]].Binormal,
- v[idx[i+1]].Pos,
- v[idx[i+2]].Pos,
- v[idx[i+0]].Pos,
- v[idx[i+1]].TCoords,
- v[idx[i+2]].TCoords,
- v[idx[i+0]].TCoords);
- if (recalculateNormals)
- v[idx[i+1]].Normal=localNormal;
-
- calculateTangents(
- localNormal,
- v[idx[i+2]].Tangent,
- v[idx[i+2]].Binormal,
- v[idx[i+2]].Pos,
- v[idx[i+0]].Pos,
- v[idx[i+1]].Pos,
- v[idx[i+2]].TCoords,
- v[idx[i+0]].TCoords,
- v[idx[i+1]].TCoords);
- if (recalculateNormals)
- v[idx[i+2]].Normal=localNormal;
- }
- }
- }
+ clone->recalculateBoundingBox();
+ if (calculateTangents)
+ recalculateTangents(clone, recalculateNormals, smooth, angleWeighted);
return clone;
}
//! Creates a copy of the mesh, which will only consist of S3DVertex2TCoords vertices.
IMesh* CMeshManipulator::createMeshWith2TCoords(IMesh* mesh) const
{
if (!mesh)
return 0;
// copy mesh and fill data into SMeshBufferLightMap
SMesh* clone = new SMesh();
const u32 meshBufferCount = mesh->getMeshBufferCount();
- u32 b;
- for (b=0; b<meshBufferCount; ++b)
+ for (u32 b=0; b<meshBufferCount; ++b)
{
- const u32 idxCnt = mesh->getMeshBuffer(b)->getIndexCount();
- const u16* idx = mesh->getMeshBuffer(b)->getIndices();
+ const IMeshBuffer* original = mesh->getMeshBuffer(b);
+ const u32 idxCnt = original->getIndexCount();
+ const u16* idx = original->getIndices();
SMeshBufferLightMap* buffer = new SMeshBufferLightMap();
- buffer->Material = mesh->getMeshBuffer(b)->getMaterial();
+ buffer->Material = original->getMaterial();
+ buffer->Vertices.reallocate(idxCnt);
+ buffer->Indices.set_used(idxCnt);
+
+ core::map<video::S3DVertex2TCoords, int> vertMap;
+ int vertLocation;
// copy vertices
- buffer->Vertices.reallocate(idxCnt);
- switch(mesh->getMeshBuffer(b)->getVertexType())
+ const video::E_VERTEX_TYPE vType = original->getVertexType();
+ video::S3DVertex2TCoords vNew;
+ for (u32 i=0; i<idxCnt; ++i)
{
- case video::EVT_STANDARD:
+ switch(vType)
{
- video::S3DVertex* v =
- (video::S3DVertex*)mesh->getMeshBuffer(b)->getVertices();
-
- for (u32 i=0; i<idxCnt; ++i)
- buffer->Vertices.push_back(
- video::S3DVertex2TCoords(
- v[idx[i]].Pos, v[idx[i]].Normal, v[idx[i]].Color, v[idx[i]].TCoords, v[idx[i]].TCoords));
+ case video::EVT_STANDARD:
+ {
+ const video::S3DVertex* v =
+ (const video::S3DVertex*)original->getVertices();
+ vNew = video::S3DVertex2TCoords(
+ v[idx[i]].Pos, v[idx[i]].Normal, v[idx[i]].Color, v[idx[i]].TCoords, v[idx[i]].TCoords);
+ }
+ break;
+ case video::EVT_2TCOORDS:
+ {
+ const video::S3DVertex2TCoords* v =
+ (const video::S3DVertex2TCoords*)original->getVertices();
+ vNew = v[idx[i]];
+ }
+ break;
+ case video::EVT_TANGENTS:
+ {
+ const video::S3DVertexTangents* v =
+ (const video::S3DVertexTangents*)original->getVertices();
+ vNew = video::S3DVertex2TCoords(
+ v[idx[i]].Pos, v[idx[i]].Normal, v[idx[i]].Color, v[idx[i]].TCoords, v[idx[i]].TCoords);
+ }
+ break;
}
- break;
- case video::EVT_2TCOORDS:
+ core::map<video::S3DVertex2TCoords, int>::Node* n = vertMap.find(vNew);
+ if (n)
{
- video::S3DVertex2TCoords* v =
- (video::S3DVertex2TCoords*)mesh->getMeshBuffer(b)->getVertices();
-
- for (u32 i=0; i<idxCnt; ++i)
- buffer->Vertices.push_back(v[idx[i]]);
+ vertLocation = n->getValue();
}
- break;
- case video::EVT_TANGENTS:
+ else
{
- video::S3DVertexTangents* v =
- (video::S3DVertexTangents*)mesh->getMeshBuffer(b)->getVertices();
-
- for (u32 i=0; i<idxCnt; ++i)
- buffer->Vertices.push_back(video::S3DVertex2TCoords(
- v[idx[i]].Pos, v[idx[i]].Normal, v[idx[i]].Color, v[idx[i]].TCoords, v[idx[i]].TCoords));
+ vertLocation = buffer->Vertices.size();
+ buffer->Vertices.push_back(vNew);
+ vertMap.insert(vNew, vertLocation);
}
- break;
- }
-
- // create new indices
-
- buffer->Indices.set_used(idxCnt);
- for (u32 i=0; i<idxCnt; ++i)
- buffer->Indices[i] = i;
- //buffer->setBoundingBox(mesh->getMeshBuffer(b)->getBoundingBox());
- buffer->recalculateBoundingBox ();
+ // create new indices
+ buffer->Indices[i] = vertLocation;
+ }
+ buffer->recalculateBoundingBox();
// add new buffer
clone->addMeshBuffer(buffer);
buffer->drop();
}
- clone->recalculateBoundingBox ();
- //clone->BoundingBox = mesh->getBoundingBox();
-
+ clone->recalculateBoundingBox();
return clone;
}
//! Creates a copy of the mesh, which will only consist of S3DVertex vertices.
IMesh* CMeshManipulator::createMeshWith1TCoords(IMesh* mesh) const
{
if (!mesh)
return 0;
// copy mesh and fill data into SMeshBuffer
SMesh* clone = new SMesh();
const u32 meshBufferCount = mesh->getMeshBufferCount();
- u32 b;
- for (b=0; b<meshBufferCount; ++b)
+ for (u32 b=0; b<meshBufferCount; ++b)
{
const IMeshBuffer* original = mesh->getMeshBuffer(b);
const u32 idxCnt = original->getIndexCount();
const u16* idx = original->getIndices();
SMeshBuffer* buffer = new SMeshBuffer();
buffer->Material = original->getMaterial();
buffer->Vertices.reallocate(idxCnt);
buffer->Indices.set_used(idxCnt);
core::map<video::S3DVertex, int> vertMap;
int vertLocation;
// copy vertices
const video::E_VERTEX_TYPE vType = original->getVertexType();
video::S3DVertex vNew;
for (u32 i=0; i<idxCnt; ++i)
{
switch(vType)
{
case video::EVT_STANDARD:
{
video::S3DVertex* v =
(video::S3DVertex*)original->getVertices();
vNew = v[idx[i]];
}
break;
case video::EVT_2TCOORDS:
{
video::S3DVertex2TCoords* v =
(video::S3DVertex2TCoords*)original->getVertices();
vNew = video::S3DVertex(
v[idx[i]].Pos, v[idx[i]].Normal, v[idx[i]].Color, v[idx[i]].TCoords);
}
break;
case video::EVT_TANGENTS:
{
video::S3DVertexTangents* v =
(video::S3DVertexTangents*)original->getVertices();
vNew = video::S3DVertex(
v[idx[i]].Pos, v[idx[i]].Normal, v[idx[i]].Color, v[idx[i]].TCoords);
}
break;
}
core::map<video::S3DVertex, int>::Node* n = vertMap.find(vNew);
if (n)
{
vertLocation = n->getValue();
}
else
{
vertLocation = buffer->Vertices.size();
buffer->Vertices.push_back(vNew);
vertMap.insert(vNew, vertLocation);
}
// create new indices
buffer->Indices[i] = vertLocation;
}
-
- //buffer->setBoundingBox(mesh->getMeshBuffer(b)->getBoundingBox());
- buffer->recalculateBoundingBox ();
+ buffer->recalculateBoundingBox();
// add new buffer
clone->addMeshBuffer(buffer);
buffer->drop();
}
clone->recalculateBoundingBox();
return clone;
}
void CMeshManipulator::calculateTangents(
core::vector3df& normal,
core::vector3df& tangent,
core::vector3df& binormal,
const core::vector3df& vt1, const core::vector3df& vt2, const core::vector3df& vt3, // vertices
const core::vector2df& tc1, const core::vector2df& tc2, const core::vector2df& tc3) // texture coords
{
// choose one of them:
//#define USE_NVIDIA_GLH_VERSION // use version used by nvidia in glh headers
#define USE_IRR_VERSION
#ifdef USE_IRR_VERSION
core::vector3df v1 = vt1 - vt2;
core::vector3df v2 = vt3 - vt1;
normal = v2.crossProduct(v1);
normal.normalize();
// binormal
f32 deltaX1 = tc1.X - tc2.X;
f32 deltaX2 = tc3.X - tc1.X;
binormal = (v1 * deltaX2) - (v2 * deltaX1);
binormal.normalize();
// tangent
f32 deltaY1 = tc1.Y - tc2.Y;
f32 deltaY2 = tc3.Y - tc1.Y;
tangent = (v1 * deltaY2) - (v2 * deltaY1);
tangent.normalize();
// adjust
core::vector3df txb = tangent.crossProduct(binormal);
if (txb.dotProduct(normal) < 0.0f)
{
tangent *= -1.0f;
binormal *= -1.0f;
}
#endif // USE_IRR_VERSION
#ifdef USE_NVIDIA_GLH_VERSION
tangent.set(0,0,0);
binormal.set(0,0,0);
core::vector3df v1(vt2.X - vt1.X, tc2.X - tc1.X, tc2.Y - tc1.Y);
core::vector3df v2(vt3.X - vt1.X, tc3.X - tc1.X, tc3.Y - tc1.Y);
core::vector3df txb = v1.crossProduct(v2);
if ( !core::iszero ( txb.X ) )
{
tangent.X = -txb.Y / txb.X;
binormal.X = -txb.Z / txb.X;
}
v1.X = vt2.Y - vt1.Y;
v2.X = vt3.Y - vt1.Y;
txb = v1.crossProduct(v2);
if ( !core::iszero ( txb.X ) )
{
tangent.Y = -txb.Y / txb.X;
binormal.Y = -txb.Z / txb.X;
}
v1.X = vt2.Z - vt1.Z;
v2.X = vt3.Z - vt1.Z;
txb = v1.crossProduct(v2);
if ( !core::iszero ( txb.X ) )
{
tangent.Z = -txb.Y / txb.X;
binormal.Z = -txb.Z / txb.X;
}
tangent.normalize();
binormal.normalize();
normal = tangent.crossProduct(binormal);
normal.normalize();
binormal = tangent.crossProduct(normal);
binormal.normalize();
core::plane3d<f32> pl(vt1, vt2, vt3);
if(normal.dotProduct(pl.Normal) < 0.0f )
normal *= -1.0f;
#endif // USE_NVIDIA_GLH_VERSION
}
//! Returns amount of polygons in mesh.
s32 CMeshManipulator::getPolyCount(scene::IMesh* mesh) const
{
if (!mesh)
return 0;
s32 trianglecount = 0;
for (u32 g=0; g<mesh->getMeshBufferCount(); ++g)
trianglecount += mesh->getMeshBuffer(g)->getIndexCount() / 3;
return trianglecount;
}
//! Returns amount of polygons in mesh.
s32 CMeshManipulator::getPolyCount(scene::IAnimatedMesh* mesh) const
{
if (mesh && mesh->getFrameCount() != 0)
return getPolyCount(mesh->getMesh(0));
return 0;
}
//! create a new AnimatedMesh and adds the mesh to it
IAnimatedMesh * CMeshManipulator::createAnimatedMesh(scene::IMesh* mesh, scene::E_ANIMATED_MESH_TYPE type) const
{
return new SAnimatedMesh(mesh, type);
}
} // end namespace scene
} // end namespace irr
diff --git a/source/Irrlicht/CMeshManipulator.h b/source/Irrlicht/CMeshManipulator.h
index bc92b2c..cb75b8c 100644
--- a/source/Irrlicht/CMeshManipulator.h
+++ b/source/Irrlicht/CMeshManipulator.h
@@ -1,91 +1,94 @@
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_MESH_MANIPULATOR_H_INCLUDED__
#define __C_MESH_MANIPULATOR_H_INCLUDED__
#include "IMeshManipulator.h"
namespace irr
{
namespace scene
{
//! An interface for easy manipulation of meshes.
/** Scale, set alpha value, flip surfaces, and so on. This exists for fixing
problems with wrong imported or exported meshes quickly after loading. It is
not intended for doing mesh modifications and/or animations during runtime.
*/
class CMeshManipulator : public IMeshManipulator
{
public:
//! Flips the direction of surfaces.
/** Changes backfacing triangles to frontfacing triangles and vice versa.
\param mesh: Mesh on which the operation is performed. */
virtual void flipSurfaces(scene::IMesh* mesh) const;
//! Recalculates all normals of the mesh.
/** \param mesh: Mesh on which the operation is performed.
\param smooth: Whether to use smoothed normals. */
virtual void recalculateNormals(scene::IMesh* mesh, bool smooth = false, bool angleWeighted = false) const;
//! Recalculates all normals of the mesh buffer.
/** \param buffer: Mesh buffer on which the operation is performed.
\param smooth: Whether to use smoothed normals. */
virtual void recalculateNormals(IMeshBuffer* buffer, bool smooth = false, bool angleWeighted = false) const;
//! Clones a static IMesh into a modifiable SMesh.
virtual SMesh* createMeshCopy(scene::IMesh* mesh) const;
//! Creates a planar texture mapping on the mesh
/** \param mesh: Mesh on which the operation is performed.
\param resolution: resolution of the planar mapping. This is the value
specifying which is the relation between world space and
texture coordinate space. */
virtual void makePlanarTextureMapping(scene::IMesh* mesh, f32 resolution) const;
//! Creates a planar texture mapping on the meshbuffer
virtual void makePlanarTextureMapping(scene::IMeshBuffer* meshbuffer, f32 resolution=0.001f) const;
//! Creates a planar texture mapping on the meshbuffer
void makePlanarTextureMapping(scene::IMeshBuffer* buffer, f32 resolutionS, f32 resolutionT, u8 axis, const core::vector3df& offset) const;
+ //! Recalculates tangents, requires a tangent mesh
+ virtual void recalculateTangents(IMesh* mesh, bool recalculateNormals=false, bool smooth=false, bool angleWeighted=false) const;
+
//! Creates a copy of the mesh, which will only consist of S3DVertexTangents vertices.
- virtual IMesh* createMeshWithTangents(IMesh* mesh, bool recalculateNormals=false, bool smooth=false, bool angleWeighted=false) const;
+ virtual IMesh* createMeshWithTangents(IMesh* mesh, bool recalculateNormals=false, bool smooth=false, bool angleWeighted=false, bool recalculateTangents=true) const;
//! Creates a copy of the mesh, which will only consist of S3D2TCoords vertices.
virtual IMesh* createMeshWith2TCoords(IMesh* mesh) const;
//! Creates a copy of the mesh, which will only consist of S3DVertex vertices.
virtual IMesh* createMeshWith1TCoords(IMesh* mesh) const;
//! Creates a copy of the mesh, which will only consist of unique triangles, i.e. no vertices are shared.
virtual IMesh* createMeshUniquePrimitives(IMesh* mesh) const;
//! Creates a copy of the mesh, which will have all duplicated vertices removed, i.e. maximal amount of vertices are shared via indexing.
virtual IMesh* createMeshWelded(IMesh *mesh, f32 tolerance=core::ROUNDING_ERROR_f32) const;
//! Returns amount of polygons in mesh.
virtual s32 getPolyCount(scene::IMesh* mesh) const;
//! Returns amount of polygons in mesh.
virtual s32 getPolyCount(scene::IAnimatedMesh* mesh) const;
//! create a new AnimatedMesh and adds the mesh to it
virtual IAnimatedMesh * createAnimatedMesh(scene::IMesh* mesh,scene::E_ANIMATED_MESH_TYPE type) const;
private:
static void calculateTangents(core::vector3df& normal,
core::vector3df& tangent,
core::vector3df& binormal,
const core::vector3df& vt1, const core::vector3df& vt2, const core::vector3df& vt3,
const core::vector2df& tc1, const core::vector2df& tc2, const core::vector2df& tc3);
};
} // end namespace scene
} // end namespace irr
#endif
diff --git a/tests/tests-last-passed-at.txt b/tests/tests-last-passed-at.txt
index 59eb1fd..16c6adc 100644
--- a/tests/tests-last-passed-at.txt
+++ b/tests/tests-last-passed-at.txt
@@ -1,4 +1,4 @@
Tests finished. 51 tests of 51 passed.
Compiled as DEBUG
-Test suite pass at GMT Tue Jan 26 01:36:48 2010
+Test suite pass at GMT Tue Jan 26 11:59:00 2010
|
tinku99/ahkdll
|
c8a1fd5186bd4cad716b506d9f9cd9a158652f80
|
removing more clipboard stuff
|
diff --git a/source/clipboard.cpp b/source/clipboard.cpp
index fa8c15d..b253d5c 100644
--- a/source/clipboard.cpp
+++ b/source/clipboard.cpp
@@ -1,513 +1,516 @@
/*
AutoHotkey
Copyright 2003-2009 Chris Mallett ([email protected])
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "stdafx.h" // pre-compiled headers
#include "clipboard.h"
#include "globaldata.h" // for g_script.ScriptError() and g_ClipboardTimeout
#include "application.h" // for MsgSleep()
#include "util.h" // for strlcpy()
size_t Clipboard::Get(LPTSTR aBuf)
// If aBuf is NULL, it returns the length of the text on the clipboard and leaves the
// clipboard open. Otherwise, it copies the clipboard text into aBuf and closes
// the clipboard (UPDATE: But only if the clipboard is still open from a prior call
// to determine the length -- see later comments for details). In both cases, the
// length of the clipboard text is returned (or the value CLIPBOARD_FAILURE if error).
// If the clipboard is still open when the next MsgSleep() is called -- presumably
// because the caller never followed up with a second call to this function, perhaps
// due to having insufficient memory -- MsgSleep() will close it so that our
// app doesn't keep the clipboard tied up. Note: In all current cases, the caller
// will use MsgBox to display an error, which in turn calls MsgSleep(), which will
// immediately close the clipboard.
{
// Seems best to always have done this even if we return early due to failure:
if (aBuf)
// It should be safe to do this even at its peak capacity, because caller
// would have then given us the last char in the buffer, which is already
// a zero terminator, so this would have no effect:
*aBuf = '\0';
+
UINT i, file_count = 0;
BOOL clipboard_contains_text = IsClipboardFormatAvailable(CF_NATIVETEXT);
BOOL clipboard_contains_files = IsClipboardFormatAvailable(CF_HDROP);
if (!(clipboard_contains_text || clipboard_contains_files))
return 0;
+ return 0; // sandbox
+
if (!mIsOpen)
{
// As a precaution, don't give the caller anything from the clipboard
// if the clipboard isn't already open from the caller's previous
// call to determine the size of what's on the clipboard (no other app
// can alter its size while we have it open). The is to prevent a
// buffer overflow from happening in a scenario such as the following:
// Caller calls us and we return zero size, either because there's no
// CF_TEXT on the clipboard or there was a problem opening the clipboard.
// In these two cases, the clipboard isn't open, so by the time the
// caller calls us again, there's a chance (vanishingly small perhaps)
// that another app (if our thread were preempted long enough, or the
// platform is multiprocessor) will have changed the contents of the
// clipboard to something larger than zero. Thus, if we copy that
// into the caller's buffer, the buffer might overflow:
if (aBuf)
return 0;
if (!Open())
{
// Since this should be very rare, a shorter message is now used. Formerly, it was
// "Could not open clipboard for reading after many timed attempts. Another program is probably holding it open."
Close(CANT_OPEN_CLIPBOARD_READ);
return CLIPBOARD_FAILURE;
}
if ( !(mClipMemNow = g_clip.GetClipboardDataTimeout(clipboard_contains_text ? CF_NATIVETEXT : CF_HDROP)) )
{
// v1.0.47.04: Commented out the following that had been in effect when clipboard_contains_files==false:
// Close("GetClipboardData"); // Short error message since so rare.
// return CLIPBOARD_FAILURE;
// This was done because there are situations when GetClipboardData can fail indefinitely.
// For example, in Firefox, pulling down the Bookmarks menu then right-clicking "Bookmarks Toolbar
// Folder" then selecting "Copy" puts one or more formats on the clipboard that cause this problem.
// For details, search the forum for TYMED_NULL.
//
// v1.0.42.03: For the fix below, GetClipboardDataTimeout() knows not to try more than once
// for CF_HDROP.
// Fix for v1.0.31.02: When clipboard_contains_files==true, tolerate failure, which happens
// as a normal/expected outcome when there are files on the clipboard but either:
// 1) zero of them;
// 2) the CF_HDROP on the clipboard is somehow misformatted.
// If you select the parent ".." folder in WinRar then use the following hotkey, the script
// would previously yield a runtime error:
//#q::
//Send, ^c
//ClipWait, 0.5, 1
//msgbox %Clipboard%
//Return
Close();
if (aBuf)
*aBuf = '\0';
return CLIPBOARD_FAILURE; // Return this because otherwise, Contents() returns mClipMemNowLocked, which is NULL.
}
// Although GlobalSize(mClipMemNow) can yield zero in some cases -- in which case GlobalLock() should
// not be attempted -- it probably can't yield zero for CF_HDROP and CF_TEXT because such a thing has
// never been reported by anyone. Therefore, GlobalSize() is currently not called.
if ( !(mClipMemNowLocked = (LPTSTR)GlobalLock(mClipMemNow)) )
{
Close(_T("GlobalLock")); // Short error message since so rare.
return CLIPBOARD_FAILURE;
}
// Otherwise: Update length after every successful new open&lock:
// Determine the length (size - 1) of the buffer than would be
// needed to hold what's on the clipboard:
if (clipboard_contains_text)
{
// See below for comments.
mLength = _tcslen(mClipMemNowLocked);
}
else // clipboard_contains_files
{
if (file_count = DragQueryFile((HDROP)mClipMemNowLocked, 0xFFFFFFFF, _T(""), 0))
{
mLength = (file_count - 1) * 2; // Init; -1 if don't want a newline after last file.
for (i = 0; i < file_count; ++i)
mLength += DragQueryFile((HDROP)mClipMemNowLocked, i, NULL, 0);
}
else
mLength = 0;
}
if (mLength >= CLIPBOARD_FAILURE) // Can't realistically happen, so just indicate silent failure.
return CLIPBOARD_FAILURE;
}
if (!aBuf)
return mLength;
// Above: Just return the length; don't close the clipboard because we expect
// to be called again soon. If for some reason we aren't called, MsgSleep()
// will automatically close the clipboard and clean up things. It's done this
// way to avoid the chance that the clipboard contents (and thus its length)
// will change while we don't have it open, possibly resulting in a buffer
// overflow. In addition, this approach performs better because it avoids
// the overhead of having to close and reopen the clipboard.
// Otherwise:
if (clipboard_contains_text) // Fixed for v1.1.16.02: Prefer text over files if both are present.
{
// Because the clipboard is being retrieved as text, return this text even if
// the clipboard also contains files. Contents() relies on this since it only
// calls Get() once and does not provide a buffer. Contents() would be used
// in "c := Clipboard" or "MsgBox %Clipboard%" because ArgMustBeDereferenced()
// returns true only if the clipboard contains files but not text.
_tcscpy(aBuf, mClipMemNowLocked); // Caller has already ensured that aBuf is large enough.
}
else // clipboard_contains_files
{
if (file_count = DragQueryFile((HDROP)mClipMemNowLocked, 0xFFFFFFFF, _T(""), 0))
for (i = 0; i < file_count; ++i)
{
// Caller has already ensured aBuf is large enough to hold them all:
aBuf += DragQueryFile((HDROP)mClipMemNowLocked, i, aBuf, 999);
if (i < file_count - 1) // i.e. don't add newline after the last filename.
{
*aBuf++ = '\r'; // These two are the proper newline sequence that the OS prefers.
*aBuf++ = '\n';
}
//else DragQueryFile() has ensured that aBuf is terminated.
}
// else aBuf has already been terminated upon entrance to this function.
}
// Fix for v1.0.37: Close() is no longer called here because it prevents the clipboard variable
// from being referred to more than once in a line. For example:
// Msgbox %Clipboard%%Clipboard%
// ToolTip % StrLen(Clipboard) . Clipboard
// Instead, the clipboard is later closed in other places (search on CLOSE_CLIPBOARD_IF_OPEN
// to find them). The alternative to fixing it this way would be to let it reopen the clipboard
// by means getting rid of the following lines above:
//if (aBuf)
// return 0;
// However, that has the risks described in the comments above those two lines.
return mLength;
}
ResultType Clipboard::Set(LPCTSTR aBuf, UINT_PTR aLength)
// Returns OK or FAIL.
{
// It was already open for writing from a prior call. Return failure because callers that do this
// are probably handling things wrong:
if (IsReadyForWrite()) return FAIL;
if (!aBuf)
{
aBuf = _T("");
aLength = 0;
}
else
if (aLength == UINT_MAX) // Caller wants us to determine the length.
aLength = (UINT)_tcslen(aBuf);
if (aLength)
{
if (!PrepareForWrite(aLength + 1))
return FAIL; // It already displayed the error.
tcslcpy(mClipMemNewLocked, aBuf, aLength + 1); // Copy only a substring, if aLength specifies such.
}
// else just do the below to empty the clipboard, which is different than setting
// the clipboard equal to the empty string: it's not truly empty then, as reported
// by IsClipboardFormatAvailable(CF_TEXT) -- and we want to be able to make it truly
// empty for use with functions such as ClipWait:
return Commit(); // It will display any errors.
}
LPTSTR Clipboard::PrepareForWrite(size_t aAllocSize)
{
if (!aAllocSize) return NULL; // Caller should ensure that size is at least 1, i.e. room for the zero terminator.
if (IsReadyForWrite())
// It was already prepared due to a prior call. Currently, the most useful thing to do
// here is return the memory area that's already been reserved:
return mClipMemNewLocked;
// Note: I think GMEM_DDESHARE is recommended in addition to the usual GMEM_MOVEABLE:
// UPDATE: MSDN: "The following values are obsolete, but are provided for compatibility
// with 16-bit Windows. They are ignored.": GMEM_DDESHARE
if ( !(mClipMemNew = GlobalAlloc(GMEM_MOVEABLE, aAllocSize * sizeof(TCHAR))) )
{
g_script.ScriptError(_T("GlobalAlloc")); // Short error message since so rare.
return NULL;
}
if ( !(mClipMemNewLocked = (LPTSTR)GlobalLock(mClipMemNew)) )
{
mClipMemNew = GlobalFree(mClipMemNew); // This keeps mClipMemNew in sync with its state.
g_script.ScriptError(_T("GlobalLock")); // Short error message since so rare.
return NULL;
}
mCapacity = (UINT)aAllocSize; // Keep mCapacity in sync with the state of mClipMemNewLocked.
*mClipMemNewLocked = '\0'; // Init for caller.
return mClipMemNewLocked; // The caller can now write to this mem.
}
ResultType Clipboard::Commit(UINT aFormat)
// If this is called while mClipMemNew is NULL, the clipboard will be set to be truly
// empty, which is different from writing an empty string to it. Note: If the clipboard
// was already physically open, this function will close it as part of the commit (since
// whoever had it open before can't use the prior contents, since they're invalid).
{
if (!mIsOpen && !Open())
// Since this should be very rare, a shorter message is now used. Formerly, it was
// "Could not open clipboard for writing after many timed attempts. Another program is probably holding it open."
return AbortWrite(CANT_OPEN_CLIPBOARD_WRITE);
if (!EmptyClipboard())
{
Close();
return AbortWrite(_T("EmptyClipboard")); // Short error message since so rare.
}
if (mClipMemNew)
{
bool new_is_empty = false;
// Unlock prior to calling SetClipboardData:
if (mClipMemNewLocked) // probably always true if we're here.
{
// Best to access the memory while it's still locked, which is why this temp var is used:
// v1.0.40.02: The following was fixed to properly recognize 0x0000 as the Unicode string terminator,
// which fixes problems with Transform Unicode.
new_is_empty = aFormat == CF_UNICODETEXT ? !*(LPWSTR)mClipMemNewLocked : !*(LPSTR)mClipMemNewLocked;
GlobalUnlock(mClipMemNew); // mClipMemNew not mClipMemNewLocked.
mClipMemNewLocked = NULL; // Keep this in sync with the above action.
mCapacity = 0; // Keep mCapacity in sync with the state of mClipMemNewLocked.
}
if (new_is_empty)
// Leave the clipboard truly empty rather than setting it to be the
// empty string (i.e. these two conditions are NOT the same).
// But be sure to free the memory since we're not giving custody
// of it to the system:
mClipMemNew = GlobalFree(mClipMemNew);
else
if (SetClipboardData(aFormat, mClipMemNew))
// In any of the failure conditions above, Close() ensures that mClipMemNew is
// freed if it was allocated. But now that we're here, the memory should not be
// freed because it is owned by the clipboard (it will free it at the appropriate time).
// Thus, we relinquish the memory because we shouldn't be looking at it anymore:
mClipMemNew = NULL;
else
{
Close();
return AbortWrite(_T("SetClipboardData")); // Short error message since so rare.
}
}
// else we will close it after having done only the EmptyClipboard(), above.
// Note: Decided not to update mLength for performance reasons (in case clipboard is huge).
// Anyway, it seems rather pointless because once the clipboard is closed, our app instantly
// loses sight of how large it is, so the the value of mLength wouldn't be reliable unless
// the clipboard were going to be immediately opened again.
return Close();
}
ResultType Clipboard::AbortWrite(LPTSTR aErrorMessage)
// Always returns FAIL.
{
// Since we were called in conjunction with an aborted attempt to Commit(), always
// ensure the clipboard is physically closed because even an attempt to Commit()
// should physically close it:
Close();
if (mClipMemNewLocked)
{
GlobalUnlock(mClipMemNew); // mClipMemNew not mClipMemNewLocked.
mClipMemNewLocked = NULL;
mCapacity = 0; // Keep mCapacity in sync with the state of mClipMemNewLocked.
}
// Above: Unlock prior to freeing below.
if (mClipMemNew)
mClipMemNew = GlobalFree(mClipMemNew);
// Caller needs us to always return FAIL:
return *aErrorMessage ? g_script.ScriptError(aErrorMessage) : FAIL;
}
ResultType Clipboard::Close(LPTSTR aErrorMessage)
// Returns OK or FAIL (but it only returns FAIL if caller gave us a non-NULL aErrorMessage).
{
// Always close it ASAP so that it is free for other apps to use:
if (mIsOpen)
{
if (mClipMemNowLocked)
{
GlobalUnlock(mClipMemNow); // mClipMemNow not mClipMemNowLocked.
mClipMemNowLocked = NULL; // Keep this in sync with its state, since it's used as an indicator.
}
// Above: It's probably best to unlock prior to closing the clipboard.
CloseClipboard();
mIsOpen = false; // Even if above fails (realistically impossible?), seems best to do this.
// Must do this only after GlobalUnlock():
mClipMemNow = NULL;
}
// Do this cleanup for callers that didn't make it far enough to even open the clipboard.
// UPDATE: DO *NOT* do this because it is valid to have the clipboard in a "ReadyForWrite"
// state even after we physically close it. Some callers rely on that.
//if (mClipMemNewLocked)
//{
// GlobalUnlock(mClipMemNew); // mClipMemNew not mClipMemNewLocked.
// mClipMemNewLocked = NULL;
// mCapacity = 0; // Keep mCapacity in sync with the state of mClipMemNewLocked.
//}
//// Above: Unlock prior to freeing below.
//if (mClipMemNew)
// // Commit() was never called after a call to PrepareForWrite(), so just free the memory:
// mClipMemNew = GlobalFree(mClipMemNew);
if (aErrorMessage && *aErrorMessage)
// Caller needs us to always return FAIL if an error was displayed:
return g_script.ScriptError(aErrorMessage);
// Seems best not to reset mLength. But it will quickly become out of date once
// the clipboard has been closed and other apps can use it.
return OK;
}
HANDLE Clipboard::GetClipboardDataTimeout(UINT uFormat, BOOL *aNullIsOkay)
// Update for v1.1.16: The comments below are obsolete; search for "v1.1.16" for related comments.
// Same as GetClipboardData() except that it doesn't give up if the first call to GetClipboardData() fails.
// Instead, it continues to retry the operation for the number of milliseconds in g_ClipboardTimeout.
// This is necessary because GetClipboardData() has been observed to fail in repeatable situations (this
// is strange because our thread already has the clipboard locked open -- presumably it happens because the
// GetClipboardData() is unable to start a data stream from the application that actually serves up the data).
// If cases where the first call to GetClipboardData() fails, a subsequent call will often succeed if you give
// the owning application (such as Excel and Word) a little time to catch up. This is especially necessary in
// the OnClipboardChange label, where sometimes a clipboard-change notification comes in before the owning
// app has finished preparing its data for subsequent readers of the clipboard.
{
#ifdef DEBUG_BY_LOGGING_CLIPBOARD_FORMATS // Provides a convenient log of clipboard formats for analysis.
static FILE *fp = fopen("c:\\debug_clipboard_formats.txt", "w");
#endif
if (aNullIsOkay)
*aNullIsOkay = FALSE; // Set default.
TCHAR format_name[MAX_PATH + 1]; // MSDN's RegisterClipboardFormat() doesn't document any max length, but the ones we're interested in certainly don't exceed MAX_PATH.
if (uFormat < 0xC000 || uFormat > 0xFFFF) // It's a registered format (you're supposed to verify in-range before calling GetClipboardFormatName()). Also helps performance.
*format_name = '\0'; // Don't need the name if it's a standard/CF_* format.
else
{
// v1.0.42.04:
// Probably need to call GetClipboardFormatName() rather than comparing directly to uFormat because
// MSDN implies that OwnerLink and other registered formats might not always have the same ID under
// all OSes (past and future).
GetClipboardFormatName(uFormat, format_name, MAX_PATH);
// Since RegisterClipboardFormat() is case insensitive, the case might vary. So use stricmp() when
// comparing format_name to anything.
// "Link Source", "Link Source Descriptor" , and anything else starting with "Link Source" is likely
// to be data that should not be attempted to be retrieved because:
// 1) It causes unwanted bookmark effects in various versions of MS Word.
// 2) Tests show that these formats are on the clipboard only if MS Word is open at the time
// ClipboardAll is accessed. That implies they're transitory formats that aren't as essential
// or well suited to ClipboardAll as the other formats (but if it weren't for #1 above, this
// wouldn't be enough reason to omit it).
// 3) Although there is hardly any documentation to be found at MSDN or elsewhere about these formats,
// it seems they're related to OLE, with further implications that the data is transitory.
// Here are the formats that Word 2002 removes from the clipboard when it the app closes:
// 0xC002 ObjectLink >>> Causes WORD bookmarking problem.
// 0xC003 OwnerLink
// 0xC00D Link Source >>> Causes WORD bookmarking problem.
// 0xC00F Link Source Descriptor >>> Doesn't directly cause bookmarking, but probably goes with above.
// 0xC0DC Hyperlink
if ( !_tcsnicmp(format_name, _T("Link Source"), 11) || !_tcsicmp(format_name, _T("ObjectLink"))
|| !_tcsicmp(format_name, _T("OwnerLink"))
// v1.0.44.07: The following were added to solve interference with MS Outlook's MS Word editor.
// If a hotkey like ^F1::ClipboardSave:=ClipboardAll is pressed after pressing Ctrl-C in that
// editor (perhaps only when copying HTML), two of the following error dialogs would otherwise
// be displayed (this occurs in Outlook 2002 and probably later versions):
// "An outgoing call cannot be made since the application is dispatching an input-synchronous call."
|| !_tcsicmp(format_name, _T("Native")) || !_tcsicmp(format_name, _T("Embed Source")) )
return NULL;
if (!_tcsicmp(format_name, _T("MSDEVColumnSelect")) || !_tcsicmp(format_name, _T("MSDEVLineSelect")))
{
// v1.1.16: These formats are used by Visual Studio, Scintilla controls and perhaps others for
// copying whole lines and rectangular blocks. Because their very presence/absence is used as
// a boolean indicator, the data is irrelevant. Presumably for this reason, Scintilla controls
// set NULL data, though doing so and then not handling WM_RENDERFORMAT is probably invalid.
// Note newer versions of Visual Studio use "VisualStudioEditorOperationsLineCutCopyClipboardTag"
// for line copy, but that doesn't need to be handled here because it has non-NULL data (and the
// latest unreleased Scintilla [as at 2014-08-19] uses both, so we can discard the long one).
// Since we just want to preserve this format's presence, indicate to caller that NULL is okay:
if (aNullIsOkay) // i.e. caller passed a variable for us to set.
*aNullIsOkay = TRUE;
return NULL;
}
}
#ifdef DEBUG_BY_LOGGING_CLIPBOARD_FORMATS
_ftprintf(fp, _T("%04X\t%s\n"), uFormat, format_name); // Since fclose() is never called, the program has to exit to close/release the file.
#endif
#ifndef ENABLE_CLIPBOARDGETDATA_TIMEOUT
// v1.1.16: The timeout and retry behaviour of this function is currently disabled, since it does more
// harm than good. It previously did NO GOOD WHATSOEVER, because SLEEP_WITHOUT_INTERRUPTION indirectly
// calls g_clip.Close() via CLOSE_CLIPBOARD_IF_OPEN, so any subsequent attempts to retrieve data by us
// or our caller always fail. The main point of failure where retrying helps is OpenClipboard(), when
// another program has the clipboard open -- and that's handled elsewhere. If the timeout is re-enabled
// for this function, the following format will need to be excluded to prevent unnecessary delays:
// - FileContents (CSTR_FILECONTENTS): MSDN says it is used "to transfer data as if it were a file,
// regardless of how it is actually stored". For example, it could be a file inside a zip folder.
// However, on Windows 8 it seems to also be present for normal files. It might be possible to
// retrieve its data via OleGetClipboard(), though it could be very large.
// Just return the data, even if NULL:
return GetClipboardData(uFormat);
#else
HANDLE h;
DWORD aThreadID = GetCurrentThreadId(); // Used to identify if code is called from different thread (AutoHotkey.dll)
for (DWORD start_time = GetTickCount();;)
{
// Known failure conditions:
// GetClipboardData() apparently fails when the text on the clipboard is greater than a certain size
// (Even though GetLastError() reports "Operation completed successfully"). The data size at which
// this occurs is somewhere between 20 to 96 MB (perhaps depending on system's memory and CPU speed).
if (h = GetClipboardData(uFormat)) // Assign
return h;
// It failed, so act according to the type of format and the timeout that's in effect.
// Certain standard (numerically constant) clipboard formats are known to validly yield NULL from a
// call to GetClipboardData(). Never retry these because it would only cause unnecessary delays
// (i.e. a failure until timeout).
// v1.0.42.04: More importantly, retrying them appears to cause problems with saving a Word/Excel
// clipboard via ClipboardAll.
if (uFormat == CF_HDROP // This format can fail "normally" for the reasons described at "clipboard_contains_files".
|| !_tcsicmp(format_name, _T("OwnerLink"))) // Known to validly yield NULL from a call to GetClipboardData(), so don't retry it to avoid having to wait the full timeout period.
return NULL;
if (g_ClipboardTimeout != -1) // We were not told to wait indefinitely and...
if (!g_ClipboardTimeout // ...we were told to make only one attempt, or ...
|| (int)(g_ClipboardTimeout - (GetTickCount() - start_time)) <= SLEEP_INTERVAL_HALF) //...it timed out.
// Above must cast to int or any negative result will be lost due to DWORD type.
return NULL;
// Use SLEEP_WITHOUT_INTERRUPTION to prevent MainWindowProc() from accepting new hotkeys
// during our operation, since a new hotkey subroutine might interfere with
// what we're doing here (e.g. if it tries to use the clipboard, or perhaps overwrites
// the deref buffer if this object's caller gave it any pointers into that memory area):
SLEEP_WITHOUT_INTERRUPTION(INTERVAL_UNSPECIFIED)
}
#endif
}
ResultType Clipboard::Open()
{
if (mIsOpen)
return OK;
DWORD aThreadID = GetCurrentThreadId(); // Used to identify if code is called from different thread (AutoHotkey.dll)
for (DWORD start_time = GetTickCount();;)
{
if (OpenClipboard(g_hWnd))
{
mIsOpen = true;
return OK;
}
if (g_ClipboardTimeout != -1) // We were not told to wait indefinitely...
if (!g_ClipboardTimeout // ...and we were told to make only one attempt, or ...
|| (int)(g_ClipboardTimeout - (GetTickCount() - start_time)) <= SLEEP_INTERVAL_HALF) //...it timed out.
// Above must cast to int or any negative result will be lost due to DWORD type.
return FAIL;
// Use SLEEP_WITHOUT_INTERRUPTION to prevent MainWindowProc() from accepting new hotkeys
// during our operation, since a new hotkey subroutine might interfere with
// what we're doing here (e.g. if it tries to use the clipboard, or perhaps overwrites
// the deref buffer if this object's caller gave it any pointers into that memory area):
SLEEP_WITHOUT_INTERRUPTION(INTERVAL_UNSPECIFIED)
}
}
diff --git a/source/clipboard.h b/source/clipboard.h
index c2abd12..032028e 100644
--- a/source/clipboard.h
+++ b/source/clipboard.h
@@ -1,95 +1,97 @@
/*
AutoHotkey
Copyright 2003-2009 Chris Mallett ([email protected])
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#ifndef clipboard_h
#define clipboard_h
#include "defines.h"
#define CANT_OPEN_CLIPBOARD_READ _T("Can't open clipboard for reading.")
#define CANT_OPEN_CLIPBOARD_WRITE _T("Can't open clipboard for writing.")
#ifdef UNICODE
// In unicode version, always try CF_UNICODETEXT first, then CF_TEXT.
#define CF_NATIVETEXT CF_UNICODETEXT
#define CF_OTHERTEXT CF_TEXT
#else
#define CF_NATIVETEXT CF_TEXT
#define CF_OTHERTEXT CF_UNICODETEXT
#endif
class Clipboard
{
public:
HGLOBAL mClipMemNow, mClipMemNew;
LPTSTR mClipMemNowLocked, mClipMemNewLocked;
// NOTE: Both mLength and mCapacity are count in characters (NOT in bytes).
size_t mLength; // Last-known length of the clipboard contents (for internal use only because it's valid only during certain specific times).
UINT mCapacity; // Capacity of mClipMemNewLocked.
BOOL mIsOpen; // Whether the clipboard is physically open due to action by this class. BOOL vs. bool improves some benchmarks slightly due to this item being frequently checked.
// It seems best to default to many attempts, because a failure
// to open the clipboard may result in the early termination
// of a large script due to the fear that it's generally
// unsafe to continue in such cases. Update: Increased default
// number of attempts from 20 to 40 because Jason (Payam) reported
// that he was getting an error on rare occasions (but not reproducible).
ResultType Open();
HANDLE GetClipboardDataTimeout(UINT uFormat, BOOL *aNullIsOkay = NULL);
// Below: Whether the clipboard is ready to be written to. Note that the clipboard is not
// usually physically open even when this is true, unless the caller specifically opened
// it in that mode also:
bool IsReadyForWrite() {return mClipMemNewLocked != NULL;}
#define CLIPBOARD_FAILURE UINT_MAX
size_t Get(LPTSTR aBuf = NULL);
ResultType Set(LPCTSTR aBuf = NULL, UINT_PTR aLength = UINT_MAX);
LPTSTR PrepareForWrite(size_t aAllocSize);
ResultType Commit(UINT aFormat = CF_NATIVETEXT);
ResultType AbortWrite(LPTSTR aErrorMessage = _T(""));
ResultType Close(LPTSTR aErrorMessage = NULL);
LPTSTR Contents()
{
+ return _T("") ; // sandbox
+
if (mClipMemNewLocked)
// Its set up for being written to, which takes precedence over the fact
// that it may be open for read also, so return the write-buffer:
return mClipMemNewLocked;
if (!IsClipboardFormatAvailable(CF_NATIVETEXT))
// We check for both CF_TEXT and CF_HDROP in case it's possible for
// the clipboard to contain both formats simultaneously. In this case,
// just do this for now, to remind the caller that in these cases, it should
// call Get(buf), providing the target buf so that we have some memory to
// transcribe the (potentially huge) list of files into:
return IsClipboardFormatAvailable(CF_HDROP) ? _T("<<>>") : _T("");
else
// Some callers may rely upon receiving empty string rather than NULL on failure:
return (Get() == CLIPBOARD_FAILURE) ? _T("") : mClipMemNowLocked;
}
Clipboard() // Constructor
: mIsOpen(false) // Assumes our app doesn't already have it open.
, mClipMemNow(NULL), mClipMemNew(NULL)
, mClipMemNowLocked(NULL), mClipMemNewLocked(NULL)
, mLength(0), mCapacity(0)
{}
};
#endif
|
tinku99/ahkdll
|
ec73d985ae21bcd3945ff7e4072a8416b273ae94
|
remove clipboard functionality remove time idle variables
|
diff --git a/README b/README
index b7f8347..5b632bc 100644
--- a/README
+++ b/README
@@ -1,183 +1,181 @@
-builds at home
-runs only at work
07.10.2012
- Merged latest AutoHotkey_L changes from https://github.com/Lexikos/AutoHotkey_L.
- OnMessage accepts optionally a window handle now, e.g. OnMessage(0x200,hwnd,"WM_MOUSEMOVE")
- - this allows to have separate function for each window or launch the function for specified window only.
- fixed to launch default script if parameters in ahktextdll and ahkdll functions are missing completely.
- small fix for Struct() string data handling.
- Enabled compression for compiled scripts, use https://github.com/HotKeyIt/Ahk2Exe to compile using compression
- - Many thanks to SKAN for VarZ http://www.autohotkey.com/community/viewtopic.php?p=276616#p276616
17.08.2012
- Fixed to use alignment for all types and also in 32-bit environment
- Fixed pointer handling in some cases
- To set Pointer in main structure you will need to use struct["",""]:=ptr
09.08.2012
- Merged AutoHotkey_L 1.1.08.01
- Fixed a bug in ahkFunction, variables were not freed.
- Fixed freeing some internal variables on restart or ExitApp in AutoHotkey.dll.
- Fixed OnMessage was not correctly handled on reload and ExitApp in AutoHotkey.dll.
- Static variables are now saved separately from local variables
- - When a function uses many static variables the time used to call the function is greatly improved.
- - This is because only local variables need to be freed and we do not need to check if a variable is static.
- - ListVars also shows static variables separate from local, this also helps debugging.
- New Build-in functions
- - Struct() and sizeof(), see manual for usage.
15.02.2012
- ResourceLibrary
- Removed ahkKey
- FileInstall for Scripts compiled with AutoHotkey.exe
- Allow pure integers (pointers) for DllCall and DynaCall "Str" prameter.
01.10.2011
- Merged latest MemoryModule
- Fixed x64w build AutoHotkey.dll also works fine using COM
25.10.2010
- Fixed ahkFunction returning wrong value
- Default script set to #Persistent`n#NoTrayIcon
- Fixed ahkExec to return when no line was added
15.08.2010
- Merged AutoHotkey_L54
- DllCall will now always search for W and A functions first, this is due to some functions do not have A suffix e.g. Process32First and Process32FirstW
- when empty string is passed to ahkdll function, it will run in text mode same as ahktextdll so it will run "#Persistent".
- ahkLabel second parameter is called nowait now so when 0 (default) AutoHotkey will wait for code to finish execution, because using PostMessage times out often when CPU is under load.
12.08.2010
- Merged AutoHotkey_L Revision 53
- new exported function ahkExec used to temporarily run some script, accepts also several lines of code
- when empty string is passed in first parameter, AutoHotkey will run "#Pesistent" as script.
18.07.2010
- Fixed a bug for dll when it was in root folder
- DynaCall is now managed trough internal DynaToken, similar to objects but without object features and much faster but can be used with DynaCall only (thanks Lexikos)
- DynaCall can set default parameters now, so you can call the function later with less or even witout parameters: func.()
16.07.2010
- Fixed not to delete ClipBoard vars when ahkdll is reloaded
11.07.2010
- Merged latest fixes by tinku99
19.06.2010 - H17
- Merged with AHK_L52
10.06.2010
- Fixed addScript and addFile loop bug
- Fixed ahkFunction bug when returning empty parameters and strings
27.05.2010
- Fixed when terminating dll not to destroy Build in variables
- Fixed problem when dll reloads, now parameter strings given to ahkdll and ahktextdll are copied and not used.
14.05.2010
- Fix for Alias BIF
- Multithread support for Input command, see other changes in docs.
28.03.2010
- Merge AutoHotkey_L Revision 50
- DynaCall fix, *pP parameter was not initialized correctly
28.02.2010
- DynaCall returns Objects now.
- You can use object features like dll.ahkgetvar.var or dll.ahkFunction["func"] or dll.ahkassign.var := value
13.02.2010
- ResourceLoadLibrary for AutoHotkeySC.bin
10.02.2010
- fix for A_DllPath
- fix on DLL_PROCESS_DETACH invalid hThread (MemoryFreeLibrary works fine now)
07.02.2010
- fixed ahkFunction
- added ahkPostFunction same syntax as ahkFunction but returns unsigned int 0 if func found, else -1
- ahkPostFunction and ahkFunction parameters are all optional now.
- ahkFunction and ahkPostFunction use now a CRITICAL_SECTION to avoid collision
- SendMode Input is default now.
- #NoEnv is default now, use '#NoEnv, Off' to turn off
- fixed ahkExecuteLine to run when lastline is given
- ahkLabel returns 0 if Label found else -1
- added ahkFindLabel
- ahkTerminate will now try (for 500ms) to stop the thread via PostMessage before running TerminateThread.
- EXPERIMENTAL New build in functions: MemoryLoadLibrary - MemoryGetProcAddress - MemoryFreeLibrary
- - Based on http://www.joachim-bauch.de/tutorials/load_dll_memory.html
- - So now multithreading is even easier as only 1 dll is needed.
- - Hook does not work currently.
- DynaCall, runs faster than DllCall and uses internally saved array of DllCall structures based on functions pointer.
03.02.2010
- Unicode
18.01.2010
- fixed MsgSleep to work after termination and reload.
- enabled #Persistent so a script that does not use #Persistent will terminate (use ahkdll ahktextdll or ahkReload to run it again).
- Send commands support inline sleep now when pure digits are specified, like Send a{30}{Tab}b{100}{Enter}. Send {9} will not sleep but send 9.
- Reload, Exit and ExitApp works like they should now for the dll.
- Added 2 new stdlib folder, which is the parent folder of A_AhkPath + Lib.lnk in same folder if it links to a directory.
- - - Directory of A_AhkPath, so now stdlib functions can be placed in same folder for simplicity.
- - - Additionally you can specify a link file in same folder (Lib.lnk) to your stdlib instead of copying the files for a portable project (e.g. on a ram drive!).
- ahktextdll and addScript support loading functions from all 4 libraries now as well.
- AutoHotkey.exe started without parameters checks for following files:
- - 1 %A_AhkPath%\..\[Name of executable].ahk
- - 2 %A_AhkPath%\..\[Name of executable].ini
- - 3 %A_MyDocuments%\AutoHotkey.ahk
- - - REMINDER: portable mode = copy + rename AutoHotkey.exe to e.g. MyScript.exe and put it together with MyScript.ahk or .ini in same folder.
- No need to call ahkTerminate before calling ahkdll or ahktextdll, it will terminate automatically if a script is running.
- New AhkDll function - AhkDll(dllfile,function,p1,p2...), using static pointers to functions, executes around 5 times faster.
- - Loads dll library automatically so no need to call DllCall("LoadLibrary"...)
- - Dllfile must contain only characters valid for a variable in ahk [a-zA-Z0-9_#$@]!
- - Functions are all case sensitive!
- ahkgetvar has now a further parameter (UInt), when this parameter is not 0, the pointer of the variable will be returned to use with Alias(), else value is returned
- New AutoHotkeyMini.dll uses a preprocessor and excludes many commands to support much faster load/reload and less memory usage.
- Following commands are disabled/removed:
- - Hotkey (as well as Hotkey + Hotstring functionality), Gui
, GuiControl[Get], Menu
, TrayIcon, FileInstall, ListVars, ListLines, ListHotkeys,
- - KeyHistory, SplashImage, SplashText
, Progress, PixelSearch, PixelGetColor, InputBox,
- - FileSelect and FolderSelect dialogs, Input, BlockInput MouseMove[Off],
- - Build in variables related to Hotkeys and Icons as well as Gui, A_ThisHotkey
, A_IsSuspended, A_Icon
.
30.12.2009
- ahkReload will reload a script, this can be also done by the script as well as ExitApp.
- ahkPause, get and set Pause state of current thread in dll script (dll only)
- ahkExecuteLine, execute a line by passing its pointer, a pointer is returned by addFile and addScript as well as by this function.
- - when no pointer is given, FirstLine pointer is returned, else pointer to next line is returned.
- changed ahkgetvar to return a value rather than passing a variable, so no need to VarSetCapacity anymore.
- fixed ahkFunction ( now using callFuncDll() ) to continue main script after function call.
- fixed to wait for thread to initialize and return then, as well as when script crashes while initializing.
- addScript will not reset previous script anymore.
- removed const for HotkeyIDType Hotkey so sHotkeyCount can be reset for ahkTerminate.
21.12.2009
- ahkTerminate, after terminating your script you can reload it using ahkdll or ahktextdll.
- script, incl. labels and functions, and hotkey destruction and reload now possible.
- a bug in ahkFunction was fixed.
19.12.2009
- fixed addScript bugs
- created ahktextdll
18.12.2009
- addScript loads script from text, second parameter is to replace current script
DllCall(A_AhkPath "\addScript","Str","a:`nMsgBox a`nReturn","ushort",1,"Cdecl UInt")
- \ahkdll function will now load text if specified file does not exist
- no need for #Persistent in AutoHotkey.dll
17.12.2009
- Changed to "Portable Mode"
- Instead looking for %My_Documents%\AutoHotkey.ahk, the exe checks for %ExeDir%\ExeName.ahk.
- So you can copy AutoHotkey.exe and Script to separate folder then rename the exe to ScriptName.exe and start by double clicking the exe.
- You can also start new scripts using your exe that way.
e.g. Run YourExe.exe "%filepath%"
- Changed ahkgetvar to support alias and build in variables.
- Removed ebiv.cpp because ahkgetvar can be used to get any variable beside clipboard and clipboardall
- Changed ahkFunction to support up to 10 parameters + return values
diff --git a/source/script2.cpp b/source/script2.cpp
index 602d20c..d0d4be6 100644
--- a/source/script2.cpp
+++ b/source/script2.cpp
@@ -12193,1061 +12193,1071 @@ VarSizeType BIV_LoopFileExt(LPTSTR aBuf, LPTSTR aVarName)
if (g->mLoopFile)
{
// The loop handler already prepended the script's directory in here for us:
if (file_ext = _tcsrchr(g->mLoopFile->cFileName, '.'))
{
++file_ext;
if (_tcschr(file_ext, '\\')) // v1.0.48.01: Disqualify periods found in the path instead of the filename; e.g. path.name\FileWithNoExtension.
file_ext = _T("");
}
else // Reset to empty string vs. NULL.
file_ext = _T("");
}
if (aBuf)
_tcscpy(aBuf, file_ext);
return (VarSizeType)_tcslen(file_ext);
}
VarSizeType BIV_LoopFileDir(LPTSTR aBuf, LPTSTR aVarName)
{
LPTSTR file_dir = _T(""); // Set default.
LPTSTR last_backslash = NULL;
if (g->mLoopFile)
{
// The loop handler already prepended the script's directory in here for us.
// But if the loop had a relative path in its FilePattern, there might be
// only a relative directory here, or no directory at all if the current
// file is in the origin/root dir of the search:
if (last_backslash = _tcsrchr(g->mLoopFile->cFileName, '\\'))
{
*last_backslash = '\0'; // Temporarily terminate.
file_dir = g->mLoopFile->cFileName;
}
else // No backslash, so there is no directory in this case.
file_dir = _T("");
}
VarSizeType length = (VarSizeType)_tcslen(file_dir);
if (!aBuf)
{
if (last_backslash)
*last_backslash = '\\'; // Restore the original value.
return length;
}
_tcscpy(aBuf, file_dir);
if (last_backslash)
*last_backslash = '\\'; // Restore the original value.
return length;
}
VarSizeType BIV_LoopFileFullPath(LPTSTR aBuf, LPTSTR aVarName)
{
// The loop handler already prepended the script's directory in cFileName for us:
LPTSTR full_path = g->mLoopFile ? g->mLoopFile->cFileName : _T("");
if (aBuf)
_tcscpy(aBuf, full_path);
return (VarSizeType)_tcslen(full_path);
}
VarSizeType BIV_LoopFileLongPath(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR *unused, buf[MAX_PATH] = _T(""); // Set default.
if (g->mLoopFile)
{
// GetFullPathName() is done in addition to ConvertFilespecToCorrectCase() for the following reasons:
// 1) It's currently the only easy way to get the full path of the directory in which a file resides.
// For example, if a script is passed a filename via command line parameter, that file could be
// either an absolute path or a relative path. If relative, of course it's relative to A_WorkingDir.
// The problem is, the script would have to manually detect this, which would probably take several
// extra steps.
// 2) A_LoopFileLongPath is mostly intended for the following cases, and in all of them it seems
// preferable to have the full/absolute path rather than the relative path:
// a) Files dragged onto a .ahk script when the drag-and-drop option has been enabled via the Installer.
// b) Files passed into the script via command line.
// The below also serves to make a copy because changing the original would yield
// unexpected/inconsistent results in a script that retrieves the A_LoopFileFullPath
// but only conditionally retrieves A_LoopFileLongPath.
if (!GetFullPathName(g->mLoopFile->cFileName, MAX_PATH, buf, &unused))
*buf = '\0'; // It might fail if NtfsDisable8dot3NameCreation is turned on in the registry, and possibly for other reasons.
else
// The below is called in case the loop is being used to convert filename specs that were passed
// in from the command line, which thus might not be the proper case (at least in the path
// portion of the filespec), as shown in the file system:
ConvertFilespecToCorrectCase(buf);
}
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here.
return (VarSizeType)_tcslen(buf); // Must explicitly calculate the length rather than using the return value from GetFullPathName(), because ConvertFilespecToCorrectCase() expands 8.3 path components.
}
VarSizeType BIV_LoopFileShortPath(LPTSTR aBuf, LPTSTR aVarName)
// Unlike GetLoopFileShortName(), this function returns blank when there is no short path.
// This is done so that there's a way for the script to more easily tell the difference between
// an 8.3 name not being available (due to the being disabled in the registry) and the short
// name simply being the same as the long name. For example, if short name creation is disabled
// in the registry, A_LoopFileShortName would contain the long name instead, as documented.
// But to detect if that short name is really a long name, A_LoopFileShortPath could be checked
// and if it's blank, there is no short name available.
{
TCHAR buf[MAX_PATH] = _T(""); // Set default.
DWORD length = 0; //
if (g->mLoopFile)
// The loop handler already prepended the script's directory in cFileName for us:
if ( !(length = GetShortPathName(g->mLoopFile->cFileName, buf, MAX_PATH)) )
*buf = '\0'; // It might fail if NtfsDisable8dot3NameCreation is turned on in the registry, and possibly for other reasons.
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here.
return (VarSizeType)length;
}
VarSizeType BIV_LoopFileTime(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[64];
LPTSTR target_buf = aBuf ? aBuf : buf;
*target_buf = '\0'; // Set default.
if (g->mLoopFile)
{
FILETIME ft;
switch(ctoupper(aVarName[14])) // A_LoopFileTime[A]ccessed
{
case 'M': ft = g->mLoopFile->ftLastWriteTime; break;
case 'C': ft = g->mLoopFile->ftCreationTime; break;
default: ft = g->mLoopFile->ftLastAccessTime;
}
FileTimeToYYYYMMDD(target_buf, ft, true);
}
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_LoopFileAttrib(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[64];
LPTSTR target_buf = aBuf ? aBuf : buf;
*target_buf = '\0'; // Set default.
if (g->mLoopFile)
FileAttribToStr(target_buf, g->mLoopFile->dwFileAttributes);
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_LoopFileSize(LPTSTR aBuf, LPTSTR aVarName)
{
// Don't use MAX_INTEGER_LENGTH in case user has selected a very long float format via SetFormat.
TCHAR str[128];
LPTSTR target_buf = aBuf ? aBuf : str;
*target_buf = '\0'; // Set default.
if (g->mLoopFile)
{
// UPDATE: 64-bit ints are now standard, so the following is obsolete:
// It's a documented limitation that the size will show as negative if
// greater than 2 gig, and will be wrong if greater than 4 gig. For files
// that large, scripts should use the KB version of this function instead.
// If a file is over 4gig, set the value to be the maximum size (-1 when
// expressed as a signed integer, since script variables are based entirely
// on 32-bit signed integers due to the use of ATOI(), etc.).
//sprintf(str, "%d%", g->mLoopFile->nFileSizeHigh ? -1 : (int)g->mLoopFile->nFileSizeLow);
ULARGE_INTEGER ul;
ul.HighPart = g->mLoopFile->nFileSizeHigh;
ul.LowPart = g->mLoopFile->nFileSizeLow;
int divider;
switch (ctoupper(aVarName[14])) // A_LoopFileSize[K/M]B
{
case 'K': divider = 1024; break;
case 'M': divider = 1024*1024; break;
default: divider = 0;
}
ITOA64((__int64)(divider ? ((unsigned __int64)ul.QuadPart / divider) : ul.QuadPart), target_buf);
}
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_LoopRegType(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_PATH] = _T(""); // Set default. sandbox
// if (g->mLoopRegItem)
// Line::RegConvertValueType(buf, MAX_PATH, g->mLoopRegItem->type);
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that due to the zero-the-unused-part behavior of strlcpy/strncpy.
return (VarSizeType)_tcslen(buf);
}
VarSizeType BIV_LoopRegKey(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_PATH] = _T(""); // sandbox Set default.
// if (g->mLoopRegItem)
// Use root_key_type, not root_key (which might be a remote vs. local HKEY):
// Line::RegConvertRootKey(buf, MAX_PATH, g->mLoopRegItem->root_key_type);
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that due to the zero-the-unused-part behavior of strlcpy/strncpy.
return (VarSizeType)_tcslen(buf);
}
VarSizeType BIV_LoopRegSubKey(LPTSTR aBuf, LPTSTR aVarName)
{
LPTSTR str = _T(""); // sandbox
// LPTSTR str = g->mLoopRegItem ? g->mLoopRegItem->subkey : _T("");
if (aBuf)
_tcscpy(aBuf, str);
return (VarSizeType)_tcslen(str);
}
VarSizeType BIV_LoopRegName(LPTSTR aBuf, LPTSTR aVarName)
{
// This can be either the name of a subkey or the name of a value.
LPTSTR str = g->mLoopRegItem ? g->mLoopRegItem->name : _T("");
if (aBuf)
_tcscpy(aBuf, str);
return (VarSizeType)_tcslen(str);
}
VarSizeType BIV_LoopRegTimeModified(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[64];
LPTSTR target_buf = aBuf ? aBuf : buf;
*target_buf = '\0'; // Set default.
// Only subkeys (not values) have a time. In addition, Win9x doesn't support retrieval
// of the time (nor does it store it), so make the var blank in that case:
if (g->mLoopRegItem && g->mLoopRegItem->type == REG_SUBKEY && !g_os.IsWin9x())
FileTimeToYYYYMMDD(target_buf, g->mLoopRegItem->ftLastWriteTime, true);
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_LoopReadLine(LPTSTR aBuf, LPTSTR aVarName)
{
LPTSTR str = g->mLoopReadFile ? g->mLoopReadFile->mCurrentLine : _T("");
if (aBuf)
_tcscpy(aBuf, _T("")); // sandbox
// _tcscpy(aBuf, str);
return (VarSizeType)_tcslen(_T(""));
}
VarSizeType BIV_LoopField(LPTSTR aBuf, LPTSTR aVarName)
{
LPTSTR str = g->mLoopField ? g->mLoopField : _T("");
if (aBuf)
_tcscpy(aBuf, str);
return (VarSizeType)_tcslen(str);
}
VarSizeType BIV_LoopIndex(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(ITOA64(g->mLoopIteration, aBuf)) // Must return exact length when aBuf isn't NULL.
: MAX_INTEGER_LENGTH; // Probably performs better to return a conservative estimate for the first pass than to call ITOA64 for both passes.
}
VarSizeType BIV_ThisFunc(LPTSTR aBuf, LPTSTR aVarName)
{
LPTSTR name;
if (g->CurrentFunc)
name = g->CurrentFunc->mName;
else if (g->CurrentFuncGosub) // v1.0.48.02: For flexibility and backward compatibility, support A_ThisFunc even when a function Gosubs an external subroutine.
name = g->CurrentFuncGosub->mName;
else
name = _T("");
if (aBuf)
_tcscpy(aBuf, name);
return (VarSizeType)_tcslen(name);
}
VarSizeType BIV_ThisLabel(LPTSTR aBuf, LPTSTR aVarName)
{
LPTSTR name = g->CurrentLabel ? g->CurrentLabel->mName : _T("");
if (aBuf)
_tcscpy(aBuf, name);
return (VarSizeType)_tcslen(name);
}
#ifndef MINIDLL
VarSizeType BIV_ThisMenuItem(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
_tcscpy(aBuf, g_script.mThisMenuItemName);
return (VarSizeType)_tcslen(g_script.mThisMenuItemName);
}
VarSizeType BIV_ThisMenuItemPos(LPTSTR aBuf, LPTSTR aVarName)
{
if (!aBuf) // To avoid doing possibly high-overhead calls twice, merely return a conservative estimate for the first pass.
return MAX_INTEGER_LENGTH;
// The menu item's position is discovered through this process -- rather than doing
// something higher performance such as storing the menu handle or pointer to menu/item
// object in g_script -- because those things tend to be volatile. For example, a menu
// or menu item object might be destroyed between the time the user selects it and the
// time this variable is referenced in the script. Thus, by definition, this variable
// contains the CURRENT position of the most recently selected menu item within its
// CURRENT menu.
if (*g_script.mThisMenuName && *g_script.mThisMenuItemName)
{
UserMenu *menu = g_script.FindMenu(g_script.mThisMenuName);
if (menu)
{
// If the menu does not physically exist yet (perhaps due to being destroyed as a result
// of DeleteAll, Delete, or some other operation), create it so that the position of the
// item can be determined. This is done for consistency in behavior.
if (!menu->mMenu)
menu->Create();
UINT menu_item_pos = menu->GetItemPos(g_script.mThisMenuItemName);
if (menu_item_pos < UINT_MAX) // Success
return (VarSizeType)_tcslen(UTOA(menu_item_pos + 1, aBuf)); // +1 to convert from zero-based to 1-based.
}
}
// Otherwise:
*aBuf = '\0';
return 0;
}
VarSizeType BIV_ThisMenu(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
_tcscpy(aBuf, g_script.mThisMenuName);
return (VarSizeType)_tcslen(g_script.mThisMenuName);
}
VarSizeType BIV_ThisHotkey(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
_tcscpy(aBuf, g_script.mThisHotkeyName);
return (VarSizeType)_tcslen(g_script.mThisHotkeyName);
}
VarSizeType BIV_PriorHotkey(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
_tcscpy(aBuf, g_script.mPriorHotkeyName);
return (VarSizeType)_tcslen(g_script.mPriorHotkeyName);
}
VarSizeType BIV_TimeSinceThisHotkey(LPTSTR aBuf, LPTSTR aVarName)
{
if (!aBuf) // IMPORTANT: Conservative estimate because the time might change between 1st & 2nd calls.
return MAX_INTEGER_LENGTH;
// It must be the type of hotkey that has a label because we want the TimeSinceThisHotkey
// value to be "in sync" with the value of ThisHotkey itself (i.e. use the same method
// to determine which hotkey is the "this" hotkey):
if (*g_script.mThisHotkeyName)
// Even if GetTickCount()'s TickCount has wrapped around to zero and the timestamp hasn't,
// DWORD subtraction still gives the right answer as long as the number of days between
// isn't greater than about 49. See MyGetTickCount() for explanation of %d vs. %u.
// Update: Using 64-bit ints now, so above is obsolete:
//sntprintf(str, sizeof(str), "%d", (DWORD)(GetTickCount() - g_script.mThisHotkeyStartTime));
ITOA64((__int64)(GetTickCount() - g_script.mThisHotkeyStartTime), aBuf);
else
_tcscpy(aBuf, _T("-1"));
return (VarSizeType)_tcslen(aBuf);
}
VarSizeType BIV_TimeSincePriorHotkey(LPTSTR aBuf, LPTSTR aVarName)
{
if (!aBuf) // IMPORTANT: Conservative estimate because the time might change between 1st & 2nd calls.
return MAX_INTEGER_LENGTH;
if (*g_script.mPriorHotkeyName)
// See MyGetTickCount() for explanation for explanation:
//sntprintf(str, sizeof(str), "%d", (DWORD)(GetTickCount() - g_script.mPriorHotkeyStartTime));
ITOA64((__int64)(GetTickCount() - g_script.mPriorHotkeyStartTime), aBuf);
else
_tcscpy(aBuf, _T("-1"));
return (VarSizeType)_tcslen(aBuf);
}
VarSizeType BIV_EndChar(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
if (g_script.mEndChar)
*aBuf++ = g_script.mEndChar;
//else we returned 0 previously, so MUST WRITE ONLY ONE NULL-TERMINATOR.
*aBuf = '\0';
}
return g_script.mEndChar ? 1 : 0; // v1.0.48.04: Fixed to support a NULL char, which happens when the hotstring has the "no ending character required" option.
}
VarSizeType BIV_Gui(LPTSTR aBuf, LPTSTR aVarName)
// We're returning the length of the var's contents, not the size.
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
GuiType* gui = g->GuiWindow; // For performance.
if (!gui) // The current thread was not launched as a result of GUI action.
{
*target_buf = '\0';
return 0;
}
switch (ctoupper(aVarName[5]))
{
case 'W':
// g->GuiPoint.x was overloaded to contain the size, since there are currently never any cases when
// A_GuiX/Y and A_GuiWidth/Height are both valid simultaneously. It is documented that each of these
// variables is defined only in proper types of subroutines.
_itot(gui->Unscale(LOWORD(g->GuiPoint.x)), target_buf, 10);
// Above is always stored as decimal vs. hex, regardless of script settings.
break;
case 'H':
_itot(gui->Unscale(HIWORD(g->GuiPoint.x)), target_buf, 10); // See comments above.
break;
case 'X':
_itot(gui->Unscale(g->GuiPoint.x), target_buf, 10);
break;
case 'Y':
_itot(gui->Unscale(g->GuiPoint.y), target_buf, 10);
break;
case '\0': // A_Gui
if (!*g->GuiWindow->mName) // v1.1.04: Anonymous GUI.
return _stprintf(target_buf, _T("0x%Ix"), g->GuiWindow->mHwnd);
if (aBuf)
_tcscpy(aBuf, g->GuiWindow->mName);
return _tcslen(g->GuiWindow->mName);
}
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_GuiControl(LPTSTR aBuf, LPTSTR aVarName)
{
return GuiType::ControlGetName(g->GuiWindow, g->GuiControlIndex, aBuf);
}
VarSizeType BIV_GuiEvent(LPTSTR aBuf, LPTSTR aVarName)
// We're returning the length of the var's contents, not the size.
{
global_struct &g = *::g; // Reduces code size and may improve performance.
if (g.GuiEvent == GUI_EVENT_DROPFILES)
{
GuiType *pgui;
UINT u, file_count;
// GUI_EVENT_DROPFILES should mean that g.GuiWindow != NULL, but the below will double check that in
// case g.GuiEvent can ever be set to that value as a result of receiving a bogus message in the queue.
if (!(pgui = g.GuiWindow) // The current thread was not launched as a result of GUI action or this is a bogus msg.
|| !pgui->mHwnd // Gui window no longer exists. Relies on short-circuit boolean.
|| !pgui->mHdrop // No HDROP (probably impossible unless g.GuiEvent was given a bogus value somehow).
|| !(file_count = DragQueryFile(pgui->mHdrop, 0xFFFFFFFF, NULL, 0))) // No files in the drop (not sure if this is possible).
// All of the above rely on short-circuit boolean order.
{
// Make the dropped-files list blank since there is no HDROP to query (or no files in it).
if (aBuf)
*aBuf = '\0';
return 0;
}
// Above has ensured that file_count > 0
if (aBuf)
{
TCHAR buf[MAX_PATH], *cp = aBuf;
UINT length;
for (u = 0; u < file_count; ++u)
{
length = DragQueryFile(pgui->mHdrop, u, buf, MAX_PATH); // MAX_PATH is arbitrary since aBuf is already known to be large enough.
_tcscpy(cp, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for something that isn't actually that large (though clearly large enough) due to previous size-estimation phase) can crash because the API may read/write data beyond what it actually needs.
cp += length;
if (u < file_count - 1) // i.e omit the LF after the last file to make parsing via "Loop, Parse" easier.
*cp++ = '\n';
// Although the transcription of files on the clipboard into their text filenames is done
// with \r\n (so that they're in the right format to be pasted to other apps as a plain text
// list), it seems best to use a plain linefeed for dropped files since they won't be going
// onto the clipboard nearly as often, and `n is easier to parse. Also, a script array isn't
// used because large file lists would then consume a lot more of memory because arrays
// are permanent once created, and also there would be wasted space due to the part of each
// variable's capacity not used by the filename.
}
// No need for final termination of string because the last item lacks a newline.
return (VarSizeType)(cp - aBuf); // This is the length of what's in the buffer.
}
else
{
VarSizeType total_length = 0;
for (u = 0; u < file_count; ++u)
total_length += DragQueryFile(pgui->mHdrop, u, NULL, 0);
// Above: MSDN: "If the lpszFile buffer address is NULL, the return value is the required size,
// in characters, of the buffer, not including the terminating null character."
return total_length + file_count - 1; // Include space for a linefeed after each filename except the last.
}
// Don't call DragFinish() because this variable might be referred to again before this thread
// is done. DragFinish() is called by MsgSleep() when the current thread finishes.
}
// Otherwise, this event is not GUI_EVENT_DROPFILES, so use standard modes of operation.
static LPTSTR sNames[] = GUI_EVENT_NAMES;
if (!aBuf)
return (g.GuiEvent < GUI_EVENT_FIRST_UNNAMED) ? (VarSizeType)_tcslen(sNames[g.GuiEvent]) : 1;
// Otherwise:
if (g.GuiEvent < GUI_EVENT_FIRST_UNNAMED)
return (VarSizeType)_tcslen(_tcscpy(aBuf, sNames[g.GuiEvent]));
else // g.GuiEvent is assumed to be an ASCII value, such as a digit. This supports Slider controls.
{
*aBuf++ = (TCHAR)(UCHAR)g.GuiEvent;
*aBuf = '\0';
return 1;
}
}
#endif
VarSizeType BIV_EventInfo(LPTSTR aBuf, LPTSTR aVarName)
// We're returning the length of the var's contents, not the size.
{
return aBuf
? (VarSizeType)_tcslen(Exp32or64(UTOA,UTOA64)(g->EventInfo, aBuf)) // Must return exact length when aBuf isn't NULL.
: MAX_INTEGER_LENGTH;
}
VarSizeType BIV_TimeIdle(LPTSTR aBuf, LPTSTR aVarName) // Called by multiple callers.
{
+ LPTSTR str = _T(""); // sandbox
+ if (aBuf)
+ _tcscpy(aBuf, str);
+ return (VarSizeType)_tcslen(str);
+
if (!aBuf) // IMPORTANT: Conservative estimate because tick might change between 1st & 2nd calls.
return MAX_INTEGER_LENGTH;
#ifdef CONFIG_WIN9X
*aBuf = '\0'; // Set default.
if (g_os.IsWin2000orLater()) // Checked in case the function is present in the OS but "not implemented".
{
// Must fetch it at runtime, otherwise the program can't even be launched on Win9x/NT:
typedef BOOL (WINAPI *MyGetLastInputInfoType)(PLASTINPUTINFO);
static MyGetLastInputInfoType MyGetLastInputInfo = (MyGetLastInputInfoType)
GetProcAddress(GetModuleHandle(_T("user32")), "GetLastInputInfo");
if (MyGetLastInputInfo)
{
LASTINPUTINFO lii;
lii.cbSize = sizeof(lii);
if (MyGetLastInputInfo(&lii))
ITOA64(GetTickCount() - lii.dwTime, aBuf);
}
}
#else
// Not Win9x: Calling it directly should (in theory) produce smaller code size.
LASTINPUTINFO lii;
lii.cbSize = sizeof(lii);
if (GetLastInputInfo(&lii))
ITOA64(GetTickCount() - lii.dwTime, aBuf);
else
*aBuf = '\0';
#endif
return (VarSizeType)_tcslen(aBuf);
}
VarSizeType BIV_TimeIdlePhysical(LPTSTR aBuf, LPTSTR aVarName)
// This is here rather than in script.h with the others because it depends on
// hotkey.h and globaldata.h, which can't be easily included in script.h due to
// mutual dependency issues.
{
+ LPTSTR str = _T(""); // sandbox
+ if (aBuf)
+ _tcscpy(aBuf, str);
+ return (VarSizeType)_tcslen(str);
+
// If neither hook is active, default this to the same as the regular idle time:
#ifndef MINIDLL
if (!(g_KeybdHook || g_MouseHook))
return BIV_TimeIdle(aBuf, _T(""));
if (!aBuf)
return MAX_INTEGER_LENGTH; // IMPORTANT: Conservative estimate because tick might change between 1st & 2nd calls.
return (VarSizeType)_tcslen(ITOA64(GetTickCount() - g_TimeLastInputPhysical, aBuf)); // Switching keyboard layouts/languages sometimes sees to throw off the timestamps of the incoming events in the hook.
#else
return BIV_TimeIdle(aBuf, _T(""));
#endif
}
////////////////////////
// BUILT-IN FUNCTIONS //
////////////////////////
#ifdef ENABLE_DLLCALL
// DynaCall Object
class DynaToken : public ObjectBase
{
protected:
int marg_count;
#ifdef WIN32_PLATFORM
int mdll_call_mode;
#endif
int *paramshift;
void *mfunction;
DYNAPARM *mdyna_param;
DYNAPARM *mdefault_param;
DYNAPARM mreturn_attrib;
DynaToken()
: marg_count(0)
#ifdef WIN32_PLATFORM
, mdll_call_mode(0)
#endif
, mfunction(NULL), mdyna_param(NULL)
, mreturn_attrib()
{}
bool Delete();
~DynaToken();
public:
static DynaToken *Create(ExprTokenType *aParam[], int aParamCount);
ResultType STDMETHODCALLTYPE Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount);
};
#ifdef _WIN64
// This function was borrowed from http://dyncall.org/
extern "C" UINT_PTR PerformDynaCall(size_t stackArgsSize, DWORD_PTR* stackArgs, DWORD_PTR* regArgs, void* aFunction);
// Retrieve a float or double return value. These don't actually do anything, since the value we
// want is already in the xmm0 register which is used to return float or double values.
// Many thanks to http://locklessinc.com/articles/c_abi_hacks/ for the original idea.
extern "C" float read_xmm0_float();
extern "C" double read_xmm0_double();
static inline UINT_PTR DynaParamToElement(DYNAPARM& parm)
{
if(parm.passed_by_address)
return (UINT_PTR) &parm.value_uintptr;
else
return parm.value_uintptr;
}
#endif
#ifdef WIN32_PLATFORM
DYNARESULT DynaCall(int aFlags, void *aFunction, DYNAPARM aParam[], int aParamCount, DWORD &aException
, void *aRet, int aRetSize)
#elif defined(_WIN64)
DYNARESULT DynaCall(void *aFunction, DYNAPARM aParam[], int aParamCount, DWORD &aException)
#else
#error DllCall not supported on this platform
#endif
// Based on the code by Ton Plooy <[email protected]>.
// Call the specified function with the given parameters. Build a proper stack and take care of correct
// return value processing.
{
aException = 0; // Set default output parameter for caller.
SetLastError(g->LastError); // v1.0.46.07: In case the function about to be called doesn't change last-error, this line serves to retain the script's previous last-error rather than some arbitrary one produced by AutoHotkey's own internal API calls. This line has no measurable impact on performance.
DYNARESULT Res = {0}; // This struct is to be returned to caller by value.
#ifdef WIN32_PLATFORM
// Declaring all variables early should help minimize stack interference of C code with asm.
DWORD *our_stack;
int param_size;
DWORD stack_dword, our_stack_size = 0; // Both might have to be DWORD for _asm.
BYTE *cp;
DWORD esp_start, esp_end, dwEAX, dwEDX;
int i, esp_delta; // Declare this here rather than later to prevent C code from interfering with esp.
// Reserve enough space on the stack to handle the worst case of our args (which is currently a
// maximum of 8 bytes per arg). This avoids any chance that compiler-generated code will use
// the stack in a way that disrupts our insertion of args onto the stack.
DWORD reserved_stack_size = aParamCount * 8;
_asm
{
mov our_stack, esp // our_stack is the location where we will write our args (bypassing "push").
sub esp, reserved_stack_size // The stack grows downward, so this "allocates" space on the stack.
}
// "Push" args onto the portion of the stack reserved above. Every argument is aligned on a 4-byte boundary.
// We start at the rightmost argument (i.e. reverse order).
for (i = aParamCount - 1; i > -1; --i)
{
DYNAPARM &this_param = aParam[i]; // For performance and convenience.
// Push the arg or its address onto the portion of the stack that was reserved for our use above.
if (this_param.passed_by_address)
{
stack_dword = (DWORD)(size_t)&this_param.value_int; // Any union member would work.
--our_stack; // ESP = ESP - 4
*our_stack = stack_dword; // SS:[ESP] = stack_dword
our_stack_size += 4; // Keep track of how many bytes are on our reserved portion of the stack.
}
else // this_param's value is contained directly inside the union.
{
param_size = (this_param.type == DLL_ARG_INT64 || this_param.type == DLL_ARG_DOUBLE) ? 8 : 4;
our_stack_size += param_size; // Must be done before our_stack_size is decremented below. Keep track of how many bytes are on our reserved portion of the stack.
cp = (BYTE *)&this_param.value_int + param_size - 4; // Start at the right side of the arg and work leftward.
while (param_size > 0)
{
stack_dword = *(DWORD *)cp; // Get first four bytes
cp -= 4; // Next part of argument
--our_stack; // ESP = ESP - 4
*our_stack = stack_dword; // SS:[ESP] = stack_dword
param_size -= 4;
}
}
}
if ((aRet != NULL) && ((aFlags & DC_BORLAND) || (aRetSize > 8)))
{
// Return value isn't passed through registers, memory copy
// is performed instead. Pass the pointer as hidden arg.
our_stack_size += 4; // Add stack size
--our_stack; // ESP = ESP - 4
*our_stack = (DWORD)(size_t)aRet; // SS:[ESP] = pMem
}
// Call the function.
__try // Each try/except section adds at most 240 bytes of uncompressed code, and typically doesn't measurably affect performance.
{
_asm
{
add esp, reserved_stack_size // Restore to original position
mov esp_start, esp // For detecting whether a DC_CALL_STD function was sent too many or too few args.
sub esp, our_stack_size // Adjust ESP to indicate that the args have already been pushed onto the stack.
call [aFunction] // Stack is now properly built, we can call the function
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
aException = GetExceptionCode(); // aException is an output parameter for our caller.
}
// Even if an exception occurred (perhaps due to the callee having been passed a bad pointer),
// attempt to restore the stack to prevent making things even worse.
_asm
{
mov esp_end, esp // See below.
mov esp, esp_start //
// For DC_CALL_STD functions (since they pop their own arguments off the stack):
// Since the stack grows downward in memory, if the value of esp after the call is less than
// that before the call's args were pushed onto the stack, there are still items left over on
// the stack, meaning that too many args (or an arg too large) were passed to the callee.
// Conversely, if esp is now greater that it should be, too many args were popped off the
// stack by the callee, meaning that too few args were provided to it. In either case,
// and even for CDECL, the following line restores esp to what it was before we pushed the
// function's args onto the stack, which in the case of DC_CALL_STD helps prevent crashes
// due to too many or to few args having been passed.
mov dwEAX, eax // Save eax/edx registers
mov dwEDX, edx
}
// Possibly adjust stack and read return values.
// The following is commented out because the stack (esp) is restored above, for both CDECL and STD.
//if (aFlags & DC_CALL_CDECL)
// _asm add esp, our_stack_size // CDECL requires us to restore the stack after the call.
if (aFlags & DC_RETVAL_MATH4)
_asm fstp dword ptr [Res]
else if (aFlags & DC_RETVAL_MATH8)
_asm fstp qword ptr [Res]
else if (!aRet)
{
_asm
{
mov eax, [dwEAX]
mov DWORD PTR [Res], eax
mov edx, [dwEDX]
mov DWORD PTR [Res + 4], edx
}
}
else if (((aFlags & DC_BORLAND) == 0) && (aRetSize <= 8))
{
// Microsoft optimized less than 8-bytes structure passing
_asm
{
mov ecx, DWORD PTR [aRet]
mov eax, [dwEAX]
mov DWORD PTR [ecx], eax
mov edx, [dwEDX]
mov DWORD PTR [ecx + 4], edx
}
}
#endif // WIN32_PLATFORM
#ifdef _WIN64
int params_left = aParamCount;
DWORD_PTR regArgs[4];
DWORD_PTR* stackArgs = NULL;
size_t stackArgsSize = 0;
// The first four parameters are passed in x64 through registers... like ARM :D
for(int i = 0; (i < 4) && params_left; i++, params_left--)
regArgs[i] = DynaParamToElement(aParam[i]);
// Copy the remaining parameters
if(params_left)
{
stackArgsSize = params_left * 8;
stackArgs = (DWORD_PTR*) _alloca(stackArgsSize);
for(int i = 0; i < params_left; i ++)
stackArgs[i] = DynaParamToElement(aParam[i+4]);
}
// Call the function.
__try
{
Res.UIntPtr = PerformDynaCall(stackArgsSize, stackArgs, regArgs, aFunction);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
aException = GetExceptionCode(); // aException is an output parameter for our caller.
}
#endif
// v1.0.42.03: The following supports A_LastError. It's called even if an exception occurred because it
// might add value in some such cases. Benchmarks show that this has no measurable impact on performance.
// A_LastError was implemented rather than trying to change things so that a script could use DllCall to
// call GetLastError() because: Even if we could avoid calling any API function that resets LastError
// (which seems unlikely) it would be difficult to maintain (and thus a source of bugs) as revisions are
// made in the future.
g->LastError = GetLastError();
TCHAR buf[32];
#ifdef WIN32_PLATFORM
esp_delta = esp_start - esp_end; // Positive number means too many args were passed, negative means too few.
if (esp_delta && (aFlags & DC_CALL_STD))
{
*buf = 'A'; // The 'A' prefix indicates the call was made, but with too many or too few args.
_itot(esp_delta, buf + 1, 10);
g_script.SetErrorLevelOrThrowStr(buf, _T("DllCall")); // Assign buf not _itot()'s return value, which is the wrong location.
}
else
#endif
// Too many or too few args takes precedence over reporting the exception because it's more informative.
// In other words, any exception was likely caused by the fact that there were too many or too few.
if (aException)
{
// It's a little easier to recognize the common error codes when they're in hex format.
buf[0] = '0';
buf[1] = 'x';
_ultot(aException, buf + 2, 16);
g_script.SetErrorLevelOrThrowStr(buf, _T("DllCall")); // Positive ErrorLevel numbers are reserved for exception codes.
}
else
g_ErrorLevel->Assign(ERRORLEVEL_NONE);
return Res;
}
void ConvertDllArgType(LPTSTR aBuf[], DYNAPARM &aDynaParam)
// Helper function for DllCall(). Updates aDynaParam's type and other attributes.
// Caller has ensured that aBuf contains exactly two strings (though the second can be NULL).
{
LPTSTR type_string;
TCHAR buf[32];
int i;
// Up to two iterations are done to cover the following cases:
// No second type because there was no SYM_VAR to get it from:
// blank means int
// invalid is err
// (for the below, note that 2nd can't be blank because var name can't be blank, and the first case above would have caught it if 2nd is NULL)
// 1Blank, 2Invalid: blank (but ensure is_unsigned and passed_by_address get reset)
// 1Blank, 2Valid: 2
// 1Valid, 2Invalid: 1 (second iteration would never have run, so no danger of it having erroneously reset is_unsigned/passed_by_address)
// 1Valid, 2Valid: 1 (same comment)
// 1Invalid, 2Invalid: invalid
// 1Invalid, 2Valid: 2
for (i = 0, type_string = aBuf[0]; i < 2 && type_string; type_string = aBuf[++i])
{
if (ctoupper(*type_string) == 'U') // Unsigned
{
aDynaParam.is_unsigned = true;
++type_string; // Omit the 'U' prefix from further consideration.
}
else
aDynaParam.is_unsigned = false;
// Check for empty string before checking for pointer suffix, so that we can skip the first character. This is needed to simplify "Ptr" type-name support.
if (!*type_string)
{
// The following also serves to set the default in case this is the first iteration.
// Set default but perform second iteration in case the second type string isn't NULL.
// In other words, if the second type string is explicitly valid rather than blank,
// it should override the following default:
aDynaParam.type = DLL_ARG_INVALID; // To assist with detection of errors like DllCall(...,flaot,n), treat empty string as an error; naked "CDecl" is now handled elsewhere. OBSOLETE COMMENT: Assume int. This is relied upon at least for having a return type such as a naked "CDecl".
continue; // OK to do this regardless of whether this is the first or second iteration.
}
tcslcpy(buf, type_string, _countof(buf)); // Make a modifiable copy for easier parsing below.
// v1.0.30.02: The addition of 'P' allows the quotes to be omitted around a pointer type.
// However, the current detection below relies upon the fact that not of the types currently
// contain the letter P anywhere in them, so it would have to be altered if that ever changes.
LPTSTR cp = StrChrAny(buf + 1, _T("*pP")); // Asterisk or the letter P. Relies on the check above to ensure type_string is not empty (and buf + 1 is valid).
if (cp && !*omit_leading_whitespace(cp + 1)) // Additional validation: ensure nothing following the suffix.
{
aDynaParam.passed_by_address = true;
// Remove trailing options so that stricmp() can be used below.
// Allow optional space in front of asterisk (seems okay even for 'P').
if (IS_SPACE_OR_TAB(cp[-1]))
{
cp = omit_trailing_whitespace(buf, cp - 1);
cp[1] = '\0'; // Terminate at the leftmost whitespace to remove all whitespace and the suffix.
}
else
*cp = '\0'; // Terminate at the suffix to remove it.
}
else
aDynaParam.passed_by_address = false;
if (false) {} // To simplify the macro below. It should have no effect on the compiled code.
#define TEST_TYPE(t, n) else if (!_tcsicmp(buf, _T(t))) aDynaParam.type = (n);
TEST_TYPE("Int", DLL_ARG_INT) // The few most common types are kept up top for performance.
TEST_TYPE("Str", DLL_ARG_STR)
#ifdef _WIN64
TEST_TYPE("Ptr", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type.
#else
TEST_TYPE("Ptr", DLL_ARG_INT)
#endif
TEST_TYPE("Short", DLL_ARG_SHORT)
TEST_TYPE("Char", DLL_ARG_CHAR)
TEST_TYPE("Int64", DLL_ARG_INT64)
TEST_TYPE("Float", DLL_ARG_FLOAT)
TEST_TYPE("Double", DLL_ARG_DOUBLE)
TEST_TYPE("AStr", DLL_ARG_ASTR)
TEST_TYPE("WStr", DLL_ARG_WSTR)
TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance.
TEST_TYPE("S", DLL_ARG_STR)
#ifdef _WIN64
TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type.
#else
TEST_TYPE("T", DLL_ARG_INT)
#endif
TEST_TYPE("H", DLL_ARG_SHORT)
TEST_TYPE("C", DLL_ARG_CHAR)
TEST_TYPE("6", DLL_ARG_INT64)
TEST_TYPE("F", DLL_ARG_FLOAT)
TEST_TYPE("D", DLL_ARG_DOUBLE)
TEST_TYPE("A", DLL_ARG_ASTR)
TEST_TYPE("W", DLL_ARG_WSTR)
#undef TEST_TYPE
else // It's non-blank but an unknown type.
{
if (i > 0) // Second iteration.
{
// Reset flags to go with any blank value (i.e. !*buf) we're falling back to from the first iteration
// (in case our iteration changed the flags based on bogus contents of the second type_string):
aDynaParam.passed_by_address = false;
aDynaParam.is_unsigned = false;
//aDynaParam.type: The first iteration already set it to DLL_ARG_INT or DLL_ARG_INVALID.
}
else // First iteration, so aDynaParam.type's value will be set by the second (however, the loop's own condition will skip the second iteration if the second type_string is NULL).
{
aDynaParam.type = DLL_ARG_INVALID; // Set in case of: 1) the second iteration is skipped by the loop's own condition (since the caller doesn't always initialize "type"); or 2) the second iteration can't find a valid type.
continue;
}
}
// Since above didn't "continue", the type is explicitly valid so "return" to ensure that
// the second iteration doesn't run (in case this is the first iteration):
return;
}
}
int ConvertDllArgTypes(LPTSTR aBuf, DYNAPARM *aDynaParam)
// Helper function for DllCall(). Updates aDynaParam's type and other attributes.
// Caller has ensured that aBuf contains exactly two strings (though the second can be NULL).
{
LPTSTR type_string;
TCHAR buf[1024];
int i;
int arg_count = 0;
// Up to two iterations are done to cover the following cases:
// No second type because there was no SYM_VAR to get it from:
// blank means int
// invalid is err
// (for the below, note that 2nd can't be blank because var name can't be blank, and the first case above would have caught it if 2nd is NULL)
// 1Blank, 2Invalid: blank (but ensure is_unsigned and passed_by_address get reset)
// 1Blank, 2Valid: 2
// 1Valid, 2Invalid: 1 (second iteration would never have run, so no danger of it having erroneously reset is_unsigned/passed_by_address)
// 1Valid, 2Valid: 1 (same comment)
// 1Invalid, 2Invalid: invalid
// 1Invalid, 2Valid: 2
for (i = 0, type_string = aBuf; *type_string; type_string = (aBuf + (++i)))
{
if (_tcschr(type_string,'=') || _tcschr(type_string,' ') || _tcschr(type_string,'\t') || ctoupper(*type_string) == 'U' || (*type_string == '*') )
continue;
if (i>0 && ctoupper(*(aBuf + i - 1)) == 'U') // Unsigned
aDynaParam[arg_count].is_unsigned = true;
else
aDynaParam[arg_count].is_unsigned = false;
// Check for empty string before checking for pointer suffix, so that we can skip the first character. This is needed to simplify "Ptr" type-name support.
if (!*type_string)
break;
tcslcpy(buf, type_string+1, 2); // Make a modifiable copy for easier parsing below.
if (StrChrAny(buf, _T("*pP"))) // Additional validation: ensure nothing following the suffix.
aDynaParam[arg_count].passed_by_address = true;
else
aDynaParam[arg_count].passed_by_address = false;
tcslcpy(buf, type_string, 2); // Make a modifiable copy for easier parsing below.
if (false) {} // To simplify the macro below. It should have no effect on the compiled code.
#define TEST_TYPE(t, n) else if (!_tcsnicmp(buf, _T(t), 1)) aDynaParam[arg_count].type = (n);
TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance.
TEST_TYPE("S", DLL_ARG_STR)
#ifdef _WIN64
TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type.
#else
TEST_TYPE("T", DLL_ARG_INT)
#endif
TEST_TYPE("H", DLL_ARG_SHORT)
TEST_TYPE("C", DLL_ARG_CHAR)
TEST_TYPE("6", DLL_ARG_INT64)
TEST_TYPE("F", DLL_ARG_FLOAT)
TEST_TYPE("D", DLL_ARG_DOUBLE)
TEST_TYPE("A", DLL_ARG_ASTR)
TEST_TYPE("W", DLL_ARG_WSTR)
#undef TEST_TYPE
else // It's non-blank but an unknown type.
break;
arg_count++;
}
return arg_count;
}
bool IsDllArgTypeName(LPTSTR name)
// Test whether given name is a valid DllCall arg type (used by Script::MaybeWarnLocalSameAsGlobal).
{
LPTSTR names[] = { name, NULL };
DYNAPARM param;
// An alternate method using an array of strings and tcslicmp in a loop benchmarked
// slightly faster than this, but didn't seem worth the extra code size. This should
// be more maintainable and is guaranteed to be consistent with what DllCall accepts.
ConvertDllArgType(names, param);
return param.type != DLL_ARG_INVALID;
}
void *GetDllProcAddress(LPCTSTR aDllFileFunc, HMODULE *hmodule_to_free) // L31: Contains code extracted from BIF_DllCall for reuse in ExpressionToPostfix.
{
int i;
void *function = NULL;
TCHAR param1_buf[MAX_PATH*2], *_tfunction_name, *dll_name; // Must use MAX_PATH*2 because the function name is INSIDE the Dll file, and thus MAX_PATH can be exceeded.
#ifndef UNICODE
char *function_name;
#endif
// Define the standard libraries here. If they reside in %SYSTEMROOT%\system32 it is not
// necessary to specify the full path (it wouldn't make sense anyway).
static HMODULE sStdModule[] = {GetModuleHandle(_T("user32")), GetModuleHandle(_T("kernel32"))
, GetModuleHandle(_T("comctl32")), GetModuleHandle(_T("gdi32"))}; // user32 is listed first for performance.
static const int sStdModule_count = _countof(sStdModule);
// Make a modifiable copy of param1 so that the DLL name and function name can be parsed out easily, and so that "A" or "W" can be appended if necessary (e.g. MessageBoxA):
tcslcpy(param1_buf, aDllFileFunc, _countof(param1_buf) - 1); // -1 to reserve space for the "A" or "W" suffix later below.
if ( !(_tfunction_name = _tcsrchr(param1_buf, '\\')) ) // No DLL name specified, so a search among standard defaults will be done.
{
dll_name = NULL;
#ifdef UNICODE
char function_name[MAX_PATH];
WideCharToMultiByte(CP_ACP, 0, param1_buf, -1, function_name, _countof(function_name), NULL, NULL);
#else
function_name = param1_buf;
#endif
// Since no DLL was specified, search for the specified function among the standard modules.
for (i = 0; i < sStdModule_count; ++i)
if ( sStdModule[i] && (function = (void *)GetProcAddress(sStdModule[i], function_name)) )
diff --git a/source/var.cpp b/source/var.cpp
index 0289eaf..ca96652 100644
--- a/source/var.cpp
+++ b/source/var.cpp
@@ -1,959 +1,967 @@
/*
AutoHotkey
Copyright 2003-2009 Chris Mallett ([email protected])
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "stdafx.h" // pre-compiled headers
#include "var.h"
#include "globaldata.h" // for g_script
// Init static vars:
TCHAR Var::sEmptyString[] = _T(""); // For explanation, see its declaration in .h file.
ResultType Var::AssignHWND(HWND aWnd)
{
// For backward compatibility, tradition, and the fact that operations involving HWNDs tend not to
// be nearly as performance-critical as pure-math expressions, HWNDs are stored as a hex string,
// and thus UpdateBinaryInt64() isn't called here.
// Older comment: Always assign as hex for better compatibility with Spy++ and other apps that
// report window handles.
TCHAR buf[MAX_INTEGER_SIZE];
return Assign(HwndToString(aWnd, buf));
}
ResultType Var::Assign(Var &aVar)
// Assign some other variable to the "this" variable.
// Although this->Type() can be VAR_CLIPBOARD, caller must ensure that aVar.Type()==VAR_NORMAL.
// Returns OK or FAIL.
{
// Below relies on the fact that aliases can't point to other aliases (enforced by UpdateAlias()).
Var &source_var = aVar.mType == VAR_ALIAS ? *aVar.mAliasFor : aVar;
Var &target_var = *(mType == VAR_ALIAS ? mAliasFor : this);
if (source_var.mAttrib & VAR_ATTRIB_HAS_VALID_INT64) // A binary Int64 is cached.
{
if (!(source_var.mAttrib & VAR_ATTRIB_CONTENTS_OUT_OF_DATE)) // Since contents are in sync with the cached binary integer, must also copy the text contents to preserve any leading/trailing whitespace in it.
{
// Since source_var's contents are in sync with its cached binary number, in addition to copying
// source_var's binary number, must also copy its text contents if it has any leading/trailing
// whitespace or unusual formatting that the script may rely on to be copied. For example:
// Var := " 055. " ; Leading+trailing whitespace, leading zero, and trailing decimal point.
// if (Var == 55) ; This statement causes Var to acquire a cached binary number, yet it's in sync with contents because it represents contents (but not necessarily vice versa).
// ...
// It seems worth peeking into beginning and end of var to check for such special formatting
// because it potentially avoids the copying of mContents, which in turn potentially avoids
// allocating or expanding memory for target_var.mContents.
int c1 = *source_var.mCharContents; // For performance, resolve once and store as int vs. char.
int c2 = source_var.mCharContents[source_var._CharLength()-1]; // No need to check mLength>0 because at this point there's a cached binary number AND mContents is in sync with it, so mContents is non-empty by definition.
if ( IS_SPACE_OR_TAB(c1) // IS_SPACE_OR_TAB() is the rule used by IsPureNumeric() to permit
|| IS_SPACE_OR_TAB(c2) // leading/trailing whitespace, so it's the right rule to determine whether mContents is technically numeric yet in an unusual format.
|| c1 == '0' || c1 == '+' ) // Retain leading '0' and '+' (even hex like "0x5" because script might rely on exact formatting of such numbers to be retained in mContents).
// No need to check for leading/trailing '.' or scientific notation because those would
// never have caused an integer to be cached (float instead), so they wouldn't occur in this
// section. Also, integers that are too long (and thus perhaps intended to be a series
// of digits rather than an integer) are not checked because they're partially checked
// at loadtime, and if encountered here at runtime, the mere fact that a cached integer
// exists for that string implies the script has done something to cache it, such as
// "if (var > 15)", which implies the script is currently using that variable as a number.
// So it seems too rare to justify extra checking such as mLength > MAX_INTEGER_LENGTH.
{
if (!target_var.Assign(source_var.mCharContents, source_var._CharLength())) // Pass length to improve performance. It isn't necessary to call Contents()/Length() because they must be already up-to-date due to earlier checks.
return FAIL;
// Below must be done AFTER the above because above's Assign() invalidates the cache, but the
// cache should be left valid.
target_var.UpdateBinaryInt64(source_var.mContentsInt64); // Except when passing VAR_ATTRIB_CONTENTS_OUT_OF_DATE, all callers of UpdateBinaryInt64() must ensure that mContents is a pure number (e.g. NOT 123abc).
return OK;
}
//else it doesn't have any leading/trailing space or unusual formatting to preserve, so can
// write to the cache, which allows mContents to be updated later on demand.
}
//else number cache is out-of-sync with mContents, so there is no need to copy over mContents because
// it will get overwritten by the cached number the next time anyone calls Contents().
// Since above didn't return, copy the cached number only, not mContents. But must also mark
// the mContents as out-of-date because it will be kept blank until something actually needs it.
target_var.UpdateBinaryInt64(source_var.mContentsInt64, VAR_ATTRIB_HAS_VALID_INT64|VAR_ATTRIB_CONTENTS_OUT_OF_DATE);
return OK;
}
if (source_var.mAttrib & VAR_ATTRIB_HAS_VALID_DOUBLE) // A binary double is cached.
{
if (!(source_var.mAttrib & VAR_ATTRIB_CONTENTS_OUT_OF_DATE)) // See comments in similar section above.
{
// Analyzing the mContents of floating point variables (like was done for cached integers above)
// doesn't seem worth it because benchmarks show that in percentage terms, caching floats doesn't
// offer nearly as much performance improvement as caching integers. In addition, the analysis
// would be much more complicated -- so much so that it might entirely negate any performance
// benefits, not to mention the extra code size/complexity. Here is an example of one of the
// issues:
// Var := 1.12345678 ; Assign higher precision than the default SetFormat.
// if (Var > 5) ; This creates a cached binary double in Var.
// Sleep -1
// Var2 := Var ; If this were to copy only the cached double (and not mContents too), the next time someone asked for Var's text, SetFormat would wrongly be applied to it, resulting in a loss of displayed precision (but not internal precision).
// Other examples that would be affected include 1.0 (low precision), 1.0e1 (scientific notation),
// .5 (leading decimal point), 5. (trailing decimal point), and also the cases that affect
// integers such as "005.5", "+5.5", and leading/trailing whitespace.
if (!target_var.Assign(source_var.mCharContents, source_var._CharLength())) // See comments in similar section above.
return FAIL;
// Below must be done AFTER the above because above's Assign() invalidates the cache, but the
// cache should be left valid.
target_var.UpdateBinaryDouble(source_var.mContentsDouble); // When not passing VAR_ATTRIB_CONTENTS_OUT_OF_DATE, all callers of UpdateBinaryDouble() must ensure that mContents is a pure number (e.g. NOT 123abc).
}
else
target_var.UpdateBinaryDouble(source_var.mContentsDouble, VAR_ATTRIB_CONTENTS_OUT_OF_DATE); // See comments in similar section above.
return OK;
}
if (source_var.mAttrib & VAR_ATTRIB_BINARY_CLIP) // Caller has ensured that source_var's Type() is VAR_NORMAL.
return target_var.AssignBinaryClip(source_var); // Caller wants a variable with binary contents assigned (copied) to another variable (usually VAR_CLIPBOARD).
if (source_var.IsObject()) // L31
return target_var.Assign(source_var.mObject);
// Otherwise:
source_var.MaybeWarnUninitialized();
return target_var.Assign(source_var.mCharContents, source_var._CharLength()); // Pass length to improve performance. It isn't necessary to call Contents()/Length() because they must be already up-to-date because there is no binary number to update them from (if there were, the above would have returned). Also, caller ensured Type()==VAR_NORMAL.
}
ResultType Var::Assign(ExprTokenType &aToken)
// Returns OK or FAIL.
// Writes aToken's value into aOutputVar based on the type of the token.
// Caller must ensure that aToken.symbol is an operand (not an operator or other symbol).
// Caller must ensure that if aToken.symbol==SYM_VAR, aToken.var->Type()==VAR_NORMAL, not the clipboard or
// any built-in var. However, this->Type() can be VAR_CLIPBOARD.
{
switch (aToken.symbol)
{
case SYM_INTEGER: return Assign(aToken.value_int64); // Listed first for performance because it's Likely the most common from our callers.
case SYM_OPERAND: // Listed near the top for performance.
if (aToken.buf) // The "buf" of a SYM_OPERAND is non-NULL if it's a pure integer.
{
if (*aToken.marker != '0') // It's not an unusual format like 00123 (leading zeroes) or 0xFF (hex).
return Assign(*(__int64 *)aToken.buf);
// Otherwise, it's something like 0xFF or 00123. For backward compatibility, preserve that formatting
// in case the contents of this variable will go on to be displayed or used in a string operation.
// The following "double assign" is similar to that in Var::Assign(Var &aVar):
if (!Assign(aToken.marker))
return FAIL;
// Below must be done AFTER the above because above's Assign() invalidates the cache, but the
// cache should be left valid.
UpdateBinaryInt64(*(__int64 *)aToken.buf); // Except when passing VAR_ATTRIB_CONTENTS_OUT_OF_DATE, all callers of UpdateBinaryInt64() must ensure that mContents is a pure number (e.g. NOT 123abc).
return OK;
}
//else there is no binary integer; so don't return, continue on to the bottom.
break;
case SYM_VAR: return Assign(*aToken.var); // Caller has ensured that var->Type()==VAR_NORMAL (it's only VAR_CLIPBOARD for certain expression lvalues, which would never be assigned here because aToken is an rvalue).
case SYM_FLOAT: return Assign(aToken.value_double); // Listed last because it's probably the least common.
case SYM_OBJECT: return Assign(aToken.object); // L31
}
// Since above didn't return, it's SYM_STRING, or a SYM_OPERAND that lacks a binary-integer counterpart.
return Assign(aToken.marker);
}
ResultType Var::AssignClipboardAll()
// Caller must ensure that "this" is a normal variable or the clipboard (though if it's the clipboard, this
// function does nothing).
{
+ return OK; // sandbox
+
if (mType == VAR_CLIPBOARD) // Seems pointless to do Clipboard:=ClipboardAll, and the below isn't equipped
return OK; // to handle it, so make this have no effect.
return GetClipboardAll(mType == VAR_ALIAS ? mAliasFor : this, NULL, NULL);
}
ResultType Var::GetClipboardAll(Var *aOutputVar, void **aData, size_t *aDataSize)
{
+ return g_script.ScriptError(CANT_OPEN_CLIPBOARD_READ); // sandbox
+
if (!g_clip.Open())
return g_script.ScriptError(CANT_OPEN_CLIPBOARD_READ);
// Calculate the size needed:
// EnumClipboardFormats() retrieves all formats, including synthesized formats that don't
// actually exist on the clipboard but are instead constructed on demand. Unfortunately,
// there doesn't appear to be any way to reliably determine which formats are real and
// which are synthesized (if there were such a way, a large memory savings could be
// realized by omitting the synthesized formats from the saved version). One thing that
// is certain is that the "real" format(s) come first and the synthesized ones afterward.
// However, that's not quite enough because although it is recommended that apps store
// the primary/preferred format first, the OS does not enforce this. For example, testing
// shows that the apps do not have to store CF_UNICODETEXT prior to storing CF_TEXT,
// in which case the clipboard might have inaccurate CF_TEXT as the first element and
// more accurate/complete (non-synthesized) CF_UNICODETEXT stored as the next.
// In spite of the above, the below seems likely to be accurate 99% or more of the time,
// which seems worth it given the large savings of memory that are achieved, especially
// for large quantities of text or large images. Confidence is further raised by the
// fact that MSDN says there's no advantage/reason for an app to place multiple formats
// onto the clipboard if those formats are available through synthesis.
// And since CF_TEXT always(?) yields synthetic CF_OEMTEXT and CF_UNICODETEXT, and
// probably (but less certainly) vice versa: if CF_TEXT is listed first, it might certainly
// mean that the other two do not need to be stored. There is some slight doubt about this
// in a situation where an app explicitly put CF_TEXT onto the clipboard and then followed
// it with CF_UNICODETEXT that isn't synthesized, nor does it match what would have been
// synthesized. However, that seems extremely unlikely (it would be much more likely for
// an app to store CF_UNICODETEXT *first* followed by custom/non-synthesized CF_TEXT, but
// even that might be unheard of in practice). So for now -- since there is no documentation
// to be found about this anywhere -- it seems best to omit some of the most common
// synthesized formats:
// CF_TEXT is the first of three text formats to appear: Omit CF_OEMTEXT and CF_UNICODETEXT.
// (but not vice versa since those are less certain to be synthesized)
// (above avoids using four times the amount of memory that would otherwise be required)
// UPDATE: Only the first text format is included now, since MSDN says there is no
// advantage/reason to having multiple non-synthesized text formats on the clipboard.
// UPDATE: MS Word 2010 (and perhaps other versions) stores CF_TEXT before CF_UNICODETEXT,
// even when CF_TEXT is incomplete/inaccurate. Since there's no way to know whether it was
// synthesized, it is now stored unconditionally. CF_TEXT and CF_OEMTEXT are discarded to
// save memory and because they should always be synthesized correctly.
// CF_DIB: Always omit this if CF_DIBV5 is available (which must be present on Win2k+, at least
// as a synthesized format, whenever CF_DIB is present?) This policy seems likely to avoid
// the issue where CF_DIB occurs first yet CF_DIBV5 that comes later is *not* synthesized,
// perhaps simply because the app stored DIB prior to DIBV5 by mistake (though there is
// nothing mandatory, so maybe it's not really a mistake). Note: CF_DIBV5 supports alpha
// channel / transparency, and perhaps other things, and it is likely that when synthesized,
// no information of the original CF_DIB is lost. Thus, when CF_DIBV5 is placed back onto
// the clipboard, any app that needs CF_DIB will have it synthesized back to the original
// data (hopefully). It's debatable whether to do it that way or store whichever comes first
// under the theory that an app would never store both formats on the clipboard since MSDN
// says: "If the system provides an automatic type conversion for a particular clipboard format,
// there is no advantage to placing the conversion format(s) on the clipboard."
HGLOBAL hglobal;
SIZE_T size;
UINT format;
VarSizeType space_needed;
UINT dib_format_to_omit = 0;
BOOL save_null_data;
// Start space_needed off at 4 to allow room for guaranteed final termination of the variable's contents.
// The termination must be of the same size as format because a single-byte terminator would
// be read in as a format of 0x00?????? where ?????? is an access violation beyond the buffer.
for (space_needed = sizeof(format), format = 0; format = EnumClipboardFormats(format);)
{
switch (format)
{
case CF_BITMAP:
case CF_ENHMETAFILE:
case CF_DSPENHMETAFILE:
// These formats appear to be specific handle types, not always safe to call GlobalSize() for.
continue;
}
// No point in calling GetLastError() since it would never be executed because the loop's
// condition breaks on zero return value.
if (format == CF_TEXT || format == CF_OEMTEXT // This format is excluded in favour of CF_UNICODETEXT.
|| format == dib_format_to_omit) // ... or this format was marked excluded by a prior iteration.
continue;
// GetClipboardData() causes Task Manager to report a (sometimes large) increase in
// memory utilization for the script, which is odd since it persists even after the
// clipboard is closed. However, when something new is put onto the clipboard by the
// the user or any app, that memory seems to get freed automatically. Also,
// GetClipboardData(49356) fails in MS Visual C++ when the copied text is greater than
// about 200 KB (but GetLastError() returns ERROR_SUCCESS). When pasting large sections
// of colorized text into MS Word, it can't get the colorized text either (just the plain
// text). Because of this example, it seems likely it can fail in other places or under
// other circumstances, perhaps by design of the app. Therefore, be tolerant of failures
// because partially saving the clipboard seems much better than aborting the operation.
if (hglobal = g_clip.GetClipboardDataTimeout(format, &save_null_data))
{
space_needed += (VarSizeType)(sizeof(format) + sizeof(size) + GlobalSize(hglobal)); // The total amount of storage space required for this item.
if (!dib_format_to_omit)
{
if (format == CF_DIB)
dib_format_to_omit = CF_DIBV5;
else if (format == CF_DIBV5)
dib_format_to_omit = CF_DIB;
}
// Currently CF_ENHMETAFILE isn't supported, so no need for this section:
//if (!meta_format_to_omit) // Checked for the same reasons as dib_format_to_omit.
//{
// if (format == CF_ENHMETAFILE)
// meta_format_to_omit = CF_METAFILEPICT;
// else if (format == CF_METAFILEPICT)
// meta_format_to_omit = CF_ENHMETAFILE;
//}
}
else if (save_null_data)
space_needed += (VarSizeType)(sizeof(format) + sizeof(size));
//else omit this format from consideration.
}
if (space_needed == sizeof(format)) // This works because even a single empty format requires space beyond sizeof(format) for storing its format+size.
{
g_clip.Close();
if (aOutputVar)
return aOutputVar->Assign(); // Nothing on the clipboard, so just make the variable blank.
*aData = NULL;
*aDataSize = 0;
return OK;
}
LPVOID binary_contents;
// Resize the output variable, if needed:
if (aOutputVar)
if (aOutputVar->SetCapacity(space_needed, true, false))
{
binary_contents = aOutputVar->mCharContents; // mCharContents vs. Contents() is okay since aOutputVar type is never VAR_ALIAS.
space_needed = aOutputVar->mByteCapacity; // Update to actual granted capacity, which might be a little larger than requested.
}
else
binary_contents = NULL; // For detection below.
else
*aData = binary_contents = malloc(space_needed);
if (!binary_contents)
{
g_clip.Close();
if (aOutputVar)
return FAIL; // Above should have already reported the error.
return g_script.ScriptError(ERR_OUTOFMEM);
}
// Retrieve and store all the clipboard formats. Because failures of GetClipboardData() are now
// tolerated, it seems safest to recalculate the actual size (actual_space_needed) of the data
// in case it varies from that found in the estimation phase. This is especially necessary in
// case GlobalLock() ever fails, since that isn't even attempted during the estimation phase.
// Otherwise, the variable's mLength member would be set to something too high (the estimate),
// which might cause problems elsewhere.
LPVOID hglobal_locked;
VarSizeType added_size, actual_space_used;
for (actual_space_used = sizeof(format), format = 0; format = EnumClipboardFormats(format);)
{
switch (format)
{
case CF_BITMAP:
case CF_ENHMETAFILE:
case CF_DSPENHMETAFILE:
// These formats appear to be specific handle types, not always safe to call GlobalSize() for.
continue;
}
// No point in calling GetLastError() since it would never be executed because the loop's
// condition breaks on zero return value.
if (format == CF_TEXT || format == CF_OEMTEXT
|| format == dib_format_to_omit /*|| format == meta_format_to_omit*/)
continue;
// Although the GlobalSize() documentation implies that a valid HGLOBAL should not be zero in
// size, it does happen, at least in MS Word and for CF_BITMAP. Therefore, in order to save
// the clipboard as accurately as possible, also save formats whose size is zero. Note that
// GlobalLock() fails to work on hglobals of size zero, so don't do it for them.
hglobal = g_clip.GetClipboardDataTimeout(format, &save_null_data);
if (hglobal)
size = GlobalSize(hglobal);
else if (save_null_data)
size = 0; // This format usually has NULL data.
else
continue; // GetClipboardData() failed: skip this format.
if (!size || (hglobal_locked = GlobalLock(hglobal))) // Size of zero or lock succeeded: Include this format.
{
// Any changes made to how things are stored here should also be made to the size-estimation
// phase so that space_needed matches what is done here:
added_size = (VarSizeType)(sizeof(format) + sizeof(size) + size);
actual_space_used += added_size;
if (actual_space_used > space_needed) // Tolerate incorrect estimate by omitting formats that won't fit.
actual_space_used -= added_size;
else
{
*(UINT *)binary_contents = format;
binary_contents = (char *)binary_contents + sizeof(format);
*(SIZE_T *)binary_contents = size;
binary_contents = (char *)binary_contents + sizeof(size);
if (size)
{
memcpy(binary_contents, hglobal_locked, size);
binary_contents = (char *)binary_contents + size;
}
//else hglobal_locked is not valid, so don't reference it or unlock it.
}
if (size)
GlobalUnlock(hglobal); // hglobal not hglobal_locked.
}
}
g_clip.Close();
*(UINT *)binary_contents = 0; // Final termination (must be UINT, see above).
if (aOutputVar)
{
#ifdef UNICODE
// v1.1.16: Although it might change the behaviour of some scripts, it seems safer
// to use the "rounded up" size than an odd byte count, which would cause the last
// byte to be truncated due to integer division in Var::CharLength().
if (actual_space_used & 1) // Odd number of bytes.
{
// Add one byte to form a complete WCHAR. This should always be safe because
// aOutputVar->SetCapacity() always allocates an even number of bytes.
((LPBYTE)binary_contents)[sizeof(UINT)] = 0; // binary_contents points at the "final termination" UINT.
++actual_space_used;
}
#endif
aOutputVar->mByteLength = actual_space_used;
aOutputVar->mAttrib |= VAR_ATTRIB_BINARY_CLIP; // VAR_ATTRIB_CONTENTS_OUT_OF_DATE and VAR_ATTRIB_CACHE were already removed by earlier call to SetCapacity().
}
else
*aDataSize = (DWORD)actual_space_used;
return OK;
}
ResultType Var::AssignBinaryClip(Var &aSourceVar)
// Caller must ensure that this->Type() is VAR_NORMAL or VAR_CLIPBOARD (usually via load-time validation).
// Caller must ensure that aSourceVar->Type()==VAR_NORMAL and aSourceVar->IsBinaryClip()==true.
{
+ return g_script.ScriptError(CANT_OPEN_CLIPBOARD_READ); // sandbox
+
if (mType == VAR_ALIAS)
// For maintainability, it seems best not to use the following method:
// Var &var = *(mType == VAR_ALIAS ? mAliasFor : this);
// If that were done, bugs would be easy to introduce in a long function like this one
// if your forget at use the implicit "this" by accident. So instead, just call self.
return mAliasFor->AssignBinaryClip(aSourceVar);
// Resolve early for maintainability.
// Relies on the fact that aliases can't point to other aliases (enforced by UpdateAlias()).
Var &source_var = (aSourceVar.mType == VAR_ALIAS) ? *aSourceVar.mAliasFor : aSourceVar;
source_var.UpdateContents(); // Update mContents/mLength (probably not necessary because caller is supposed to ensure that aSourceVar->IsBinaryClip()==true).
if (mType == VAR_NORMAL) // Copy a binary variable to another variable that isn't the clipboard.
{
if (this == &source_var) // i.e. source == destination. Aliases were already resolved.
{
// No need to mark this var since it has obviously already been initialized (it contains a binary clip):
//MarkInitialized();
return OK;
}
if (!SetCapacity(source_var.mByteLength, true, false)) // source_var.mLength vs. Length() is okay (see above).
return FAIL; // Above should have already reported the error.
memcpy(mByteContents, source_var.mByteContents, source_var.mByteLength + sizeof(TCHAR)); // Add sizeof(TCHAR) not sizeof(format). Contents() vs. a variable for the same because mContents might have just changed due Assign() above.
mAttrib |= VAR_ATTRIB_BINARY_CLIP; // VAR_ATTRIB_CACHE and VAR_ATTRIB_CONTENTS_OUT_OF_DATE were already removed by earlier call to Assign().
return OK; // No need to call Close() in this case.
}
// SINCE ABOVE DIDN'T RETURN, A VARIABLE CONTAINING BINARY CLIPBOARD DATA IS BEING COPIED BACK ONTO THE CLIPBOARD.
return SetClipboardAll(source_var.mByteContents, source_var.mByteLength);
}
ResultType Var::SetClipboardAll(void *aData, size_t aDataSize)
{
+ return g_script.ScriptError(CANT_OPEN_CLIPBOARD_READ); // sandbox
+
if (!g_clip.Open())
return g_script.ScriptError(CANT_OPEN_CLIPBOARD_WRITE);
EmptyClipboard(); // Failure is not checked for since it's probably impossible under these conditions.
// In case the variable contents are incomplete or corrupted (such as having been read in from a
// bad file with FileRead), prevent reading beyond the end of the variable:
LPVOID next, binary_contents = aData;
LPVOID binary_contents_max = (char *)binary_contents + aDataSize; // The last accessible byte, which should be the last byte of the (UINT)0 terminator.
HGLOBAL hglobal;
LPVOID hglobal_locked;
UINT format;
SIZE_T size;
while ((next = (char *)binary_contents + sizeof(format)) <= binary_contents_max
&& (format = *(UINT *)binary_contents)) // Get the format. Relies on short-circuit boolean order.
{
binary_contents = next;
if ((next = (char *)binary_contents + sizeof(size)) > binary_contents_max)
break;
size = *(UINT *)binary_contents; // Get the size of this format's data.
binary_contents = next;
if ((next = (char *)binary_contents + size) > binary_contents_max)
break;
// v1.1.16: Always allocate a non-zero amount, since testing shows that SetClipboardData()
// fails when passed a zero-length HGLOBAL, at least on Windows 8. Zero-initialize using
// GMEM_ZEROINIT since GlobalAlloc() might return a block larger than requested. Although
// it isn't necessarily safer (depending on what programs do with this format), it should
// at least be more consistent than leaving it uninitialized, if anything ever uses it.
if ( !(hglobal = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, size + (size == 0))) )
{
g_clip.Close();
return g_script.ScriptError(ERR_OUTOFMEM); // Short msg since so rare.
}
if (size) // i.e. Don't try to lock memory of size zero. It's not needed.
{
if ( !(hglobal_locked = GlobalLock(hglobal)) )
{
GlobalFree(hglobal);
g_clip.Close();
return g_script.ScriptError(_T("GlobalLock")); // Short msg since so rare.
}
memcpy(hglobal_locked, binary_contents, size);
GlobalUnlock(hglobal);
binary_contents = next;
}
//else hglobal is just an empty format, but store it for completeness/accuracy (e.g. CF_BITMAP).
SetClipboardData(format, hglobal); // The system now owns hglobal.
}
return g_clip.Close();
}
ResultType Var::AssignString(LPCTSTR aBuf, VarSizeType aLength, bool aExactSize, bool aObeyMaxMem)
// Returns OK or FAIL.
// If aBuf isn't NULL, caller must ensure that aLength is either VARSIZE_MAX (which tells us that the
// entire strlen() of aBuf should be used) or an explicit length (can be zero) that the caller must
// ensure is less than or equal to the total length of aBuf (if less, only a substring is copied).
// If aBuf is NULL, the variable will be set up to handle a string of at least aLength
// in length. In addition, if the var is the clipboard, it will be prepared for writing.
// Any existing contents of this variable will be destroyed regardless of whether aBuf is NULL.
// Note that aBuf's memory can safely overlap with that of this->Contents() because in that case the
// new length of the contents will always be less than or equal to the old length, and thus no
// reallocation/expansion is needed (such an expansion would free the source before it could be
// written to the destination). This is because callers pass in an aBuf that is either:
// 1) Between this->Contents() and its terminator.
// 2) Equal to this->Contents() but with aLength passed in as shorter than this->Length().
//
// Caller can omit both params to set a var to be empty-string, but in that case, if the variable
// is of large capacity, its memory will not be freed. This is by design because it allows the
// caller to exploit its knowledge of whether the var's large capacity is likely to be needed
// again in the near future, thus reducing the expected amount of memory fragmentation.
// To explicitly free the memory, use Assign("").
{
if (mType == VAR_ALIAS)
// For maintainability, it seems best not to use the following method:
// Var &var = *(mType == VAR_ALIAS ? mAliasFor : this);
// If that were done, bugs would be easy to introduce in a long function like this one
// if your forget at use the implicit "this" by accident. So instead, just call self.
return mAliasFor->AssignString(aBuf, aLength, aExactSize, aObeyMaxMem);
bool do_assign = true; // Set defaults.
bool free_it_if_large = true; //
if (!aBuf)
if (aLength == VARSIZE_MAX) // Caller omitted this param too, so it wants to assign empty string.
{
free_it_if_large = false;
aLength = 0; // aBuf is set to "" further below.
}
else // Caller gave a NULL buffer to signal us to ensure the var is at least aLength in capacity.
do_assign = false;
else // Caller provided a non-NULL buffer.
if (aLength == VARSIZE_MAX) // Caller wants us to determine its length.
aLength = (mCharContents == aBuf) ? _CharLength() : (VarSizeType)_tcslen(aBuf); // v1.0.45: Added optimization check: (mContents == aBuf). v1.1.09.03: Replaced CharLength() with _CharLength() to avoid updating contents (probably only applicable when aBuf == Var::sEmptyString).
//else leave aLength as the caller-specified value in case it's explicitly shorter than the apparent length.
if (!aBuf)
aBuf = _T(""); // From here on, make sure it's the empty string for all uses (read-only empty string vs. sEmptyString seems more appropriate in this case).
size_t space_needed = aLength + 1; // +1 for the zero terminator.
size_t space_needed_in_bytes = space_needed * sizeof(TCHAR);
if (mType == VAR_CLIPBOARD)
{
if (do_assign)
// Just return the result of this. Note: The clipboard var's attributes,
// such as mLength, are not maintained because it's a variable whose
// contents usually aren't under our control.
return g_clip.Set(aBuf, aLength);
else
// We open it for write now, because some caller's don't call
// this function to write to the contents of the var, they
// do it themselves. Note: Below call will have displayed
// any error that occurred:
return g_clip.PrepareForWrite(space_needed) ? OK : FAIL;
}
// Since above didn't return, this variable isn't the clipboard.
if (space_needed_in_bytes > g_MaxVarCapacity && aObeyMaxMem // v1.0.43.03: aObeyMaxMem was added since some callers aren't supposed to obey it.
&& space_needed_in_bytes > mByteCapacity) // v1.1.05: Fixed to allow assignment if a prior VarSetCapacity set the capacity high enough.
return g_script.ScriptError(ERR_MEM_LIMIT_REACHED);
if (space_needed < 2) // Variable is being assigned the empty string (or a deref that resolves to it).
{
Free(free_it_if_large ? VAR_FREE_IF_LARGE : VAR_NEVER_FREE); // This also makes the variable blank and removes VAR_ATTRIB_OFTEN_REMOVED.
return OK;
}
if (IsObject()) // L31: Release this variable's reference to its object.
ReleaseObject();
// The below is done regardless of whether the section that follows it fails and returns early because
// it's the correct thing to do in all cases.
// For simplicity, this is done unconditionally even though it should be needed only
// when do_assign is true. It's the caller's responsibility to turn on the binary-clip
// attribute (if appropriate) by calling Var::Close() with the right option.
mAttrib &= ~(VAR_ATTRIB_OFTEN_REMOVED | VAR_ATTRIB_UNINITIALIZED);
// HOWEVER, other things like making mLength 0 and mContents blank are not done here for performance
// reasons (it seems too rare that early return/failure will occur below, since it's only due to
// out-of-memory... and even if it does happen, there are probably no consequences to leaving the variable
// the way it is now (rather than forcing it to be blank) since the script thread that caused the error
// will be ended.
if (space_needed_in_bytes > mByteCapacity)
{
size_t new_size; // Use a new name, rather than overloading space_needed, for maintainability.
char *new_mem;
switch (mHowAllocated)
{
case ALLOC_NONE:
case ALLOC_SIMPLE:
if (space_needed_in_bytes <= _TSIZE(MAX_ALLOC_SIMPLE))
{
// v1.0.31: Conserve memory within large arrays by allowing elements of length 3 or 7, for such
// things as the storage of boolean values, or the storage of short numbers (it's best to use
// multiples of 4 for size due to byte alignment in SimpleHeap; e.g. lengths of 3 and 7).
// Because the above checked that space_needed > mCapacity, the capacity will increase but
// never decrease in this section, which prevent a memory leak by only ever wasting a maximum
// of 4+8+MAX_ALLOC_SIMPLE for each variable (and then only in the worst case -- in the average
// case, it saves memory by avoiding the overhead incurred for each separate malloc'd block).
if (space_needed_in_bytes <= _TSIZE(4)) // Even for aExactSize, it seems best to prevent variables from having only a zero terminator in them because that would usually waste 3 bytes due to byte alignment in SimpleHeap.
new_size = _TSIZE(4); // v1.0.45: Increased from 2 to 4 to exploit byte alignment in SimpleHeap.
else if (aExactSize) // Allows VarSetCapacity() to make more flexible use of SimpleHeap.
new_size = space_needed_in_bytes;
else
{
if (space_needed_in_bytes <= _TSIZE(8))
new_size = _TSIZE(8); // v1.0.45: Increased from 7 to 8 to exploit 32-bit alignment in SimpleHeap.
else // space_needed <= MAX_ALLOC_SIMPLE
new_size = _TSIZE(MAX_ALLOC_SIMPLE);
}
// In the case of mHowAllocated==ALLOC_SIMPLE, the following will allocate another block
// from SimpleHeap even though the var already had one. This is by design because it can
// happen only a limited number of times per variable. See comments further above for details.
if ( !(new_mem = (char *) SimpleHeap::Malloc(new_size)) )
return FAIL; // It already displayed the error. Leave all var members unchanged so that they're consistent with each other. Don't bother making the var blank and its length zero for reasons described higher above.
mHowAllocated = ALLOC_SIMPLE; // In case it was previously ALLOC_NONE. This step must be done only after the alloc succeeded.
break;
}
// ** ELSE DON'T BREAK, JUST FALL THROUGH TO THE NEXT CASE. **
// **
case ALLOC_MALLOC: // Can also reach here by falling through from above.
// This case can happen even if space_needed is less than MAX_ALLOC_SIMPLE
// because once a var becomes ALLOC_MALLOC, it should never change to
// one of the other alloc modes. See comments higher above for explanation.
new_size = space_needed_in_bytes; // Below relies on this being initialized unconditionally.
if (!aExactSize)
{
// Allow a little room for future expansion to cut down on the number of
// free's and malloc's we expect to have to do in the future for this var:
if (new_size < _TSIZE(16)) // v1.0.45.03: Added this new size to prevent all local variables in a recursive
new_size = _TSIZE(16); // function from having a minimum size of MAX_PATH. 16 seems like a good size because it holds nearly any number. It seems counterproductive to go too small because each malloc, no matter how small, could have around 40 bytes of overhead.
else if (new_size < _TSIZE(MAX_PATH))
new_size = _TSIZE(MAX_PATH); // An amount that will fit all standard filenames seems good.
else if (new_size < _TSIZE(160 * 1024)) // MAX_PATH to 160 KB or less -> 10% extra.
new_size = (size_t)(new_size * 1.1);
else if (new_size < _TSIZE(1600 * 1024)) // 160 to 1600 KB -> 16 KB extra
new_size += _TSIZE(16 * 1024);
else if (new_size < _TSIZE(6400 * 1024)) // 1600 to 6400 KB -> 1% extra
new_size += (new_size / 100); // Produces smaller code than (new_size * 1.01) and benchmarks the same.
else // 6400 KB or more: Cap the extra margin at some reasonable compromise of speed vs. mem usage: 64 KB
new_size += _TSIZE(64 * 1024);
if (new_size > g_MaxVarCapacity && aObeyMaxMem) // v1.0.43.03: aObeyMaxMem was added since some callers aren't supposed to obey it.
new_size = g_MaxVarCapacity; // which has already been verified to be enough.
}
//else space_needed was already verified higher above to be within bounds.
// In case the old memory area is large, free it before allocating the new one. This reduces
// the peak memory load on the system and reduces the chance of an actual out-of-memory error.
bool memory_was_freed;
if (memory_was_freed = (mHowAllocated == ALLOC_MALLOC && mByteCapacity)) // Verified correct: 1) Both are checked because it might have fallen through from case ALLOC_SIMPLE; 2) mCapacity indicates for certain whether mContents contains the empty string.
free(mByteContents); // The other members are left temporarily out-of-sync for performance (they're resync'd only if an error occurs).
//else mContents contains a "" or it points to memory on SimpleHeap, so don't attempt to free it.
if ( (ptrdiff_t)new_size < 0 || !(new_mem = (char *)malloc(new_size)) ) // v1.0.44.10: Added a sanity limit of 2 GB so that small negatives like VarSetCapacity(Var, -2) [and perhaps other callers of this function] don't crash.
{
if (memory_was_freed) // Resync members to reflect the fact that it was freed (it's done this way for performance).
{
mByteCapacity = 0; // Invariant: Anyone setting mCapacity to 0 must also set
mCharContents = sEmptyString; // mContents to the empty string.
}
else
{
// IMPORTANT: It's the empty string (a constant) or it points to memory on SimpleHeap, so don't
// change mContents/Capacity (that would cause a memory leak for reasons described elsewhere).
// Make the var empty for the following reasons:
// 1) This condition could be caused by the script requesting a very high (possibly invalid)
// capacity with VarSetCapacity(). The script might be handling the failure using TRY/CATCH,
// so we want the result to be sane.
// 2) It's safer and more maintainable. For instance, VarSetCapacity() sets length to 0, which
// can produce bad/undefined results if there is no null-terminator at mCharContents[Length()]
// as some other parts of the code assume.
// 3) It's more consistent. If this var contained a binary number or object, it has already
// been cleared by "mAttrib &=" above.
*mCharContents = '\0'; // If it's sEmptyString, that's okay too because it's writable.
}
mByteLength = 0; // mAttrib was already updated higher above.
return g_script.ScriptError(ERR_OUTOFMEM); // since an error is most likely to occur at runtime.
}
// Below is necessary because it might have fallen through from case ALLOC_SIMPLE.
// This step must be done only after the alloc succeeded (because otherwise, want to keep it
// set to ALLOC_SIMPLE (fall-through), if that's what it was).
mHowAllocated = ALLOC_MALLOC;
break;
} // switch()
// Since above didn't return, the alloc succeeded. Because that's true, all the members (except those
// set in their sections above) are updated together so that they stay consistent with each other:
mByteContents = new_mem;
mByteCapacity = (VarSizeType)new_size;
mAttrib &= ~VAR_ATTRIB_CACHE_DISABLED; // If the script previously took the address of this variable, that address is no longer valid; so there is no need to protect against the script directly accessing this variable. This is never reached for VAR_CLIPBOARD, so that isn't checked.
} // if (space_needed > mCapacity)
if (do_assign)
{
// Above has ensured that space_needed is either strlen(aBuf)-1 or the length of some
// substring within aBuf starting at aBuf. However, aBuf might overlap mContents or
// even be the same memory address (due to something like GlobalVar := YieldGlobalVar(),
// in which case ACT_ASSIGNEXPR calls us to assign GlobalVar to GlobalVar).
if (mCharContents != aBuf)
{
// Don't use strlcpy() or such because:
// 1) Caller might have specified that only part of aBuf's total length should be copied.
// 2) mContents and aBuf might overlap (see above comment), in which case strcpy()'s result
// is undefined, but memmove() is guaranteed to work (and performs about the same).
tmemmove(mCharContents, aBuf, aLength); // Some callers such as RegEx routines might rely on this copying binary zeroes over rather than stopping at the first binary zero.
}
//else nothing needs to be done since source and target are identical. Some callers probably rely on
// this optimization.
mCharContents[aLength] = '\0'; // v1.0.45: This is now done unconditionally in case caller wants to shorten a variable's existing contents (no known callers do this, but it helps robustness).
}
else // Caller only wanted the variable resized as a preparation for something it will do later.
{
// Init for greater robustness/safety (the ongoing conflict between robustness/redundancy and performance).
// This has been in effect for so long that some callers probably rely on it.
*mCharContents = '\0'; // If it's sEmptyString, that's okay too because it's writable.
// We've done everything except the actual assignment. Let the caller handle that.
// Also, the length will be set below to the expected length in case the caller
// doesn't override this.
// Below: Already verified that the length value will fit into VarSizeType.
}
// Writing to union is safe because above already ensured that "this" isn't an alias.
mByteLength = aLength * sizeof(TCHAR); // aLength was verified accurate higher above.
return OK;
}
ResultType Var::AssignSkipAddRef(IObject *aValueToAssign)
{
// Relies on the fact that aliases can't point to other aliases (enforced by UpdateAlias()).
Var &var = *(mType == VAR_ALIAS ? mAliasFor : this);
if (var.mType != VAR_NORMAL)
{
aValueToAssign->Release();
return g_script.ScriptError(ERR_INVALID_VALUE, _T("An object."));
}
var.Free(); // If var contains an object, this will Release() it. It will also clear any string contents and free memory if appropriate.
var.mObject = aValueToAssign;
// Already done by Free() above:
//mAttrib &= ~(VAR_ATTRIB_OFTEN_REMOVED | VAR_ATTRIB_UNINITIALIZED);
// Mark this variable to indicate it contains an object.
// Currently nothing should attempt to cache a number in a variable which contains an object, but it may become
// possible if a "default property" mechanism is introduced for implicitly converting an object to a string/number.
// There are at least two ways the caching mechanism could conflict with objects:
// 1) Caching a number would overwrite mObject.
// 2) Caching a number or flagging the variable as "non-numeric" would give incorrect results if the object's
// default property can implicitly change (and this change cannot be detected in order to invalidate the cache).
// Including VAR_ATTRIB_CACHE_DISABLED below should prevent caching from ever occurring for a variable containing an object.
// Including VAR_ATTRIB_NOT_NUMERIC below allows IsNonBlankIntegerOrFloat to return early if it is passed an object.
var.mAttrib |= VAR_ATTRIB_OBJECT | VAR_ATTRIB_CACHE_DISABLED | VAR_ATTRIB_NOT_NUMERIC;
return OK;
}
VarSizeType Var::Get(LPTSTR aBuf)
// Returns the length of this var's contents. In addition, if aBuf isn't NULL, it will copy the contents into aBuf.
{
// Aliases: VAR_ALIAS is checked and handled further down than in most other functions.
//
// For v1.0.25, don't do the following because in some cases the existing contents of aBuf will not
// be altered. Instead, it will be set to blank as needed further below.
//if (aBuf) *aBuf = '\0'; // Init early to get it out of the way, in case of early return.
DWORD result;
VarSizeType length;
TCHAR buf_temp[1]; // Just a fake buffer to pass to some API functions in lieu of a NULL, to avoid any chance of misbehavior. Keep the size at 1 so that API functions will always fail to copy to buf.
switch(mType)
{
case VAR_NORMAL: // Listed first for performance.
UpdateContents(); // Update mContents and mLength, if necessary.
if (!g_NoEnv && !mByteLength) // If auto-env retrieval is on and the var is empty, check to see if it's really an env. var.
{
// Regardless of whether aBuf is NULL or not, we don't know at this stage
// whether mName is the name of a valid environment variable. Therefore,
// GetEnvironmentVariable() is currently called once in the case where
// aBuf is NULL and twice in the case where it's not. There may be some
// way to reduce it to one call always, but that is an optimization for
// the future. Another reason: Calling it twice seems safer, because we can't
// be completely sure that it wouldn't act on our (possibly undersized) aBuf
// buffer even if it doesn't find the env. var.
// UPDATE: v1.0.36.02: It turns out that GetEnvironmentVariable() is a fairly
// high overhead call. To improve the speed of accessing blank variables that
// aren't environment variables (and most aren't), cached_empty_var is used
// to indicate that the previous size-estimation call to us yielded "no such
// environment variable" so that the upcoming get-contents call to us can avoid
// calling GetEnvironmentVariable() again. Testing shows that this doubles
// the speed of a simple loop that accesses an empty variable such as the following:
// SetBatchLines -1
// Loop 500000
// if Var = Test
// ...
static Var *cached_empty_var = NULL; // Doubles the speed of accessing empty variables that aren't environment variables (i.e. most of them).
if (!(cached_empty_var == this && aBuf) && (result = GetEnvironmentVariable(mName, buf_temp, 0)))
{
// This env. var exists.
cached_empty_var = NULL; // i.e. one use only to avoid cache from hiding the fact that an environment variable has newly come into existence since the previous call.
if (aBuf)
{
if (g_Warn_UseEnv)
g_script.ScriptWarning(g_Warn_UseEnv, WARNING_USE_ENV_VARIABLE, mName);
return GetEnvVarReliable(mName, aBuf); // The caller has ensured, probably via previous call to this function with aBuf == NULL, that aBuf is large enough to hold the result.
}
return result - 1; // -1 because GetEnvironmentVariable() returns total size needed when called that way.
}
else // No matching env. var. or the cache indicates that GetEnvironmentVariable() need not be called.
{
if (aBuf)
{
MaybeWarnUninitialized();
*aBuf = '\0';
cached_empty_var = NULL; // i.e. one use only to avoid cache from hiding the fact that an environment variable has newly come into existence since the previous call.
}
else // Size estimation phase: Since there is no such env. var., flag it for the upcoming get-contents phase.
cached_empty_var = this;
return 0;
}
}
length = _CharLength();
// Otherwise (since above didn't return), it's not an environment variable (or it is, but there's
// a script variable of non-zero length that's eclipsing it).
if (!aBuf)
return length;
else // Caller provider buffer, so if mLength is zero, just make aBuf empty now and return early (for performance).
if (!mByteLength)
{
MaybeWarnUninitialized();
*aBuf = '\0';
return 0;
}
//else continue on below.
if (aBuf == mCharContents)
// When we're called from ExpandArg() that was called from PerformAssign(), PerformAssign()
// relies on this check to avoid the overhead of copying a variables contents onto itself.
return length;
else if (mByteLength < 100000)
{
// Copy the var contents into aBuf. Although a little bit slower than CopyMemory() for large
// variables (say, over 100K), this loop seems much faster for small ones, which is the typical
// case. Also of note is that this code section is the main bottleneck for scripts that manipulate
// large variables, such as this:
//start_time = %A_TICKCOUNT%
//my = 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
//tempvar =
//loop, 2000
// tempvar = %tempvar%%My%
//elapsed_time = %A_TICKCOUNT%
//elapsed_time -= %start_time%
//msgbox, elapsed_time = %elapsed_time%
//return
for (LPTSTR cp = mCharContents; *cp; *aBuf++ = *cp++); // UpdateContents() was already called higher above to update mContents.
*aBuf = '\0';
}
else
{
CopyMemory(aBuf, mByteContents, mByteLength); // Faster for large vars, but large vars aren't typical.
aBuf[length] = '\0'; // This is done as a step separate from above in case mLength is inaccurate (e.g. due to script's improper use of DllCall).
}
return length;
case VAR_ALIAS:
// For maintainability, it seems best not to use the following method:
// Var &var = *(mType == VAR_ALIAS ? mAliasFor : this);
// If that were done, bugs would be easy to introduce in a long function like this one
// if your forget at use the implicit "this" by accident. So instead, just call self.
return mAliasFor->Get(aBuf);
// Built-in vars with volatile contents:
case VAR_CLIPBOARD:
{
length = (VarSizeType)g_clip.Get(aBuf); // It will also copy into aBuf if it's non-NULL.
if (length == CLIPBOARD_FAILURE)
{
// Above already displayed the error, so just return.
// If we were called only to determine the size, the
// next call to g_clip.Get() will not put anything into
// aBuf (it will either fail again, or it will return
// a length of zero due to the clipboard not already
// being open & ready), so there's no danger of future
// buffer overflows as a result of returning zero here.
// Also, due to this function's return type, there's
// no easy way to terminate the current hotkey
// subroutine (or entire script) due to this error.
// However, due to the fact that multiple attempts
// are made to open the clipboard, failure should
// be extremely rare. And the user will be notified
// with a MsgBox anyway, during which the subroutine
// will be suspended:
length = 0;
}
if (aBuf)
aBuf[length] = '\0'; // Might not be necessary, but kept in case it ever is.
return length;
}
case VAR_CLIPBOARDALL: // There's a slight chance this case is never executed; but even if true, it should be kept for maintainability.
// This variable is directly handled at a higher level. As documented, any use of ClipboardAll outside of
// the supported modes yields an empty string.
if (aBuf)
*aBuf = '\0';
return 0;
default: // v1.0.46.16: VAR_BUILTIN: Call the function associated with this variable to retrieve its contents. This change reduced uncompressed coded size by 6 KB.
return mBIV(aBuf, mName);
} // switch(mType)
}
void Var::Free(int aWhenToFree, bool aExcludeAliasesAndRequireInit)
// The name "Free" is a little misleading because this function:
// ALWAYS sets the variable to be blank (except for static variables and aExcludeAliases==true).
// BUT ONLY SOMETIMES frees the memory, depending on various factors described further below.
// Caller must be aware that ALLOC_SIMPLE (due to its nature) is never freed.
// aExcludeAliasesAndRequireInit may be split into two if any caller ever wants to pass
// true for one and not the other (currently there is only one caller who passes true).
{
// Not checked because even if it's not VAR_NORMAL, there are few if any consequences to continuing.
//if (mType != VAR_NORMAL) // For robustness, since callers generally shouldn't call it this way.
// return;
if (mType == VAR_ALIAS) // For simplicity and reduced code size, just make a recursive call to self.
{
if (!aExcludeAliasesAndRequireInit)
// For maintainability, it seems best not to use the following method:
// Var &var = *(mType == VAR_ALIAS ? mAliasFor : this);
// If that were done, bugs would be easy to introduce in a long function like this one
// if your forget at use the implicit "this" by accident. So instead, just call self.
mAliasFor->Free(aWhenToFree);
//else caller didn't want the target of the alias freed, so do nothing.
return;
}
// Must check this one first because caller relies not only on var not being freed in this case,
// but also on its contents not being set to an empty string:
// HotKeyIt changed because static vars are saved in separate list
//if (aWhenToFree == VAR_ALWAYS_FREE_BUT_EXCLUDE_STATIC && IsStatic())
// return; // This is the only case in which the variable ISN'T made blank.
if (IsObject()) // L31: Release this variable's reference to its object.
|
tinku99/ahkdll
|
e1d311283c34bd85a2c61056451154d13b77ee4e
|
modified: source/script2.cpp
|
diff --git a/source/script2.cpp b/source/script2.cpp
index ad444f1..602d20c 100644
--- a/source/script2.cpp
+++ b/source/script2.cpp
@@ -10925,1035 +10925,1047 @@ ResultType Line::SetToggleState(vk_type aVK, ToggleValueType &ForceLock, LPTSTR
// Misc lower level functions //
////////////////////////////////
HWND Line::DetermineTargetWindow(LPTSTR aTitle, LPTSTR aText, LPTSTR aExcludeTitle, LPTSTR aExcludeText)
{
HWND target_window; // A variable of this name is used by the macros below.
IF_USE_FOREGROUND_WINDOW(g->DetectHiddenWindows, aTitle, aText, aExcludeTitle, aExcludeText)
else if (*aTitle || *aText || *aExcludeTitle || *aExcludeText)
target_window = WinExist(*g, aTitle, aText, aExcludeTitle, aExcludeText);
else // Use the "last found" window.
target_window = GetValidLastUsedWindow(*g);
return target_window;
}
bool Line::FileIsFilteredOut(WIN32_FIND_DATA &aCurrentFile, FileLoopModeType aFileLoopMode
, LPTSTR aFilePath, size_t aFilePathLength)
// Caller has ensured that aFilePath (if non-blank) has a trailing backslash.
{
if (aCurrentFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // It's a folder.
{
if (aFileLoopMode == FILE_LOOP_FILES_ONLY
|| aCurrentFile.cFileName[0] == '.' && (!aCurrentFile.cFileName[1] // Relies on short-circuit boolean order.
|| aCurrentFile.cFileName[1] == '.' && !aCurrentFile.cFileName[2])) //
return true; // Exclude this folder by returning true.
}
else // it's not a folder.
if (aFileLoopMode == FILE_LOOP_FOLDERS_ONLY)
return true; // Exclude this file by returning true.
// Since file was found, also prepend the file's path to its name for the caller:
if (*aFilePath)
{
// Seems best to check length in advance because it allows a faster move/copy method further below
// (in lieu of sntprintf(), which is probably quite a bit slower than the method here).
size_t name_length = _tcslen(aCurrentFile.cFileName);
if (aFilePathLength + name_length >= MAX_PATH)
// v1.0.45.03: Filter out filenames that would be truncated because it seems undesirable in 99% of
// cases to include such "faulty" data in the loop. Most scripts would want to skip them rather than
// seeing the truncated names. Furthermore, a truncated name might accidentally match the name
// of a legitimate non-truncated filename, which could cause such a name to get retrieved twice by
// the loop (or other undesirable side-effects).
return true;
//else no overflow is possible, so below can move things around inside the buffer without concern.
tmemmove(aCurrentFile.cFileName + aFilePathLength, aCurrentFile.cFileName, name_length + 1); // memmove() because source & dest might overlap. +1 to include the terminator.
tmemcpy(aCurrentFile.cFileName, aFilePath, aFilePathLength); // Prepend in the area liberated by the above. Don't include the terminator since this is a concat operation.
}
return false; // Indicate that this file is not to be filtered out.
}
Label *Line::GetJumpTarget(bool aIsDereferenced)
{
LPTSTR target_label = aIsDereferenced ? ARG1 : RAW_ARG1;
Label *label = g_script.FindLabel(target_label);
if (!label)
{
LineError(ERR_NO_LABEL, FAIL, target_label);
return NULL;
}
if (!aIsDereferenced)
mRelatedLine = (Line *)label; // The script loader has ensured that label->mJumpToLine isn't NULL.
// else don't update it, because that would permanently resolve the jump target, and we want it to stay dynamic.
// Seems best to do this even for GOSUBs even though it's a bit weird:
return IsJumpValid(*label);
// Any error msg was already displayed by the above call.
}
Label *Line::IsJumpValid(Label &aTargetLabel, bool aSilent)
// Returns aTargetLabel is the jump is valid, or NULL otherwise.
{
// aTargetLabel can be NULL if this Goto's target is the physical end of the script.
// And such a destination is always valid, regardless of where aOrigin is.
// UPDATE: It's no longer possible for the destination of a Goto or Gosub to be
// NULL because the script loader has ensured that the end of the script always has
// an extra ACT_EXIT that serves as an anchor for any final labels in the script:
//if (aTargetLabel == NULL)
// return OK;
// The above check is also necessary to avoid dereferencing a NULL pointer below.
Line *parent_line_of_label_line;
if ( !(parent_line_of_label_line = aTargetLabel.mJumpToLine->mParentLine) )
// A Goto/Gosub can always jump to a point anywhere in the outermost layer
// (i.e. outside all blocks) without restriction:
return &aTargetLabel; // Indicate success.
// So now we know this Goto/Gosub is attempting to jump into a block somewhere. Is that
// block a legal place to jump?:
for (Line *ancestor = mParentLine; ancestor != NULL; ancestor = ancestor->mParentLine)
if (parent_line_of_label_line == ancestor)
// Since aTargetLabel is in the same block as the Goto line itself (or a block
// that encloses that block), it's allowed:
return &aTargetLabel; // Indicate success.
// This can happen if the Goto's target is at a deeper level than it, or if the target
// is at a more shallow level but is in some block totally unrelated to it!
// Returns FAIL by default, which is what we want because that value is zero:
if (!aSilent)
LineError(_T("A Goto/Gosub must not jump into a block that doesn't enclose it.")); // Omit GroupActivate from the error msg since that is rare enough to justify the increase in common-case clarity.
return NULL;
}
BOOL Line::IsOutsideAnyFunctionBody() // v1.0.48.02
{
for (Line *ancestor = mParentLine; ancestor != NULL; ancestor = ancestor->mParentLine)
if (ancestor->mAttribute == ATTR_TRUE && ancestor->mActionType == ACT_BLOCK_BEGIN) // Ordered for short-circuit performance.
return FALSE; // ATTR_TRUE marks an open-brace as belonging to a function's body, so indicate this this line is inside a function.
return TRUE; // Indicate that this line is not inside any function body.
}
BOOL Line::CheckValidFinallyJump(Line* jumpTarget) // v1.1.14
{
Line* jumpParent = jumpTarget->mParentLine;
for (Line *ancestor = mParentLine; ancestor != NULL; ancestor = ancestor->mParentLine)
{
if (ancestor == jumpParent)
return TRUE; // We found the common ancestor.
if (ancestor->mActionType == ACT_FINALLY)
{
LineError(ERR_BAD_JUMP_INSIDE_FINALLY);
return FALSE; // The common ancestor is outside the FINALLY block and thus this jump is invalid.
}
}
return TRUE; // The common ancestor is the root of the script.
}
////////////////////////
// BUILT-IN VARIABLES //
////////////////////////
VarSizeType BIV_True_False_Null(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
*aBuf++ = (aVarName[2] == 'l' || aVarName[2] == 'L') ? '0': '1';
*aBuf = '\0';
}
return 1; // The length of the value.
}
VarSizeType BIV_MMM_DDD(LPTSTR aBuf, LPTSTR aVarName)
{
LPTSTR format_str;
switch(ctoupper(aVarName[2]))
{
// Use the case-sensitive formats required by GetDateFormat():
case 'M': format_str = (aVarName[5] ? _T("MMMM") : _T("MMM")); break;
case 'D': format_str = (aVarName[5] ? _T("dddd") : _T("ddd")); break;
}
// Confirmed: The below will automatically use the local time (not UTC) when 3rd param is NULL.
return (VarSizeType)(GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, format_str, aBuf, aBuf ? 999 : 0) - 1);
}
VarSizeType BIV_DateTime(LPTSTR aBuf, LPTSTR aVarName)
{
if (!aBuf)
return 6; // Since only an estimate is needed in this mode, return the maximum length of any item.
aVarName += 2; // Skip past the "A_".
// The current time is refreshed only if it's been a certain number of milliseconds since
// the last fetch of one of these built-in time variables. This keeps the variables in
// sync with one another when they are used consecutively such as this example:
// Var = %A_Hour%:%A_Min%:%A_Sec%
// Using GetTickCount() because it's very low overhead compared to the other time functions:
static DWORD sLastUpdate = 0; // Static should be thread + recursion safe in this case.
static SYSTEMTIME sST = {0}; // Init to detect when it's empty.
BOOL is_msec = !_tcsicmp(aVarName, _T("MSec")); // Always refresh if it's milliseconds, for better accuracy.
DWORD now_tick = GetTickCount();
if (is_msec || now_tick - sLastUpdate > 50 || !sST.wYear) // See comments above.
{
GetLocalTime(&sST);
sLastUpdate = now_tick;
}
if (is_msec)
return _stprintf(aBuf, _T("%03d"), sST.wMilliseconds);
TCHAR second_letter = ctoupper(aVarName[1]);
switch(ctoupper(aVarName[0]))
{
case 'Y':
switch(second_letter)
{
case 'D': // A_YDay
return _stprintf(aBuf, _T("%d"), GetYDay(sST.wMonth, sST.wDay, IS_LEAP_YEAR(sST.wYear)));
case 'W': // A_YWeek
return GetISOWeekNumber(aBuf, sST.wYear
, GetYDay(sST.wMonth, sST.wDay, IS_LEAP_YEAR(sST.wYear))
, sST.wDayOfWeek);
default: // A_Year/A_YYYY
return _stprintf(aBuf, _T("%d"), sST.wYear);
}
// No break because all cases above return:
//break;
case 'M':
switch(second_letter)
{
case 'D': // A_MDay (synonymous with A_DD)
return _stprintf(aBuf, _T("%02d"), sST.wDay);
case 'I': // A_Min
return _stprintf(aBuf, _T("%02d"), sST.wMinute);
default: // A_MM and A_Mon (A_MSec was already completely handled higher above).
return _stprintf(aBuf, _T("%02d"), sST.wMonth);
}
// No break because all cases above return:
//break;
case 'D': // A_DD (synonymous with A_MDay)
return _stprintf(aBuf, _T("%02d"), sST.wDay);
case 'W': // A_WDay
return _stprintf(aBuf, _T("%d"), sST.wDayOfWeek + 1);
case 'H': // A_Hour
return _stprintf(aBuf, _T("%02d"), sST.wHour);
case 'S': // A_Sec (A_MSec was already completely handled higher above).
return _stprintf(aBuf, _T("%02d"), sST.wSecond);
}
return 0; // Never reached, but avoids compiler warning.
}
VarSizeType BIV_BatchLines(LPTSTR aBuf, LPTSTR aVarName)
{
// The BatchLine value can be either a numerical string or a string that ends in "ms".
TCHAR buf[256];
LPTSTR target_buf = aBuf ? aBuf : buf;
if (g->IntervalBeforeRest > -1) // Have this new method take precedence, if it's in use by the script.
return _stprintf(target_buf, _T("%dms"), g->IntervalBeforeRest); // Not sntprintf().
// Otherwise:
ITOA64(g->LinesPerCycle, target_buf);
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_TitleMatchMode(LPTSTR aBuf, LPTSTR aVarName)
{
if (g->TitleMatchMode == FIND_REGEX) // v1.0.45.
{
if (aBuf) // For backward compatibility (due to StringCaseSense), never change the case used here:
_tcscpy(aBuf, _T("RegEx"));
return 5; // The length.
}
// Otherwise, it's a numerical mode:
// It's done this way in case it's ever allowed to go beyond a single-digit number.
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
_itot(g->TitleMatchMode, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence).
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_TitleMatchModeSpeed(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf) // For backward compatibility (due to StringCaseSense), never change the case used here:
_tcscpy(aBuf, g->TitleFindFast ? _T("Fast") : _T("Slow"));
return 4; // Always length 4
}
VarSizeType BIV_DetectHiddenWindows(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(_tcscpy(aBuf, g->DetectHiddenWindows ? _T("On") : _T("Off"))) // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required).
: 3; // Room for either On or Off (in the estimation phase).
}
VarSizeType BIV_DetectHiddenText(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(_tcscpy(aBuf, g->DetectHiddenText ? _T("On") : _T("Off"))) // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required).
: 3; // Room for either On or Off (in the estimation phase).
}
VarSizeType BIV_AutoTrim(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(_tcscpy(aBuf, g->AutoTrim ? _T("On") : _T("Off"))) // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required).
: 3; // Room for either On or Off (in the estimation phase).
}
VarSizeType BIV_StringCaseSense(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(_tcscpy(aBuf, g->StringCaseSense == SCS_INSENSITIVE ? _T("Off") // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required).
: (g->StringCaseSense == SCS_SENSITIVE ? _T("On") : _T("Locale"))))
: 6; // Room for On, Off, or Locale (in the estimation phase).
}
VarSizeType BIV_FormatInteger(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
*aBuf++ = g->FormatInt;
*aBuf = '\0';
}
return 1;
}
VarSizeType BIV_FormatFloat(LPTSTR aBuf, LPTSTR aVarName)
{
if (!aBuf)
return (VarSizeType)_tcslen(g->FormatFloat); // Include the extra chars since this is just an estimate.
LPTSTR str_with_leading_percent_omitted = g->FormatFloat + 1;
size_t length = _tcslen(str_with_leading_percent_omitted);
tcslcpy(aBuf, str_with_leading_percent_omitted
, length + !(length && str_with_leading_percent_omitted[length-1] == 'f')); // Omit the trailing character only if it's an 'f', not any other letter such as the 'e' in "%0.6e" (for backward compatibility).
return (VarSizeType)_tcslen(aBuf); // Must return exact length when aBuf isn't NULL.
}
VarSizeType BIV_KeyDelay(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
_itot(g->KeyDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence).
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_WinDelay(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
_itot(g->WinDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence).
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_ControlDelay(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
_itot(g->ControlDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence).
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_MouseDelay(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
_itot(g->MouseDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence).
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_DefaultMouseSpeed(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
_itot(g->DefaultMouseSpeed, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence).
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_IsPaused(LPTSTR aBuf, LPTSTR aVarName) // v1.0.48: Lexikos: Added BIV_IsPaused and BIV_IsCritical.
{
// Although A_IsPaused could indicate how many threads are paused beneath the current thread,
// that would be a problem because it would yield a non-zero value even when the underlying thread
// isn't paused (i.e. other threads below it are paused), which would defeat the original purpose.
// In addition, A_IsPaused probably won't be commonly used, so it seems best to keep it simple.
// NAMING: A_IsPaused seems to be a better name than A_Pause or A_Paused due to:
// Better readability.
// Consistent with A_IsSuspended, which is strongly related to pause/unpause.
// The fact that it wouldn't be likely for a function to turn off pause then turn it back on
// (or vice versa), which was the main reason for storing "Off" and "On" in things like
// A_DetectHiddenWindows.
if (aBuf)
{
// Checking g>g_array avoids any chance of underflow, which might otherwise happen if this is
// called by the AutoExec section or a threadless callback running in thread #0.
*aBuf++ = (g > g_array && g[-1].IsPaused) ? '1' : '0';
*aBuf = '\0';
}
return 1;
}
VarSizeType BIV_IsCritical(LPTSTR aBuf, LPTSTR aVarName) // v1.0.48: Lexikos: Added BIV_IsPaused and BIV_IsCritical.
{
if (!aBuf) // Return conservative estimate in case Critical status can ever change between the 1st and 2nd calls to this function.
return MAX_INTEGER_LENGTH;
// It seems more useful to return g->PeekFrequency than "On" or "Off" (ACT_CRITICAL ensures that
// g->PeekFrequency!=0 whenever g->ThreadIsCritical==true). Also, the word "Is" in "A_IsCritical"
// implies a value that can be used as a boolean such as "if A_IsCritical".
if (g->ThreadIsCritical)
return (VarSizeType)_tcslen(UTOA(g->PeekFrequency, aBuf)); // ACT_CRITICAL ensures that g->PeekFrequency > 0 when critical is on.
// Otherwise:
*aBuf++ = '0';
*aBuf = '\0';
return 1; // Caller might rely on receiving actual length when aBuf!=NULL.
}
#ifndef MINIDLL
VarSizeType BIV_IsSuspended(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
*aBuf++ = g_IsSuspended ? '1' : '0';
*aBuf = '\0';
}
return 1;
}
#endif
#ifdef AUTOHOTKEYSC // A_IsCompiled is left blank/undefined in uncompiled scripts.
VarSizeType BIV_IsCompiled(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
*aBuf++ = '1';
*aBuf = '\0';
}
return 1;
}
#else
VarSizeType BIV_IsCompiled(LPTSTR aBuf, LPTSTR aVarName)
{
if (!g_hResource)
{
if (aBuf)
*aBuf = '\0';
return 1;
}
else if (aBuf)
{
*aBuf++ = '1';
*aBuf = '\0';
}
return 1;
}
#endif
VarSizeType BIV_IsUnicode(LPTSTR aBuf, LPTSTR aVarName)
{
#ifdef UNICODE
if (aBuf)
{
*aBuf++ = '1';
*aBuf = '\0';
}
return 1;
#else
// v1.1.06: A_IsUnicode is defined so that it does not cause warnings with #Warn enabled,
// but left empty to encourage compatibility with older versions and AutoHotkey Basic.
// This prevents scripts from using expressions like A_IsUnicode+1, which would succeed
// if A_IsUnicode is 0 or 1 but fail if it is "". This change has side-effects similar
// to those described for A_IsCompiled above.
if (aBuf)
*aBuf = '\0';
return 0;
#endif
}
VarSizeType BIV_FileEncoding(LPTSTR aBuf, LPTSTR aVarName)
{
// A similar section may be found under "case Encoding:" in FileObject::Invoke. Maintain that with this:
switch (g->Encoding)
{
case CP_ACP:
if (aBuf)
*aBuf = '\0';
return 0;
#define FILEENCODING_CASE(n, s) \
case n: \
if (aBuf) \
_tcscpy(aBuf, _T(s)); \
return _countof(_T(s)) - 1;
// Returning readable strings for these seems more useful than returning their numeric values, especially with CP_AHKNOBOM:
FILEENCODING_CASE(CP_UTF8, "UTF-8")
FILEENCODING_CASE(CP_UTF8 | CP_AHKNOBOM, "UTF-8-RAW")
FILEENCODING_CASE(CP_UTF16, "UTF-16")
FILEENCODING_CASE(CP_UTF16 | CP_AHKNOBOM, "UTF-16-RAW")
#undef FILEENCODING_CASE
default:
{
TCHAR buf[MAX_INTEGER_SIZE + 2]; // + 2 for "CP"
LPTSTR target_buf = aBuf ? aBuf : buf;
target_buf[0] = _T('C');
target_buf[1] = _T('P');
_itot(g->Encoding, target_buf + 2, 10); // Always output as decimal since we aren't exactly returning a number.
return (VarSizeType)_tcslen(target_buf);
}
}
}
VarSizeType BIV_RegView(LPTSTR aBuf, LPTSTR aVarName)
{
LPCTSTR value;
switch (g->RegView)
{
case KEY_WOW64_32KEY: value = _T("32"); break;
case KEY_WOW64_64KEY: value = _T("64"); break;
default: value = _T("Default"); break;
}
if (aBuf)
_tcscpy(aBuf, value);
return (VarSizeType)_tcslen(value);
}
VarSizeType BIV_LastError(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
_itot(g->LastError, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence).
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_GlobalStruct(LPTSTR aBuf, LPTSTR aVarName)
{
+ LPTSTR str = _T(""); // sandbox
+ if (aBuf)
+ _tcscpy(aBuf, str);
+ return (VarSizeType)_tcslen(str);
+ /*
return aBuf
? (VarSizeType)_tcslen(ITOA64((LONGLONG)g, aBuf))
: MAX_INTEGER_LENGTH;
+ */
}
VarSizeType BIV_ScriptStruct(LPTSTR aBuf, LPTSTR aVarName)
{
+ LPTSTR str = _T(""); // sandbox
+ if (aBuf)
+ _tcscpy(aBuf, str);
+ return (VarSizeType)_tcslen(str);
+ /*
return aBuf
? (VarSizeType)_tcslen(ITOA64((LONGLONG)&g_script, aBuf))
: MAX_INTEGER_LENGTH;
+ */
}
VarSizeType BIV_ModuleHandle(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(ITOA64((LONGLONG)g_hInstance, aBuf))
: MAX_INTEGER_LENGTH;
}
VarSizeType BIV_MemoryModule(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(ITOA64((LONGLONG)g_hMemoryModule, aBuf))
: MAX_INTEGER_LENGTH;
}
VarSizeType BIV_IsDll(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
*aBuf++ = (g_hInstance == GetModuleHandle(NULL)) ? '0' : '1';
*aBuf = '\0';
}
return 1;
}
VarSizeType BIV_IsMini(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
#ifdef MINIDLL
*aBuf++ = '1';
#else
*aBuf++ = '0';
#endif
*aBuf = '\0';
}
return 1;
}
VarSizeType BIV_CoordMode(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(ITOA64(((g->CoordMode >> Line::ConvertCoordModeCmd(aVarName + 11)) & COORD_MODE_MASK), aBuf))
: MAX_INTEGER_LENGTH;
}
VarSizeType BIV_PtrSize(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
// Return size in bytes of a pointer in the current build.
*aBuf++ = '0' + sizeof(void *);
*aBuf = '\0';
}
return 1;
}
#ifndef MINIDLL
VarSizeType BIV_ScreenDPI(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
_itot(g_ScreenDPI, aBuf, 10);
return aBuf ? (VarSizeType)_tcslen(aBuf) : MAX_INTEGER_SIZE;
}
VarSizeType BIV_IconHidden(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
*aBuf++ = g_NoTrayIcon ? '1' : '0';
*aBuf = '\0';
}
return 1; // Length is always 1.
}
VarSizeType BIV_IconTip(LPTSTR aBuf, LPTSTR aVarName)
{
if (!aBuf)
return g_script.mTrayIconTip ? (VarSizeType)_tcslen(g_script.mTrayIconTip) : 0;
if (g_script.mTrayIconTip)
return (VarSizeType)_tcslen(_tcscpy(aBuf, g_script.mTrayIconTip));
else
{
*aBuf = '\0';
return 0;
}
}
VarSizeType BIV_IconFile(LPTSTR aBuf, LPTSTR aVarName)
{
if (!aBuf)
return g_script.mCustomIconFile ? (VarSizeType)_tcslen(g_script.mCustomIconFile) : 0;
if (g_script.mCustomIconFile)
return (VarSizeType)_tcslen(_tcscpy(aBuf, g_script.mCustomIconFile));
else
{
*aBuf = '\0';
return 0;
}
}
VarSizeType BIV_IconNumber(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
if (!g_script.mCustomIconNumber) // Yield an empty string rather than the digit "0".
{
*target_buf = '\0';
return 0;
}
return (VarSizeType)_tcslen(UTOA(g_script.mCustomIconNumber, target_buf));
}
VarSizeType BIV_PriorKey(LPTSTR aBuf, LPTSTR aVarName)
{
const int bufSize = 32;
if (!aBuf)
return bufSize;
*aBuf = '\0'; // Init for error & not-found cases
int validEventCount = 0;
// Start at the current event (offset 1)
for (int iOffset = 1; iOffset <= g_MaxHistoryKeys; ++iOffset)
{
// Get index for circular buffer
int i = (g_KeyHistoryNext + g_MaxHistoryKeys - iOffset) % g_MaxHistoryKeys;
// Keep looking until we hit the second valid event
if (g_KeyHistory[i].event_type != _T('i') && ++validEventCount > 1)
{
// Find the next most recent key-down
if (!g_KeyHistory[i].key_up)
{
GetKeyName(g_KeyHistory[i].vk, g_KeyHistory[i].sc, aBuf, bufSize);
break;
}
}
}
return (VarSizeType)_tcslen(aBuf);
}
#endif
VarSizeType BIV_ExitReason(LPTSTR aBuf, LPTSTR aVarName)
{
LPTSTR str;
switch(g_script.mExitReason)
{
case EXIT_LOGOFF: str = _T("Logoff"); break;
case EXIT_SHUTDOWN: str = _T("Shutdown"); break;
// Since the below are all relatively rare, except WM_CLOSE perhaps, they are all included
// as one word to cut down on the number of possible words (it's easier to write OnExit
// routines to cover all possibilities if there are fewer of them).
case EXIT_WM_QUIT:
case EXIT_CRITICAL:
case EXIT_DESTROY:
case EXIT_WM_CLOSE: str = _T("Close"); break;
case EXIT_ERROR: str = _T("Error"); break;
case EXIT_MENU: str = _T("Menu"); break; // Standard menu, not a user-defined menu.
case EXIT_EXIT: str = _T("Exit"); break; // ExitApp or Exit command.
case EXIT_RELOAD: str = _T("Reload"); break;
case EXIT_SINGLEINSTANCE: str = _T("Single"); break;
default: // EXIT_NONE or unknown value (unknown would be considered a bug if it ever happened).
str = _T("");
}
if (aBuf)
_tcscpy(aBuf, str);
return (VarSizeType)_tcslen(str);
}
VarSizeType BIV_Space_Tab(LPTSTR aBuf, LPTSTR aVarName)
{
// Really old comment:
// A_Space is a built-in variable rather than using an escape sequence such as `s, because the escape
// sequence method doesn't work (probably because `s resolves to a space and is trimmed at some point
// prior to when it can be used):
if (aBuf)
{
*aBuf++ = aVarName[5] ? ' ' : '\t'; // A_Tab[]
*aBuf = '\0';
}
return 1;
}
VarSizeType BIV_AhkVersion(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
_tcscpy(aBuf, T_AHK_VERSION);
return (VarSizeType)_tcslen(T_AHK_VERSION);
}
VarSizeType BIV_AhkPath(LPTSTR aBuf, LPTSTR aVarName) // v1.0.41.
{
#ifdef AUTOHOTKEYSC
if (aBuf)
{
size_t length;
if (length = GetAHKInstallDir(aBuf))
// Name "AutoHotkey.exe" is assumed for code size reduction and because it's not stored in the registry:
tcslcpy(aBuf + length, _T("\\AutoHotkey.exe"), MAX_PATH - length); // strlcpy() in case registry has a path that is too close to MAX_PATH to fit AutoHotkey.exe
//else leave it blank as documented.
return (VarSizeType)_tcslen(aBuf);
}
// Otherwise: Always return an estimate of MAX_PATH in case the registry entry changes between the
// first call and the second. This is also relied upon by strlcpy() above, which zero-fills the tail
// of the destination up through the limit of its capacity (due to calling strncpy, which does this).
return MAX_PATH;
#else
TCHAR buf[MAX_PATH];
VarSizeType length = (VarSizeType)GetModuleFileName(NULL, buf, MAX_PATH);
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like this one.
return length;
#endif
}
VarSizeType BIV_AhkDir(LPTSTR aBuf, LPTSTR aVarName) // v1.0.41.
{
#ifdef AUTOHOTKEYSC
if (aBuf)
{
GetAHKInstallDir(aBuf);
return (VarSizeType)_tcslen(aBuf);
}
// Otherwise: Always return an estimate of MAX_PATH in case the registry entry changes between the
// first call and the second. This is also relied upon by strlcpy() above, which zero-fills the tail
// of the destination up through the limit of its capacity (due to calling strncpy, which does this).
return MAX_PATH;
#else
TCHAR buf[MAX_PATH];
GetModuleFileName(NULL, buf, MAX_PATH);
VarSizeType length = (_tcsrchr(buf, L'\\') - buf);
if (aBuf)
{
_tcsncpy(aBuf, buf, length); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like this one.
*(aBuf + length) = L'\0';
}
return length;
#endif
}
VarSizeType BIV_DllPath(LPTSTR aBuf, LPTSTR aVarName) // HotKeyIt H1 path of loaded dll
{
TCHAR buf[MAX_PATH];
VarSizeType length = (VarSizeType)GetModuleFileName(g_hInstance, buf, _countof(buf));
if (length == 0)
VarSizeType length = (VarSizeType)GetModuleFileName(NULL, buf, _countof(buf));
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like this one.
return length;
}
VarSizeType BIV_DllDir(LPTSTR aBuf, LPTSTR aVarName) // HotKeyIt H1 path of loaded dll
{
TCHAR buf[MAX_PATH];
VarSizeType length = (VarSizeType)GetModuleFileName(g_hInstance, buf, _countof(buf));
if (length == 0)
GetModuleFileName(NULL, buf, _countof(buf));
length = _tcsrchr(buf, L'\\') - buf;
if (aBuf)
{
_tcsncpy(aBuf, buf, length); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like this one.
*(aBuf + length) = '\0';
}
return length;
}
VarSizeType BIV_TickCount(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(ITOA64(GetTickCount(), aBuf))
: MAX_INTEGER_LENGTH; // IMPORTANT: Conservative estimate because tick might change between 1st & 2nd calls.
}
VarSizeType BIV_Now(LPTSTR aBuf, LPTSTR aVarName)
{
if (!aBuf)
return DATE_FORMAT_LENGTH;
SYSTEMTIME st;
if (aVarName[5]) // A_Now[U]TC
GetSystemTime(&st);
else
GetLocalTime(&st);
SystemTimeToYYYYMMDD(aBuf, st);
return (VarSizeType)_tcslen(aBuf);
}
VarSizeType BIV_OSType(LPTSTR aBuf, LPTSTR aVarName)
{
LPTSTR type = g_os.IsWinNT() ? _T("WIN32_NT") : _T("WIN32_WINDOWS");
if (aBuf)
_tcscpy(aBuf, type);
return (VarSizeType)_tcslen(type); // Return length of type, not aBuf.
}
VarSizeType BIV_OSVersion(LPTSTR aBuf, LPTSTR aVarName)
{
LPCTSTR version = _T(""); // Init for maintainability.
if (g_os.IsWinNT()) // "NT" includes all NT-kernel OSes: NT4/2000/XP/2003/Vista/7/8/etc.
{
if (g_os.IsWinXP())
version = _T("WIN_XP");
else if (g_os.IsWin7())
version = _T("WIN_7");
else if (g_os.IsWin8_1())
version = _T("WIN_8.1");
else if (g_os.IsWin8())
version = _T("WIN_8");
else if (g_os.IsWinVista())
version = _T("WIN_VISTA");
else if (g_os.IsWin2003())
version = _T("WIN_2003");
else
{
if (g_os.IsWin2000())
version = _T("WIN_2000");
else if (g_os.IsWinNT4())
version = _T("WIN_NT4");
}
}
else
{
if (g_os.IsWin95())
version = _T("WIN_95");
else
{
if (g_os.IsWin98())
version = _T("WIN_98");
else
version = _T("WIN_ME");
}
}
if (aBuf)
_tcscpy(aBuf, version);
return (VarSizeType)_tcslen(version); // Always return the length of version, not aBuf.
}
VarSizeType BIV_Is64bitOS(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
*aBuf++ = IsOS64Bit() ? '1' : '0';
*aBuf = '\0';
}
return 1;
}
VarSizeType BIV_Language(LPTSTR aBuf, LPTSTR aVarName)
// Registry locations from J-Paul Mesnage.
{
TCHAR buf[MAX_PATH];
VarSizeType length;
if (g_os.IsWinNT()) // NT/2k/XP+
length = g_os.IsWin2000orLater()
? ReadRegString(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\Nls\\Language"), _T("InstallLanguage"), buf, MAX_PATH)
: ReadRegString(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\Nls\\Language"), _T("Default"), buf, MAX_PATH); // NT4
else // Win9x
{
length = ReadRegString(HKEY_USERS, _T(".DEFAULT\\Control Panel\\Desktop\\ResourceLocale"), _T(""), buf, MAX_PATH);
if (length > 3)
{
length -= 4;
memmove(buf, buf + 4, length + 1); // +1 to include the zero terminator.
}
}
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string).
return length;
}
VarSizeType BIV_UserName_ComputerName(LPTSTR aBuf, LPTSTR aVarName)
{
*aBuf = '\0'; // sandbox
return 0;
TCHAR buf[MAX_PATH]; // Doesn't use MAX_COMPUTERNAME_LENGTH + 1 in case longer names are allowed in the future.
DWORD buf_size = MAX_PATH; // Below: A_Computer[N]ame (N is the 11th char, index 10, which if present at all distinguishes between the two).
if ( !(aVarName[10] ? GetComputerName(buf, &buf_size) : GetUserName(buf, &buf_size)) )
*buf = '\0';
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the ones here.
return (VarSizeType)_tcslen(buf); // I seem to remember that the lengths returned from the above API calls aren't consistent in these cases.
}
VarSizeType BIV_WorkingDir(LPTSTR aBuf, LPTSTR aVarName)
{
// Use GetCurrentDirectory() vs. g_WorkingDir because any in-progress FileSelectFile()
// dialog is able to keep functioning even when it's quasi-thread is suspended. The
// dialog can thus change the current directory as seen by the active quasi-thread even
// though g_WorkingDir hasn't been updated. It might also be possible for the working
// directory to change in unusual circumstances such as a network drive being lost).
//
// Fix for v1.0.43.11: Changed size below from 9999 to MAX_PATH, otherwise it fails sometimes on Win9x.
// Testing shows that the failure is not caused by GetCurrentDirectory() writing to the unused part of the
// buffer, such as zeroing it (which is good because that would require this part to be redesigned to pass
// the actual buffer size or use a temp buffer). So there's something else going on to explain why the
// problem only occurs in longer scripts on Win98se, not in trivial ones such as Var=%A_WorkingDir%.
// Nor did the problem affect expression assignments such as Var:=A_WorkingDir.
TCHAR buf[MAX_PATH];
VarSizeType length = GetCurrentDirectory(MAX_PATH, buf);
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here.
return length;
// Formerly the following, but I don't think it's as reliable/future-proof given the 1.0.47 comment above:
//return aBuf
// ? GetCurrentDirectory(MAX_PATH, aBuf)
// : GetCurrentDirectory(0, NULL); // MSDN says that this is a valid way to call it on all OSes, and testing shows that it works on WinXP and 98se.
// Above avoids subtracting 1 to be conservative and to reduce code size (due to the need to otherwise check for zero and avoid subtracting 1 in that case).
}
VarSizeType BIV_WinDir(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_PATH];
VarSizeType length = GetWindowsDirectory(buf, MAX_PATH);
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here.
return length;
// Formerly the following, but I don't think it's as reliable/future-proof given the 1.0.47 comment above:
//TCHAR buf_temp[1]; // Just a fake buffer to pass to some API functions in lieu of a NULL, to avoid any chance of misbehavior. Keep the size at 1 so that API functions will always fail to copy to buf.
//// Sizes/lengths/-1/return-values/etc. have been verified correct.
//return aBuf
// ? GetWindowsDirectory(aBuf, MAX_PATH) // MAX_PATH is kept in case it's needed on Win9x for reasons similar to those in GetEnvironmentVarWin9x().
// : GetWindowsDirectory(buf_temp, 0);
// Above avoids subtracting 1 to be conservative and to reduce code size (due to the need to otherwise check for zero and avoid subtracting 1 in that case).
}
VarSizeType BIV_Temp(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_PATH];
VarSizeType length = GetTempPath(MAX_PATH, buf);
if (aBuf)
{
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here.
if (length)
{
aBuf += length - 1;
if (*aBuf == '\\') // For some reason, it typically yields a trailing backslash, so omit it to improve friendliness/consistency.
{
*aBuf = '\0';
--length;
}
}
}
return length;
}
VarSizeType BIV_ComSpec(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf_temp[1]; // Just a fake buffer to pass to some API functions in lieu of a NULL, to avoid any chance of misbehavior. Keep the size at 1 so that API functions will always fail to copy to buf.
// Sizes/lengths/-1/return-values/etc. have been verified correct.
return aBuf ? GetEnvVarReliable(_T("comspec"), aBuf) // v1.0.46.08: GetEnvVarReliable() fixes %Comspec% on Windows 9x.
: GetEnvironmentVariable(_T("comspec"), buf_temp, 0); // Avoids subtracting 1 to be conservative and to reduce code size (due to the need to otherwise check for zero and avoid subtracting 1 in that case).
}
VarSizeType BIV_SpecialFolderPath(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_PATH]; // One caller relies on this being explicitly limited to MAX_PATH.
int aFolder;
switch (ctoupper(aVarName[2]))
{
case 'P': // A_[P]rogram...
case 'O': // Pr[o]gramFiles
if (ctoupper(aVarName[9]) == 'S') // A_Programs(Common)
aFolder = aVarName[10] ? CSIDL_COMMON_PROGRAMS : CSIDL_PROGRAMS;
else // A_Program[F]iles or ProgramFi[L]es
aFolder = CSIDL_PROGRAM_FILES;
break;
case 'A': // A_AppData(Common)
aFolder = aVarName[9] ? CSIDL_COMMON_APPDATA : CSIDL_APPDATA;
break;
case 'D': // A_Desktop(Common)
aFolder = aVarName[9] ? CSIDL_COMMON_DESKTOPDIRECTORY : CSIDL_DESKTOPDIRECTORY;
break;
case 'S':
if (ctoupper(aVarName[7]) == 'M') // A_Start[M]enu(Common)
aFolder = aVarName[11] ? CSIDL_COMMON_STARTMENU : CSIDL_STARTMENU;
else // A_Startup(Common)
aFolder = aVarName[9] ? CSIDL_COMMON_STARTUP : CSIDL_STARTUP;
break;
#ifdef _DEBUG
default:
MsgBox(_T("DEBUG: Unhandled SpecialFolderPath variable."));
#endif
}
if (SHGetFolderPath(NULL, aFolder, NULL, SHGFP_TYPE_CURRENT, buf) != S_OK)
*buf = '\0';
if (aBuf)
_tcscpy(aBuf, buf); // Must be done as a separate copy because SHGetFolderPath requires a buffer of length MAX_PATH, and aBuf is usually smaller.
return _tcslen(buf);
}
VarSizeType BIV_MyDocuments(LPTSTR aBuf, LPTSTR aVarName) // Called by multiple callers.
{
TCHAR buf[MAX_PATH];
if (SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, buf) != S_OK)
*buf = '\0';
// Since it is common (such as in networked environments) to have My Documents on the root of a drive
// (such as a mapped drive letter), remove the backslash from something like M:\ because M: is more
// appropriate for most uses:
VarSizeType length = (VarSizeType)strip_trailing_backslash(buf);
if (aBuf)
|
tinku99/ahkdll
|
d9bbf67d498d7174523a37f06574506c65b19827
|
modified: .gitignore
|
diff --git a/.gitignore b/.gitignore
index 9ce5f66..dbbaff3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,12 +1,14 @@
AutoHotkey.sdf
*.opensdf
*.dll
*.suo
AutoHotkey.suo
AutoHotkey.vcxproj.user
ComServer_h.h
ComServer_i.c
Test
bin
ipch
temp
+MDtemp
+MDbin
diff --git a/AutoHotkey.sln b/AutoHotkey.sln
index 05816f1..b19b58f 100644
--- a/AutoHotkey.sln
+++ b/AutoHotkey.sln
@@ -1,156 +1,156 @@

-Microsoft Visual Studio Solution File, Format Version 11.00
-# Visual Studio 2010
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 2012
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lib_pcre", "source\lib_pcre\lib_pcre.vcxproj", "{39037993-9571-4DF2-8E39-CD2909043574}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AutoHotkey", "AutoHotkey.vcxproj", "{31335317-2533-40F5-ACD8-361075C7C4CC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug(mbcs)|Win32 = Debug(mbcs)|Win32
Debug(mbcs)|x64 = Debug(mbcs)|x64
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
DebugDll|Win32 = DebugDll|Win32
DebugDll|x64 = DebugDll|x64
Release(mbcs)|Win32 = Release(mbcs)|Win32
Release(mbcs)|x64 = Release(mbcs)|x64
Release(minimal)|Win32 = Release(minimal)|Win32
Release(minimal)|x64 = Release(minimal)|x64
Release|Win32 = Release|Win32
Release|x64 = Release|x64
ReleaseDll(mbcs)|Win32 = ReleaseDll(mbcs)|Win32
ReleaseDll(mbcs)|x64 = ReleaseDll(mbcs)|x64
ReleaseDll|Win32 = ReleaseDll|Win32
ReleaseDll|x64 = ReleaseDll|x64
ReleaseDllMini(mbcs)|Win32 = ReleaseDllMini(mbcs)|Win32
ReleaseDllMini(mbcs)|x64 = ReleaseDllMini(mbcs)|x64
ReleaseDllMini|Win32 = ReleaseDllMini|Win32
ReleaseDllMini|x64 = ReleaseDllMini|x64
Self-contained(debug)|Win32 = Self-contained(debug)|Win32
Self-contained(debug)|x64 = Self-contained(debug)|x64
Self-contained(mbcs)|Win32 = Self-contained(mbcs)|Win32
Self-contained(mbcs)|x64 = Self-contained(mbcs)|x64
Self-contained(minimal)|Win32 = Self-contained(minimal)|Win32
Self-contained(minimal)|x64 = Self-contained(minimal)|x64
Self-contained|Win32 = Self-contained|Win32
Self-contained|x64 = Self-contained|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{39037993-9571-4DF2-8E39-CD2909043574}.Debug(mbcs)|Win32.ActiveCfg = Debug(mbcs)|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.Debug(mbcs)|Win32.Build.0 = Debug(mbcs)|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.Debug(mbcs)|x64.ActiveCfg = Debug(mbcs)|x64
{39037993-9571-4DF2-8E39-CD2909043574}.Debug(mbcs)|x64.Build.0 = Debug(mbcs)|x64
{39037993-9571-4DF2-8E39-CD2909043574}.Debug|Win32.ActiveCfg = Debug|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.Debug|Win32.Build.0 = Debug|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.Debug|x64.ActiveCfg = Debug|x64
{39037993-9571-4DF2-8E39-CD2909043574}.Debug|x64.Build.0 = Debug|x64
{39037993-9571-4DF2-8E39-CD2909043574}.DebugDll|Win32.ActiveCfg = Debug|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.DebugDll|Win32.Build.0 = Debug|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.DebugDll|x64.ActiveCfg = Debug|x64
{39037993-9571-4DF2-8E39-CD2909043574}.DebugDll|x64.Build.0 = Debug|x64
{39037993-9571-4DF2-8E39-CD2909043574}.Release(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.Release(mbcs)|Win32.Build.0 = Release(mbcs)|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.Release(mbcs)|x64.ActiveCfg = Release(mbcs)|x64
{39037993-9571-4DF2-8E39-CD2909043574}.Release(mbcs)|x64.Build.0 = Release(mbcs)|x64
- {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|Win32.ActiveCfg = Release(minimal)|Win32
- {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|Win32.Build.0 = Release(minimal)|Win32
- {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|x64.ActiveCfg = Release(minimal)|x64
- {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|x64.Build.0 = Release(minimal)|x64
+ {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|Win32.ActiveCfg = Release(mbcs)|Win32
+ {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|Win32.Build.0 = Release(mbcs)|Win32
+ {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|x64.ActiveCfg = Release(mbcs)|x64
+ {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|x64.Build.0 = Release(mbcs)|x64
{39037993-9571-4DF2-8E39-CD2909043574}.Release|Win32.ActiveCfg = Release|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.Release|Win32.Build.0 = Release|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.Release|x64.ActiveCfg = Release|x64
{39037993-9571-4DF2-8E39-CD2909043574}.Release|x64.Build.0 = Release|x64
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll(mbcs)|Win32.Build.0 = Release(mbcs)|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll(mbcs)|x64.ActiveCfg = Release(mbcs)|x64
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll(mbcs)|x64.Build.0 = Release(mbcs)|x64
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll|Win32.ActiveCfg = Release|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll|Win32.Build.0 = Release|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll|x64.ActiveCfg = Release|x64
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll|x64.Build.0 = Release|x64
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini(mbcs)|Win32.Build.0 = Release(mbcs)|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini(mbcs)|x64.ActiveCfg = Release(mbcs)|x64
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini(mbcs)|x64.Build.0 = Release(mbcs)|x64
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini|Win32.ActiveCfg = Release|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini|Win32.Build.0 = Release|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini|x64.ActiveCfg = Release|x64
{39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini|x64.Build.0 = Release|x64
{39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(debug)|Win32.ActiveCfg = Release|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(debug)|Win32.Build.0 = Release|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(debug)|x64.ActiveCfg = Debug|x64
{39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(debug)|x64.Build.0 = Debug|x64
{39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(mbcs)|Win32.Build.0 = Release(mbcs)|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(mbcs)|x64.ActiveCfg = Release(mbcs)|x64
{39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(mbcs)|x64.Build.0 = Release(mbcs)|x64
- {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|Win32.ActiveCfg = Release(minimal)|Win32
- {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|Win32.Build.0 = Release(minimal)|Win32
- {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|x64.ActiveCfg = Release(minimal)|x64
- {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|x64.Build.0 = Release(minimal)|x64
+ {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|Win32.ActiveCfg = Release|Win32
+ {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|Win32.Build.0 = Release|Win32
+ {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|x64.ActiveCfg = Release|x64
+ {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|x64.Build.0 = Release|x64
{39037993-9571-4DF2-8E39-CD2909043574}.Self-contained|Win32.ActiveCfg = Release|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.Self-contained|Win32.Build.0 = Release|Win32
{39037993-9571-4DF2-8E39-CD2909043574}.Self-contained|x64.ActiveCfg = Release|x64
{39037993-9571-4DF2-8E39-CD2909043574}.Self-contained|x64.Build.0 = Release|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Debug(mbcs)|Win32.ActiveCfg = Debug(mbcs)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Debug(mbcs)|Win32.Build.0 = Debug(mbcs)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Debug(mbcs)|x64.ActiveCfg = Debug(mbcs)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Debug(mbcs)|x64.Build.0 = Debug(mbcs)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Debug|Win32.ActiveCfg = Debug|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Debug|Win32.Build.0 = Debug|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Debug|x64.ActiveCfg = Debug|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Debug|x64.Build.0 = Debug|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.DebugDll|Win32.ActiveCfg = DebugDll|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.DebugDll|Win32.Build.0 = DebugDll|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.DebugDll|x64.ActiveCfg = DebugDll|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.DebugDll|x64.Build.0 = DebugDll|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Release(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Release(mbcs)|Win32.Build.0 = Release(mbcs)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Release(mbcs)|x64.ActiveCfg = Release(mbcs)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Release(mbcs)|x64.Build.0 = Release(mbcs)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Release(minimal)|Win32.ActiveCfg = Release(minimal)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Release(minimal)|Win32.Build.0 = Release(minimal)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Release(minimal)|x64.ActiveCfg = Release(minimal)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Release(minimal)|x64.Build.0 = Release(minimal)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Release|Win32.ActiveCfg = Release|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Release|Win32.Build.0 = Release|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Release|x64.ActiveCfg = Release|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Release|x64.Build.0 = Release|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll(mbcs)|Win32.ActiveCfg = ReleaseDll(mbcs)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll(mbcs)|Win32.Build.0 = ReleaseDll(mbcs)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll(mbcs)|x64.ActiveCfg = ReleaseDll(mbcs)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll(mbcs)|x64.Build.0 = ReleaseDll(mbcs)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll|Win32.ActiveCfg = ReleaseDll|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll|Win32.Build.0 = ReleaseDll|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll|x64.ActiveCfg = ReleaseDll|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll|x64.Build.0 = ReleaseDll|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini(mbcs)|Win32.ActiveCfg = ReleaseDllMini(mbcs)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini(mbcs)|Win32.Build.0 = ReleaseDllMini(mbcs)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini(mbcs)|x64.ActiveCfg = ReleaseDllMini(mbcs)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini(mbcs)|x64.Build.0 = ReleaseDllMini(mbcs)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini|Win32.ActiveCfg = ReleaseDllMini|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini|Win32.Build.0 = ReleaseDllMini|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini|x64.ActiveCfg = ReleaseDllMini|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini|x64.Build.0 = ReleaseDllMini|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(debug)|Win32.ActiveCfg = Self-contained(debug)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(debug)|Win32.Build.0 = Self-contained(debug)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(debug)|x64.ActiveCfg = Self-contained(debug)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(debug)|x64.Build.0 = Self-contained(debug)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(mbcs)|Win32.ActiveCfg = Self-contained(mbcs)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(mbcs)|Win32.Build.0 = Self-contained(mbcs)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(mbcs)|x64.ActiveCfg = Self-contained(mbcs)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(mbcs)|x64.Build.0 = Self-contained(mbcs)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(minimal)|Win32.ActiveCfg = Self-contained(minimal)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(minimal)|Win32.Build.0 = Self-contained(minimal)|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(minimal)|x64.ActiveCfg = Self-contained(minimal)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(minimal)|x64.Build.0 = Self-contained(minimal)|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained|Win32.ActiveCfg = Self-contained|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained|Win32.Build.0 = Self-contained|Win32
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained|x64.ActiveCfg = Self-contained|x64
{31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained|x64.Build.0 = Self-contained|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
diff --git a/AutoHotkey.vcxproj b/AutoHotkey.vcxproj
index 0b1b21f..0e0d015 100644
--- a/AutoHotkey.vcxproj
+++ b/AutoHotkey.vcxproj
@@ -1,694 +1,697 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectGuid>{31335317-2533-40F5-ACD8-361075C7C4CC}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<PropertyGroup>
<TargetName>AutoHotkey</TargetName>
<ConfigurationType>Application</ConfigurationType>
<TargetName Condition="'$(Configuration)'=='ReleaseDllMini' OR '$(Configuration)'=='ReleaseDllMini(mbcs)'">AutoHotkeyMini</TargetName>
<TargetName Condition="'$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='ReleaseDll(mbcs)'">AutoHotkeyDll</TargetName>
<ConfigurationType Condition="'$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='ReleaseDllMini' OR '$(Configuration)'=='ReleaseDll(mbcs)' OR '$(Configuration)'=='ReleaseDllMini(mbcs)' OR '$(Configuration)'=='DebugDll'">DynamicLibrary</ConfigurationType>
</PropertyGroup>
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="DebugDll|Win32">
<Configuration>DebugDll</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="DebugDll|x64">
<Configuration>DebugDll</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug(mbcs)|Win32">
<Configuration>Debug(mbcs)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug(mbcs)|x64">
<Configuration>Debug(mbcs)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDll(mbcs)|Win32">
<Configuration>ReleaseDll(mbcs)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDll(mbcs)|x64">
<Configuration>ReleaseDll(mbcs)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDllMini(mbcs)|Win32">
<Configuration>ReleaseDllMini(mbcs)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDllMini(mbcs)|x64">
<Configuration>ReleaseDllMini(mbcs)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDllMini|Win32">
<Configuration>ReleaseDllMini</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDllMini|x64">
<Configuration>ReleaseDllMini</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDll|Win32">
<Configuration>ReleaseDll</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDll|x64">
<Configuration>ReleaseDll</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release(mbcs)|Win32">
<Configuration>Release(mbcs)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release(mbcs)|x64">
<Configuration>Release(mbcs)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release(minimal)|Win32">
<Configuration>Release(minimal)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release(minimal)|x64">
<Configuration>Release(minimal)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained|Win32">
<Configuration>Self-contained</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained|x64">
<Configuration>Self-contained</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained(debug)|Win32">
<Configuration>Self-contained(debug)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained(debug)|x64">
<Configuration>Self-contained(debug)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained(mbcs)|Win32">
<Configuration>Self-contained(mbcs)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained(mbcs)|x64">
<Configuration>Self-contained(mbcs)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained(minimal)|Win32">
<Configuration>Self-contained(minimal)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained(minimal)|x64">
<Configuration>Self-contained(minimal)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectName>AutoHotkey</ProjectName>
</PropertyGroup>
<!-- x64 toolset: must precede the import below -->
<PropertyGroup Label="Configuration" Condition="'$(Platform)'=='x64'">
<PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" Label="Configuration">
<PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" Label="Configuration">
<PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" Label="Configuration">
<PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<PlatformToolset>v110</PlatformToolset>
<UseOfMfc>false</UseOfMfc>
<UseOfAtl>false</UseOfAtl>
<CharacterSet />
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">
<PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'" Label="Configuration">
<PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
<PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">
<PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">
<PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">
<PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">
<PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">
<PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">
<PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
+ <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">
+ <CharacterSet>MultiByte</CharacterSet>
+ </PropertyGroup>
<!-- import common config -->
<Import Project="Config.vcxproj" />
<!-- platform: win32 & x64 (common) -->
<ItemDefinitionGroup Condition="'$(Platform)'=='Win32' OR '$(Platform)'=='x64'">
<ClCompile>
<PreprocessorDefinitions>_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<AdditionalDependencies>wsock32.lib;winmm.lib;version.lib;comctl32.lib;odbc32.lib;odbccp32.lib;shlwapi.lib;crypt32.lib;psapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<StackReserveSize>4194304</StackReserveSize>
<TerminalServerAware>false</TerminalServerAware>
</Link>
</ItemDefinitionGroup>
<!-- platform: win32 -->
<ItemDefinitionGroup Condition="'$(Platform)'=='Win32'">
<Link>
<TargetMachine>MachineX86</TargetMachine>
<MinimumRequiredVersion>5</MinimumRequiredVersion>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='ReleaseDll(mbcs)' OR '$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='DebugDll'">
<ClCompile>
<PreprocessorDefinitions>_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='ReleaseDllMini(mbcs)' OR '$(Configuration)'=='ReleaseDllMini'">
<ClCompile>
<PreprocessorDefinitions>_USRDLL;MINIDLL;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<!-- platform: x64 -->
<ItemDefinitionGroup Condition="'$(Platform)'=='x64'">
<ClCompile>
<PreprocessorDefinitions>_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<!-- paths and basic settings -->
<PropertyGroup>
<IntDir>MDtemp\$(Platform)\$(Configuration)\</IntDir>
<BinDir>bin\$(Platform)</BinDir>
<BinDir Condition="'$(CharacterSet)'=='Unicode'">$(BinDir)w</BinDir>
<BinDir Condition="'$(CharacterSet)'=='MultiByte'">$(BinDir)a</BinDir>
<OutDir>MD$(BinDir)\</OutDir>
<OutDir Condition="$(ConfigDebug)">MD$(BinDir)_debug\</OutDir>
<OutDir Condition="$(ConfigMinSize)">$(BinDir)_minimal\</OutDir>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<PrecompiledHeader Condition="!$(ConfigDebug)">Use</PrecompiledHeader>
</ClCompile>
<Link>
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
</Link>
<Manifest>
<AdditionalManifestFiles>source\resources\AutoHotkey.exe.manifest;%(AdditionalManifestFiles)</AdditionalManifestFiles>
</Manifest>
</ItemDefinitionGroup>
<!-- self-contained: required settings -->
<PropertyGroup Condition="$(ConfigSC)">
<TargetName>AutoHotkeySC</TargetName>
<TargetExt>.bin</TargetExt>
</PropertyGroup>
<ItemDefinitionGroup Condition="$(ConfigSC)">
<ClCompile>
<PreprocessorDefinitions>AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_WIN64;AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions Condition="$(ConfigDebug)">_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ResourceCompile>
<Link>
<AdditionalDependencies Condition="'$(Platform)'=='Win32'">%(AdditionalDependencies)</AdditionalDependencies>
</Link>
<PostBuildEvent>
<Message>Removing CheckSum from $(TargetFileName) so Ahk2Exe doesn't complain</Message>
<Command>"$(ProjectDir)PostBuildSC.ahk" "$(TargetPath)"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<!-- upx compression: Release -->
<PropertyGroup>
<PackerName>upx</PackerName>
<PackerName Condition="'$(Platform)'=='x64'">mpress</PackerName>
<PackerPath Condition="'$(PackerPath)'=='' AND exists('$(PackerName).exe')">$(PackerName).exe</PackerPath>
<PackerPath Condition="'$(PackerPath)'=='' AND exists('..\$(PackerName).exe')">..\$(PackerName).exe</PackerPath>
<PackerArgs Condition="'$(PackerArgs)'=='' AND '$(PackerName)'=='upx'"> --best --no-lzma --filter=73 --compress-icons=0</PackerArgs>
<PackerArgs Condition="'$(PackerArgs)'=='' AND '$(PackerName)'=='mpress'"> -x</PackerArgs>
</PropertyGroup>
<ItemDefinitionGroup Condition="$(ConfigRelease)">
<PostBuildEvent>
<Command>echo $(PackerName).exe disabled or not found, skipping compression</Command>
<Command Condition="exists('$(PackerPath)')">$(PackerPath)$(PackerArgs) "$(TargetPath)" & exit 0</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<!-- Visual C++ 2010 should place any newly created properties in these groups -->
<!-- FILES -->
<ItemGroup>
<ClCompile Include="source\application.cpp" />
<ClCompile Include="source\AutoHotkey.cpp" />
<ClCompile Include="source\clipboard.cpp" />
<ClCompile Include="source\Debugger.cpp">
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">Speed</FavorSizeOrSpeed>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="source\dllmain.cpp" />
<ClCompile Include="source\exports.cpp" />
<ClCompile Include="source\globaldata.cpp" />
<ClCompile Include="source\hook.cpp" />
<ClCompile Include="source\hotkey.cpp" />
<ClCompile Include="source\keyboard_mouse.cpp" />
<ClCompile Include="source\LiteUnzip.c">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="source\lowlevelbif.cpp" />
<ClCompile Include="source\MemoryModule.cpp">
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">DEBUG_OUTPUT;_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
</UndefinePreprocessorDefinitions>
<MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</MinimalRebuild>
<BasicRuntimeChecks Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">EnableFastChecks</BasicRuntimeChecks>
<FunctionLevelLinking Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
</FunctionLevelLinking>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">DEBUG_OUTPUT;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">_USRDLL;MINIDLL;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">_MBCS;AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</UndefinePreprocessorDefinitions>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">Use</PrecompiledHeader>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">
</UndefinePreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">
</UndefinePreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">
</UndefinePreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">
</UndefinePreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">
</UndefinePreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">
</UndefinePreprocessorDefinitions>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">Use</PrecompiledHeader>
</ClCompile>
<ClCompile Include="source\mt19937ar-cok.cpp" />
<ClCompile Include="source\os_version.cpp" />
<ClCompile Include="source\Registry.cpp">
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">_MBCS;MBCS;_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">_UNICODE;UNICODE</UndefinePreprocessorDefinitions>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">NotUsing</PrecompiledHeader>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_MBCS;MBCS;_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_UNICODE;UNICODE</UndefinePreprocessorDefinitions>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">NotUsing</PrecompiledHeader>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_MBCS;MBCS;_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_UNICODE;UNICODE</UndefinePreprocessorDefinitions>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="source\script.cpp" />
<ClCompile Include="source\script2.cpp" />
<ClCompile Include="source\script_autoit.cpp" />
<ClCompile Include="source\script_com.cpp" />
<ClCompile Include="source\script_expression.cpp" />
<ClCompile Include="source\script_gui.cpp" />
<ClCompile Include="source\script_menu.cpp" />
<ClCompile Include="source\script_object.cpp" />
<ClCompile Include="source\script_object_bif.cpp" />
<ClCompile Include="source\script_registry.cpp" />
<ClCompile Include="source\script_struct.cpp" />
<ClCompile Include="source\SimpleHeap.cpp" />
<ClCompile Include="source\stdafx.cpp">
<PrecompiledHeader>Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="source\StringConv.cpp" />
<ClCompile Include="source\TextIO.cpp" />
<ClCompile Include="source\util.cpp" />
<ClCompile Include="source\var.cpp" />
<ClCompile Include="source\window.cpp" />
<ClCompile Include="source\WinGroup.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="source\ahkversion.h" />
<ClInclude Include="source\application.h" />
<ClInclude Include="source\ComServerImpl.h" />
<ClInclude Include="source\clipboard.h" />
<ClInclude Include="source\config.h" />
<ClInclude Include="source\debug.h" />
<ClInclude Include="source\Debugger.h" />
<ClInclude Include="source\defines.h" />
<ClInclude Include="source\exports.h" />
<ClInclude Include="source\lib\exearc_read.h" />
<ClInclude Include="source\globaldata.h" />
<ClInclude Include="source\hook.h" />
<ClInclude Include="source\hotkey.h" />
<ClInclude Include="source\keyboard_mouse.h" />
<ClInclude Include="source\KuString.h" />
<ClInclude Include="source\LiteUnzip.h" />
<ClInclude Include="source\MemoryModule.h" />
<ClInclude Include="source\mt19937ar-cok.h" />
<ClInclude Include="source\os_version.h" />
<ClInclude Include="source\lib_pcre\pcre\pcre.h" />
<ClInclude Include="source\qmath.h" />
<ClInclude Include="source\Registry.h" />
<ClInclude Include="source\resources\resource.h" />
<ClInclude Include="source\script.h" />
<ClInclude Include="source\script_com.h" />
<ClInclude Include="source\script_object.h" />
<ClInclude Include="source\SimpleHeap.h" />
<ClInclude Include="source\stdafx.h" />
<ClInclude Include="source\StringConv.h" />
<ClInclude Include="source\TextIO.h" />
<ClInclude Include="source\util.h" />
<ClInclude Include="source\var.h" />
<ClInclude Include="source\window.h" />
<ClInclude Include="source\WinGroup.h" />
</ItemGroup>
<PropertyGroup>
<Masm>ml</Masm>
<Masm Condition="'$(Platform)'=='x64'">ml64</Masm>
<TargetExt>.exe</TargetExt>
<TargetExt Condition="'$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='ReleaseDllMini' OR '$(Configuration)'=='ReleaseDll(mbcs)' OR '$(Configuration)'=='ReleaseDllMini(mbcs)' OR '$(Configuration)'=='DebugDll'">.dll</TargetExt>
<TargetExt Condition="'$(Configuration)'=='Self-contained(mbcs)' OR '$(Configuration)'=='Self-contained'">.bin</TargetExt>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</LinkIncremental>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</LinkIncremental>
<IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</IgnoreImportLibrary>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
</ReferencePath>
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(VCInstallDir)bin;$(WindowsSdkDir)bin\NETFX 4.0 Tools;$(WindowsSdkDir)bin;$(VSInstallDir)Common7\Tools\bin;$(VSInstallDir)Common7\tools;$(VSInstallDir)Common7\ide;$(ProgramFiles)\HTML Help Workshop;$(FrameworkSDKDir)\bin;$(MSBuildToolsPath32);$(VSInstallDir);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ReferencePath>
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;$(MSBuildToolsPath32);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib;</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<ItemDefinitionGroup>
<CustomBuild>
<Command>$(Masm) /Cx /Fo"$(SolutionDir)temp\$(Platform)\%(Filename).obj" /c "%(FullPath)"</Command>
<Message />
<Outputs>$(SolutionDir)temp\$(Platform)\%(Filename).obj</Outputs>
</CustomBuild>
<ClCompile>
<Optimization Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Disabled</Optimization>
</ClCompile>
<ClCompile>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Neither</FavorSizeOrSpeed>
</ClCompile>
<ClCompile>
<OmitFramePointers Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</OmitFramePointers>
<StringPooling Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</StringPooling>
<MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">true</MinimalRebuild>
<BasicRuntimeChecks Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">MultiThreadedDebugDLL</RuntimeLibrary>
<BufferSecurityCheck Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">true</BufferSecurityCheck>
<EnableFiberSafeOptimizations Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</EnableFiberSafeOptimizations>
<IntrinsicFunctions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</IntrinsicFunctions>
<CreateHotpatchableImage Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</CreateHotpatchableImage>
<MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</MultiProcessorCompilation>
</ClCompile>
<Link>
<GenerateDebugInformation Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">true</GenerateDebugInformation>
<ModuleDefinitionFile Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">./comserver.def</ModuleDefinitionFile>
<ImportLibrary Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</ImportLibrary>
<RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</RandomizedBaseAddress>
<DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</DataExecutionPrevention>
<CreateHotPatchableImage Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</CreateHotPatchableImage>
<HeapReserveSize Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</HeapReserveSize>
<Driver Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">NotSet</Driver>
<OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</OptimizeReferences>
<LinkTimeCodeGeneration Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</LinkTimeCodeGeneration>
<EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</EnableCOMDATFolding>
<DelayLoadDLLs Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</DelayLoadDLLs>
</Link>
<Link>
<ModuleDefinitionFile Condition="'$(Configuration)'=='ReleaseDll'">.\comserver.def</ModuleDefinitionFile>
<ImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
<ImportLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">
</ImportLibrary>
<ImportLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">
</ImportLibrary>
<ImportLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">
</ImportLibrary>
<OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</OptimizeReferences>
<OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">true</OptimizeReferences>
<OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">true</OptimizeReferences>
<OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">true</OptimizeReferences>
<EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</EnableCOMDATFolding>
<EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">true</EnableCOMDATFolding>
<EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">true</EnableCOMDATFolding>
<EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">true</EnableCOMDATFolding>
<ForceSymbolReferences Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
<ForceSymbolReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" />
<ForceSymbolReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" />
<ForceSymbolReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" />
<AddModuleNamesToAssembly Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
<AddModuleNamesToAssembly Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" />
<AddModuleNamesToAssembly Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" />
<AddModuleNamesToAssembly Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" />
<AssemblyLinkResource Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
<AssemblyLinkResource Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" />
<AssemblyLinkResource Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" />
<AssemblyLinkResource Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" />
|
tinku99/ahkdll
|
57d1d2d01a5d4ce22b55c553b00f87e793bdc227
|
modified: README
|
diff --git a/AutoHotkey.vcxproj b/AutoHotkey.vcxproj
index 1ac196a..48320fb 100644
--- a/AutoHotkey.vcxproj
+++ b/AutoHotkey.vcxproj
@@ -1,644 +1,644 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectGuid>{31335317-2533-40F5-ACD8-361075C7C4CC}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<PropertyGroup>
<TargetName>AutoHotkey</TargetName>
<ConfigurationType>Application</ConfigurationType>
<TargetName Condition="'$(Configuration)'=='ReleaseDllMini' OR '$(Configuration)'=='ReleaseDllMini(mbcs)'">AutoHotkeyMini</TargetName>
<ConfigurationType Condition="'$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='ReleaseDllMini' OR '$(Configuration)'=='ReleaseDll(mbcs)' OR '$(Configuration)'=='ReleaseDllMini(mbcs)' OR '$(Configuration)'=='DebugDll'">DynamicLibrary</ConfigurationType>
</PropertyGroup>
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="DebugDll|Win32">
<Configuration>DebugDll</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="DebugDll|x64">
<Configuration>DebugDll</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug(mbcs)|Win32">
<Configuration>Debug(mbcs)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug(mbcs)|x64">
<Configuration>Debug(mbcs)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDll(mbcs)|Win32">
<Configuration>ReleaseDll(mbcs)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDll(mbcs)|x64">
<Configuration>ReleaseDll(mbcs)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDllMini(mbcs)|Win32">
<Configuration>ReleaseDllMini(mbcs)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDllMini(mbcs)|x64">
<Configuration>ReleaseDllMini(mbcs)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDllMini|Win32">
<Configuration>ReleaseDllMini</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDllMini|x64">
<Configuration>ReleaseDllMini</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDll|Win32">
<Configuration>ReleaseDll</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDll|x64">
<Configuration>ReleaseDll</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release(mbcs)|Win32">
<Configuration>Release(mbcs)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release(mbcs)|x64">
<Configuration>Release(mbcs)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release(minimal)|Win32">
<Configuration>Release(minimal)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release(minimal)|x64">
<Configuration>Release(minimal)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained|Win32">
<Configuration>Self-contained</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained|x64">
<Configuration>Self-contained</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained(debug)|Win32">
<Configuration>Self-contained(debug)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained(debug)|x64">
<Configuration>Self-contained(debug)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained(mbcs)|Win32">
<Configuration>Self-contained(mbcs)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained(mbcs)|x64">
<Configuration>Self-contained(mbcs)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained(minimal)|Win32">
<Configuration>Self-contained(minimal)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Self-contained(minimal)|x64">
<Configuration>Self-contained(minimal)</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectName>AutoHotkey</ProjectName>
</PropertyGroup>
<!-- x64 toolset: must precede the import below -->
<PropertyGroup Label="Configuration" Condition="'$(Platform)'=='x64'">
- <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ <PlatformToolset>v110</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<PlatformToolset>
</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" Label="Configuration">
<PlatformToolset>v100</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" Label="Configuration">
<PlatformToolset>
</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" Label="Configuration">
<PlatformToolset>
</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<PlatformToolset>
</PlatformToolset>
<UseOfMfc>false</UseOfMfc>
<UseOfAtl>false</UseOfAtl>
<CharacterSet />
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">
<PlatformToolset>
</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'" Label="Configuration">
<PlatformToolset>v100</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
<PlatformToolset>
</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">
<PlatformToolset />
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">
<PlatformToolset />
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">
<PlatformToolset />
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">
<PlatformToolset />
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">
<PlatformToolset />
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">
<PlatformToolset />
</PropertyGroup>
<!-- import common config -->
<Import Project="Config.vcxproj" />
<!-- platform: win32 & x64 (common) -->
<ItemDefinitionGroup Condition="'$(Platform)'=='Win32' OR '$(Platform)'=='x64'">
<ClCompile>
<PreprocessorDefinitions>_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<AdditionalDependencies>wsock32.lib;winmm.lib;version.lib;comctl32.lib;odbc32.lib;odbccp32.lib;shlwapi.lib;psapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<StackReserveSize>4194304</StackReserveSize>
<TerminalServerAware>false</TerminalServerAware>
</Link>
</ItemDefinitionGroup>
<!-- platform: win32 -->
<ItemDefinitionGroup Condition="'$(Platform)'=='Win32'">
<Link>
<TargetMachine>MachineX86</TargetMachine>
<MinimumRequiredVersion>5</MinimumRequiredVersion>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='ReleaseDll(mbcs)' OR '$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='DebugDll'">
<ClCompile>
<PreprocessorDefinitions>_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='ReleaseDllMini(mbcs)' OR '$(Configuration)'=='ReleaseDllMini'">
<ClCompile>
<PreprocessorDefinitions>_USRDLL;MINIDLL;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<!-- platform: x64 -->
<ItemDefinitionGroup Condition="'$(Platform)'=='x64'">
<ClCompile>
<PreprocessorDefinitions>_WIN64;AUTOCOMSERVER_EXPORTS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<!-- paths and basic settings -->
<PropertyGroup>
<IntDir>temp\$(Platform)\$(Configuration)\</IntDir>
<BinDir>bin\$(Platform)</BinDir>
<BinDir Condition="'$(CharacterSet)'=='Unicode'">$(BinDir)w</BinDir>
<BinDir Condition="'$(CharacterSet)'=='MultiByte'">$(BinDir)a</BinDir>
<OutDir>$(BinDir)\</OutDir>
<OutDir Condition="$(ConfigDebug)">$(BinDir)_debug\</OutDir>
<OutDir Condition="$(ConfigMinSize)">$(BinDir)_minimal\</OutDir>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<PrecompiledHeader Condition="!$(ConfigDebug)">Use</PrecompiledHeader>
</ClCompile>
<Link>
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
</Link>
<Manifest>
<AdditionalManifestFiles>source\resources\AutoHotkey.exe.manifest;%(AdditionalManifestFiles)</AdditionalManifestFiles>
</Manifest>
</ItemDefinitionGroup>
<!-- self-contained: required settings -->
<PropertyGroup Condition="$(ConfigSC)">
<TargetName>AutoHotkeySC</TargetName>
<TargetExt>.bin</TargetExt>
</PropertyGroup>
<ItemDefinitionGroup Condition="$(ConfigSC)">
<ClCompile>
<PreprocessorDefinitions>AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_WIN64;AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions Condition="$(ConfigDebug)">_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ResourceCompile>
<Link>
<AdditionalDependencies Condition="'$(Platform)'=='Win32'">%(AdditionalDependencies)</AdditionalDependencies>
</Link>
<PostBuildEvent>
<Message>Removing CheckSum from $(TargetFileName) so Ahk2Exe doesn't complain</Message>
<Command>"$(ProjectDir)PostBuildSC.ahk" "$(TargetPath)"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<!-- upx compression: Release -->
<PropertyGroup>
<PackerName>upx</PackerName>
<PackerName Condition="'$(Platform)'=='x64'">mpress</PackerName>
<PackerPath Condition="'$(PackerPath)'=='' AND exists('$(PackerName).exe')">$(PackerName).exe</PackerPath>
<PackerPath Condition="'$(PackerPath)'=='' AND exists('..\$(PackerName).exe')">..\$(PackerName).exe</PackerPath>
<PackerArgs Condition="'$(PackerArgs)'=='' AND '$(PackerName)'=='upx'"> --best --no-lzma --filter=73 --compress-icons=0</PackerArgs>
<PackerArgs Condition="'$(PackerArgs)'=='' AND '$(PackerName)'=='mpress'"> -x</PackerArgs>
</PropertyGroup>
<ItemDefinitionGroup Condition="$(ConfigRelease)">
<PostBuildEvent>
<Command>echo $(PackerName).exe disabled or not found, skipping compression</Command>
<Command Condition="exists('$(PackerPath)')">$(PackerPath)$(PackerArgs) "$(TargetPath)" & exit 0</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<!-- Visual C++ 2010 should place any newly created properties in these groups -->
<!-- FILES -->
<ItemGroup>
<ClCompile Include="source\application.cpp" />
<ClCompile Include="source\AutoHotkey.cpp" />
<ClCompile Include="source\clipboard.cpp" />
<ClCompile Include="source\Debugger.cpp">
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">Speed</FavorSizeOrSpeed>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">Speed</FavorSizeOrSpeed>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="source\dllmain.cpp" />
<ClCompile Include="source\exports.cpp" />
<ClCompile Include="source\globaldata.cpp" />
<ClCompile Include="source\hook.cpp" />
<ClCompile Include="source\hotkey.cpp" />
<ClCompile Include="source\keyboard_mouse.cpp" />
<ClCompile Include="source\lowlevelbif.cpp" />
<ClCompile Include="source\MemoryModule.cpp">
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">DEBUG_OUTPUT;_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
</UndefinePreprocessorDefinitions>
<MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</MinimalRebuild>
<BasicRuntimeChecks Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">EnableFastChecks</BasicRuntimeChecks>
<FunctionLevelLinking Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
</FunctionLevelLinking>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">DEBUG_OUTPUT;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">_USRDLL;MINIDLL;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">_MBCS;AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">
</UndefinePreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</UndefinePreprocessorDefinitions>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">Use</PrecompiledHeader>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">
</UndefinePreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">
</UndefinePreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">
</UndefinePreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">
</UndefinePreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">
</UndefinePreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">
</UndefinePreprocessorDefinitions>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">Use</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">Use</PrecompiledHeader>
</ClCompile>
<ClCompile Include="source\mt19937ar-cok.cpp" />
<ClCompile Include="source\os_version.cpp" />
<ClCompile Include="source\Registry.cpp">
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">_MBCS;MBCS;_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">_UNICODE;UNICODE</UndefinePreprocessorDefinitions>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">NotUsing</PrecompiledHeader>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_MBCS;MBCS;_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_UNICODE;UNICODE</UndefinePreprocessorDefinitions>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">NotUsing</PrecompiledHeader>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_MBCS;MBCS;_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_UNICODE;UNICODE</UndefinePreprocessorDefinitions>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="source\script.cpp" />
<ClCompile Include="source\script2.cpp" />
<ClCompile Include="source\script_autoit.cpp" />
<ClCompile Include="source\script_com.cpp" />
<ClCompile Include="source\script_expression.cpp" />
<ClCompile Include="source\script_gui.cpp" />
<ClCompile Include="source\script_menu.cpp" />
<ClCompile Include="source\script_object.cpp" />
<ClCompile Include="source\script_object_bif.cpp" />
<ClCompile Include="source\script_registry.cpp" />
<ClCompile Include="source\script_struct.cpp" />
<ClCompile Include="source\SimpleHeap.cpp" />
<ClCompile Include="source\stdafx.cpp">
<PrecompiledHeader>Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="source\StringConv.cpp" />
<ClCompile Include="source\TextIO.cpp" />
<ClCompile Include="source\util.cpp" />
<ClCompile Include="source\var.cpp" />
<ClCompile Include="source\window.cpp" />
<ClCompile Include="source\WinGroup.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="source\ahkversion.h" />
<ClInclude Include="source\application.h" />
<ClInclude Include="source\ComServerImpl.h" />
<ClInclude Include="source\clipboard.h" />
<ClInclude Include="source\config.h" />
<ClInclude Include="source\debug.h" />
<ClInclude Include="source\Debugger.h" />
<ClInclude Include="source\defines.h" />
<ClInclude Include="source\exports.h" />
<ClInclude Include="source\lib\exearc_read.h" />
<ClInclude Include="source\globaldata.h" />
<ClInclude Include="source\hook.h" />
<ClInclude Include="source\hotkey.h" />
<ClInclude Include="source\keyboard_mouse.h" />
<ClInclude Include="source\KuString.h" />
<ClInclude Include="source\MemoryModule.h" />
<ClInclude Include="source\mt19937ar-cok.h" />
<ClInclude Include="source\os_version.h" />
<ClInclude Include="source\lib_pcre\pcre\pcre.h" />
<ClInclude Include="source\qmath.h" />
<ClInclude Include="source\Registry.h" />
<ClInclude Include="source\resources\resource.h" />
<ClInclude Include="source\script.h" />
<ClInclude Include="source\script_com.h" />
<ClInclude Include="source\script_object.h" />
<ClInclude Include="source\SimpleHeap.h" />
<ClInclude Include="source\stdafx.h" />
<ClInclude Include="source\StringConv.h" />
<ClInclude Include="source\TextIO.h" />
<ClInclude Include="source\util.h" />
<ClInclude Include="source\var.h" />
<ClInclude Include="source\window.h" />
<ClInclude Include="source\WinGroup.h" />
</ItemGroup>
<PropertyGroup>
<Masm>ml</Masm>
<Masm Condition="'$(Platform)'=='x64'">ml64</Masm>
<TargetExt>.exe</TargetExt>
<TargetExt Condition="'$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='ReleaseDllMini' OR '$(Configuration)'=='ReleaseDll(mbcs)' OR '$(Configuration)'=='ReleaseDllMini(mbcs)' OR '$(Configuration)'=='DebugDll'">.dll</TargetExt>
<TargetExt Condition="'$(Configuration)'=='Self-contained(mbcs)' OR '$(Configuration)'=='Self-contained'">.bin</TargetExt>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</LinkIncremental>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</LinkIncremental>
<IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</IgnoreImportLibrary>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
</ReferencePath>
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath>
<ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'" />
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath>
<ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath>
</PropertyGroup>
<ItemDefinitionGroup>
<CustomBuild>
<Command>$(Masm) /Cx /Fo"$(SolutionDir)temp\$(Platform)\%(Filename).obj" /c "%(FullPath)"</Command>
<Message />
<Outputs>$(SolutionDir)temp\$(Platform)\%(Filename).obj</Outputs>
</CustomBuild>
<ClCompile>
<Optimization Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Disabled</Optimization>
</ClCompile>
<ClCompile>
<FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Neither</FavorSizeOrSpeed>
</ClCompile>
<ClCompile>
<OmitFramePointers Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</OmitFramePointers>
<StringPooling Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</StringPooling>
<MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">true</MinimalRebuild>
<BasicRuntimeChecks Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">MultiThreadedDLL</RuntimeLibrary>
<BufferSecurityCheck Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">true</BufferSecurityCheck>
<EnableFiberSafeOptimizations Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</EnableFiberSafeOptimizations>
<IntrinsicFunctions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</IntrinsicFunctions>
<CreateHotpatchableImage Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</CreateHotpatchableImage>
<MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</MultiProcessorCompilation>
</ClCompile>
<Link>
<GenerateDebugInformation Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">true</GenerateDebugInformation>
<ModuleDefinitionFile Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">.\comserver.def</ModuleDefinitionFile>
<ImportLibrary Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</ImportLibrary>
<RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</RandomizedBaseAddress>
<DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</DataExecutionPrevention>
<CreateHotPatchableImage Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</CreateHotPatchableImage>
<HeapReserveSize Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</HeapReserveSize>
<Driver Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">NotSet</Driver>
<OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</OptimizeReferences>
<LinkTimeCodeGeneration Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</LinkTimeCodeGeneration>
<EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">
</EnableCOMDATFolding>
</Link>
<Link>
<ModuleDefinitionFile Condition="'$(Configuration)'=='ReleaseDll'">.\comserver.def</ModuleDefinitionFile>
<ImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
<ImportLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">
</ImportLibrary>
<ImportLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">
</ImportLibrary>
<ImportLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">
</ImportLibrary>
<OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</OptimizeReferences>
<OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">true</OptimizeReferences>
<OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">true</OptimizeReferences>
<OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">true</OptimizeReferences>
<EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</EnableCOMDATFolding>
diff --git a/README b/README
index 9247ae6..b7f8347 100644
--- a/README
+++ b/README
@@ -1,181 +1,183 @@
+builds at home
+runs only at work
07.10.2012
- Merged latest AutoHotkey_L changes from https://github.com/Lexikos/AutoHotkey_L.
- OnMessage accepts optionally a window handle now, e.g. OnMessage(0x200,hwnd,"WM_MOUSEMOVE")
- - this allows to have separate function for each window or launch the function for specified window only.
- fixed to launch default script if parameters in ahktextdll and ahkdll functions are missing completely.
- small fix for Struct() string data handling.
- Enabled compression for compiled scripts, use https://github.com/HotKeyIt/Ahk2Exe to compile using compression
- - Many thanks to SKAN for VarZ http://www.autohotkey.com/community/viewtopic.php?p=276616#p276616
17.08.2012
- Fixed to use alignment for all types and also in 32-bit environment
- Fixed pointer handling in some cases
- To set Pointer in main structure you will need to use struct["",""]:=ptr
09.08.2012
- Merged AutoHotkey_L 1.1.08.01
- Fixed a bug in ahkFunction, variables were not freed.
- Fixed freeing some internal variables on restart or ExitApp in AutoHotkey.dll.
- Fixed OnMessage was not correctly handled on reload and ExitApp in AutoHotkey.dll.
- Static variables are now saved separately from local variables
- - When a function uses many static variables the time used to call the function is greatly improved.
- - This is because only local variables need to be freed and we do not need to check if a variable is static.
- - ListVars also shows static variables separate from local, this also helps debugging.
- New Build-in functions
- - Struct() and sizeof(), see manual for usage.
15.02.2012
- ResourceLibrary
- Removed ahkKey
- FileInstall for Scripts compiled with AutoHotkey.exe
- Allow pure integers (pointers) for DllCall and DynaCall "Str" prameter.
01.10.2011
- Merged latest MemoryModule
- Fixed x64w build AutoHotkey.dll also works fine using COM
25.10.2010
- Fixed ahkFunction returning wrong value
- Default script set to #Persistent`n#NoTrayIcon
- Fixed ahkExec to return when no line was added
15.08.2010
- Merged AutoHotkey_L54
- DllCall will now always search for W and A functions first, this is due to some functions do not have A suffix e.g. Process32First and Process32FirstW
- when empty string is passed to ahkdll function, it will run in text mode same as ahktextdll so it will run "#Persistent".
- ahkLabel second parameter is called nowait now so when 0 (default) AutoHotkey will wait for code to finish execution, because using PostMessage times out often when CPU is under load.
12.08.2010
- Merged AutoHotkey_L Revision 53
- new exported function ahkExec used to temporarily run some script, accepts also several lines of code
- when empty string is passed in first parameter, AutoHotkey will run "#Pesistent" as script.
18.07.2010
- Fixed a bug for dll when it was in root folder
- DynaCall is now managed trough internal DynaToken, similar to objects but without object features and much faster but can be used with DynaCall only (thanks Lexikos)
- DynaCall can set default parameters now, so you can call the function later with less or even witout parameters: func.()
16.07.2010
- Fixed not to delete ClipBoard vars when ahkdll is reloaded
11.07.2010
- Merged latest fixes by tinku99
19.06.2010 - H17
- Merged with AHK_L52
10.06.2010
- Fixed addScript and addFile loop bug
- Fixed ahkFunction bug when returning empty parameters and strings
27.05.2010
- Fixed when terminating dll not to destroy Build in variables
- Fixed problem when dll reloads, now parameter strings given to ahkdll and ahktextdll are copied and not used.
14.05.2010
- Fix for Alias BIF
- Multithread support for Input command, see other changes in docs.
28.03.2010
- Merge AutoHotkey_L Revision 50
- DynaCall fix, *pP parameter was not initialized correctly
28.02.2010
- DynaCall returns Objects now.
- You can use object features like dll.ahkgetvar.var or dll.ahkFunction["func"] or dll.ahkassign.var := value
13.02.2010
- ResourceLoadLibrary for AutoHotkeySC.bin
10.02.2010
- fix for A_DllPath
- fix on DLL_PROCESS_DETACH invalid hThread (MemoryFreeLibrary works fine now)
07.02.2010
- fixed ahkFunction
- added ahkPostFunction same syntax as ahkFunction but returns unsigned int 0 if func found, else -1
- ahkPostFunction and ahkFunction parameters are all optional now.
- ahkFunction and ahkPostFunction use now a CRITICAL_SECTION to avoid collision
- SendMode Input is default now.
- #NoEnv is default now, use '#NoEnv, Off' to turn off
- fixed ahkExecuteLine to run when lastline is given
- ahkLabel returns 0 if Label found else -1
- added ahkFindLabel
- ahkTerminate will now try (for 500ms) to stop the thread via PostMessage before running TerminateThread.
- EXPERIMENTAL New build in functions: MemoryLoadLibrary - MemoryGetProcAddress - MemoryFreeLibrary
- - Based on http://www.joachim-bauch.de/tutorials/load_dll_memory.html
- - So now multithreading is even easier as only 1 dll is needed.
- - Hook does not work currently.
- DynaCall, runs faster than DllCall and uses internally saved array of DllCall structures based on functions pointer.
03.02.2010
- Unicode
18.01.2010
- fixed MsgSleep to work after termination and reload.
- enabled #Persistent so a script that does not use #Persistent will terminate (use ahkdll ahktextdll or ahkReload to run it again).
- Send commands support inline sleep now when pure digits are specified, like Send a{30}{Tab}b{100}{Enter}. Send {9} will not sleep but send 9.
- Reload, Exit and ExitApp works like they should now for the dll.
- Added 2 new stdlib folder, which is the parent folder of A_AhkPath + Lib.lnk in same folder if it links to a directory.
- - - Directory of A_AhkPath, so now stdlib functions can be placed in same folder for simplicity.
- - - Additionally you can specify a link file in same folder (Lib.lnk) to your stdlib instead of copying the files for a portable project (e.g. on a ram drive!).
- ahktextdll and addScript support loading functions from all 4 libraries now as well.
- AutoHotkey.exe started without parameters checks for following files:
- - 1 %A_AhkPath%\..\[Name of executable].ahk
- - 2 %A_AhkPath%\..\[Name of executable].ini
- - 3 %A_MyDocuments%\AutoHotkey.ahk
- - - REMINDER: portable mode = copy + rename AutoHotkey.exe to e.g. MyScript.exe and put it together with MyScript.ahk or .ini in same folder.
- No need to call ahkTerminate before calling ahkdll or ahktextdll, it will terminate automatically if a script is running.
- New AhkDll function - AhkDll(dllfile,function,p1,p2...), using static pointers to functions, executes around 5 times faster.
- - Loads dll library automatically so no need to call DllCall("LoadLibrary"...)
- - Dllfile must contain only characters valid for a variable in ahk [a-zA-Z0-9_#$@]!
- - Functions are all case sensitive!
- ahkgetvar has now a further parameter (UInt), when this parameter is not 0, the pointer of the variable will be returned to use with Alias(), else value is returned
- New AutoHotkeyMini.dll uses a preprocessor and excludes many commands to support much faster load/reload and less memory usage.
- Following commands are disabled/removed:
- - Hotkey (as well as Hotkey + Hotstring functionality), Gui
, GuiControl[Get], Menu
, TrayIcon, FileInstall, ListVars, ListLines, ListHotkeys,
- - KeyHistory, SplashImage, SplashText
, Progress, PixelSearch, PixelGetColor, InputBox,
- - FileSelect and FolderSelect dialogs, Input, BlockInput MouseMove[Off],
- - Build in variables related to Hotkeys and Icons as well as Gui, A_ThisHotkey
, A_IsSuspended, A_Icon
.
30.12.2009
- ahkReload will reload a script, this can be also done by the script as well as ExitApp.
- ahkPause, get and set Pause state of current thread in dll script (dll only)
- ahkExecuteLine, execute a line by passing its pointer, a pointer is returned by addFile and addScript as well as by this function.
- - when no pointer is given, FirstLine pointer is returned, else pointer to next line is returned.
- changed ahkgetvar to return a value rather than passing a variable, so no need to VarSetCapacity anymore.
- fixed ahkFunction ( now using callFuncDll() ) to continue main script after function call.
- fixed to wait for thread to initialize and return then, as well as when script crashes while initializing.
- addScript will not reset previous script anymore.
- removed const for HotkeyIDType Hotkey so sHotkeyCount can be reset for ahkTerminate.
21.12.2009
- ahkTerminate, after terminating your script you can reload it using ahkdll or ahktextdll.
- script, incl. labels and functions, and hotkey destruction and reload now possible.
- a bug in ahkFunction was fixed.
19.12.2009
- fixed addScript bugs
- created ahktextdll
18.12.2009
- addScript loads script from text, second parameter is to replace current script
DllCall(A_AhkPath "\addScript","Str","a:`nMsgBox a`nReturn","ushort",1,"Cdecl UInt")
- \ahkdll function will now load text if specified file does not exist
- no need for #Persistent in AutoHotkey.dll
17.12.2009
- Changed to "Portable Mode"
- Instead looking for %My_Documents%\AutoHotkey.ahk, the exe checks for %ExeDir%\ExeName.ahk.
- So you can copy AutoHotkey.exe and Script to separate folder then rename the exe to ScriptName.exe and start by double clicking the exe.
- You can also start new scripts using your exe that way.
e.g. Run YourExe.exe "%filepath%"
- Changed ahkgetvar to support alias and build in variables.
- Removed ebiv.cpp because ahkgetvar can be used to get any variable beside clipboard and clipboardall
-- Changed ahkFunction to support up to 10 parameters + return values
\ No newline at end of file
+- Changed ahkFunction to support up to 10 parameters + return values
diff --git a/source/lib_pcre/lib_pcre.vcxproj b/source/lib_pcre/lib_pcre.vcxproj
index c38ea7d..ef4e7e5 100644
--- a/source/lib_pcre/lib_pcre.vcxproj
+++ b/source/lib_pcre/lib_pcre.vcxproj
@@ -1,359 +1,362 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <PropertyGroup>
- <ProjectGuid>{39037993-9571-4DF2-8E39-CD2909043574}</ProjectGuid>
- <Keyword>Win32Proj</Keyword>
- </PropertyGroup>
- <PropertyGroup>
- <ConfigurationType>StaticLibrary</ConfigurationType>
- </PropertyGroup>
- <ItemGroup Label="ProjectConfigurations">
- <ProjectConfiguration Include="Debug(mbcs)|x64">
- <Configuration>Debug(mbcs)</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Debug|Win32">
- <Configuration>Debug</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Debug(mbcs)|Win32">
- <Configuration>Debug(mbcs)</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Debug|x64">
- <Configuration>Debug</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release(mbcs)|x64">
- <Configuration>Release(mbcs)</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release(minimal)|x64">
- <Configuration>Release(minimal)</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release|Win32">
- <Configuration>Release</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release(mbcs)|Win32">
- <Configuration>Release(mbcs)</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release(minimal)|Win32">
- <Configuration>Release(minimal)</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release|x64">
- <Configuration>Release</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- </ItemGroup>
- <!-- import common config -->
- <Import Project="..\..\Config.vcxproj" />
- <!-- platform: win32 -->
- <ItemDefinitionGroup Condition="'$(Platform)'=='Win32'">
- <ClCompile>
- <PreprocessorDefinitions>WIN32;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- </ClCompile>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Platform)'=='x64'">
- <ClCompile>
- <PreprocessorDefinitions>WIN32;_LIB;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- </ClCompile>
- </ItemDefinitionGroup>
- <!-- paths and basic settings -->
- <PropertyGroup>
- <OutDir>$(SolutionDir)temp\$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(SolutionDir)temp\$(Platform)\$(Configuration)\lib_pcre\</IntDir>
- </PropertyGroup>
- <ItemDefinitionGroup>
- <ClCompile>
- <CompileAs>CompileAsC</CompileAs>
- <PreprocessorDefinitions>HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- </ClCompile>
- <Lib>
- <OutputFile>$(OutDir)lib_pcre.lib</OutputFile>
- </Lib>
- </ItemDefinitionGroup>
- <!-- Release -->
- <ItemDefinitionGroup Condition="!$(ConfigDebug)">
- <ClCompile>
- <IntrinsicFunctions>true</IntrinsicFunctions>
- </ClCompile>
- <Lib>
- <!-- WHY IS THIS EXCLUDED IN DEBUG CONFIG? -->
- <IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries>
- <!--<IgnoreSpecificDefaultLibraries>LibCMT;MSVCrt;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>-->
- </Lib>
- </ItemDefinitionGroup>
- <!-- Visual C++ 2010 should place any newly created properties in these groups -->
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'" />
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <ClCompile>
- <UndefinePreprocessorDefinitions>
- </UndefinePreprocessorDefinitions>
- </ClCompile>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'" />
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'" />
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'" />
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'" />
- <!-- FILES -->
- <ItemGroup>
- <ClCompile Include="pcre\pcre16_chartables.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_compile.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_config.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_exec.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_fullinfo.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_get.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_globals.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_jit_compile.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_newline.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_ord2utf16.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_refcount.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_string_utils.c" />
- <ClCompile Include="pcre\pcre16_study.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_tables.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_ucd.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_valid_utf16.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_version.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre16_xclass.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_chartables.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_compile.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_config.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_exec.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_fullinfo.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_get.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_globals.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_jit_compile.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_newline.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_ord2utf8.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_refcount.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_string_utils.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_study.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_tables.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_ucd.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_version.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- <ClCompile Include="pcre\pcre_xclass.c">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
- </ClCompile>
- </ItemGroup>
- <ItemGroup>
- <ClInclude Include="pcre\config.h" />
- <ClInclude Include="pcre\pcre_internal.h" />
- </ItemGroup>
- <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <ProjectGuid>{39037993-9571-4DF2-8E39-CD2909043574}</ProjectGuid>
+ <Keyword>Win32Proj</Keyword>
+ </PropertyGroup>
+ <PropertyGroup>
+ <ConfigurationType>StaticLibrary</ConfigurationType>
+ </PropertyGroup>
+ <ItemGroup Label="ProjectConfigurations">
+ <ProjectConfiguration Include="Debug(mbcs)|x64">
+ <Configuration>Debug(mbcs)</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug|Win32">
+ <Configuration>Debug</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug(mbcs)|Win32">
+ <Configuration>Debug(mbcs)</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug|x64">
+ <Configuration>Debug</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release(mbcs)|x64">
+ <Configuration>Release(mbcs)</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release(minimal)|x64">
+ <Configuration>Release(minimal)</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|Win32">
+ <Configuration>Release</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release(mbcs)|Win32">
+ <Configuration>Release(mbcs)</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release(minimal)|Win32">
+ <Configuration>Release(minimal)</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|x64">
+ <Configuration>Release</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ </ItemGroup>
+ <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">
+ <PlatformToolset>v110</PlatformToolset>
+ </PropertyGroup>
+ <!-- import common config -->
+ <Import Project="..\..\Config.vcxproj" />
+ <!-- platform: win32 -->
+ <ItemDefinitionGroup Condition="'$(Platform)'=='Win32'">
+ <ClCompile>
+ <PreprocessorDefinitions>WIN32;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Platform)'=='x64'">
+ <ClCompile>
+ <PreprocessorDefinitions>WIN32;_LIB;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ </ItemDefinitionGroup>
+ <!-- paths and basic settings -->
+ <PropertyGroup>
+ <OutDir>$(SolutionDir)temp\$(Platform)\$(Configuration)\</OutDir>
+ <IntDir>$(SolutionDir)temp\$(Platform)\$(Configuration)\lib_pcre\</IntDir>
+ </PropertyGroup>
+ <ItemDefinitionGroup>
+ <ClCompile>
+ <CompileAs>CompileAsC</CompileAs>
+ <PreprocessorDefinitions>HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <Lib>
+ <OutputFile>$(OutDir)lib_pcre.lib</OutputFile>
+ </Lib>
+ </ItemDefinitionGroup>
+ <!-- Release -->
+ <ItemDefinitionGroup Condition="!$(ConfigDebug)">
+ <ClCompile>
+ <IntrinsicFunctions>true</IntrinsicFunctions>
+ </ClCompile>
+ <Lib>
+ <!-- WHY IS THIS EXCLUDED IN DEBUG CONFIG? -->
+ <IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries>
+ <!--<IgnoreSpecificDefaultLibraries>LibCMT;MSVCrt;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>-->
+ </Lib>
+ </ItemDefinitionGroup>
+ <!-- Visual C++ 2010 should place any newly created properties in these groups -->
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'" />
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <ClCompile>
+ <UndefinePreprocessorDefinitions>
+ </UndefinePreprocessorDefinitions>
+ </ClCompile>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'" />
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'" />
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'" />
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'" />
+ <!-- FILES -->
+ <ItemGroup>
+ <ClCompile Include="pcre\pcre16_chartables.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_compile.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_config.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_exec.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_fullinfo.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_get.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_globals.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_jit_compile.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_newline.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_ord2utf16.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_refcount.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_string_utils.c" />
+ <ClCompile Include="pcre\pcre16_study.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_tables.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_ucd.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_valid_utf16.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_version.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre16_xclass.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_chartables.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_compile.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_config.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_exec.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_fullinfo.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_get.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_globals.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_jit_compile.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_newline.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_ord2utf8.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_refcount.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_string_utils.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_study.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_tables.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_ucd.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_version.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ <ClCompile Include="pcre\pcre_xclass.c">
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</ExcludedFromBuild>
+ <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
+ </ClCompile>
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="pcre\config.h" />
+ <ClInclude Include="pcre\pcre_internal.h" />
+ </ItemGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
</Project>
\ No newline at end of file
|
tinku99/ahkdll
|
46f176d800715603c07dcfc464695ffef8e658cc
|
WinApi added psapi.dll
|
diff --git a/source/resources/WINAPI.zip b/source/resources/WINAPI.zip
index 6151cff..09b3c5b 100644
Binary files a/source/resources/WINAPI.zip and b/source/resources/WINAPI.zip differ
|
tinku99/ahkdll
|
de1a106a1c420819996afd0de324969b505ef9bc
|
Zero memory used when reading script
|
diff --git a/source/TextIO.h b/source/TextIO.h
index 4b4e9fe..290abb3 100644
--- a/source/TextIO.h
+++ b/source/TextIO.h
@@ -1,356 +1,359 @@
#pragma once
#define TEXT_IO_BLOCK 8192
#ifndef CP_UTF16
#define CP_UTF16 1200 // the codepage of UTF-16LE
#endif
#ifdef UNICODE
#define W_OR_A(n) n##W
#else
#define W_OR_A(n) n##A
#endif
#define TEOF ((TCHAR)EOF)
#include <locale.h> // For _locale_t, _create_locale and _free_locale.
extern UINT g_ACP;
// VS2005 and later come with Unicode stream IO in the C runtime library, but it doesn't work very well.
// For example, it can't read the files encoded in "system codepage" by using
// wide-char version of the functions such as fgetws(). The characters were not translated to
// UTF-16 properly. Although we can create some workarounds for it, but that will make
// the codes even hard to maintain.
class TextStream
{
public:
enum {
// open modes
READ
, WRITE
, APPEND
, UPDATE
, USEHANDLE = 0x10000000 // Used by BIF_FileOpen/FileObject. High value avoids conflict with the flags below, which can't change because it would break scripts.
, ACCESS_MODE_MASK = READ|WRITE|APPEND|UPDATE|USEHANDLE
// EOL translations
, EOL_CRLF = 0x00000004 // read: CRLF to LF. write: LF to CRLF.
, EOL_ORPHAN_CR = 0x00000008 // read: CR to LF (when the next character isn't LF)
// write byte order mark when open for write
, BOM_UTF8 = 0x00000010
, BOM_UTF16 = 0x00000020
// shared accesses
, SHARE_READ = 0x00000100
, SHARE_WRITE = 0x00000200
, SHARE_DELETE = 0x00000400
, SHARE_ALL = SHARE_READ|SHARE_WRITE|SHARE_DELETE
};
TextStream()
: mFlags(0), mCodePage(-1), mLength(0), mBuffer(NULL), mPos(NULL), mLastRead(0)
{
SetCodePage(CP_ACP);
}
virtual ~TextStream()
{
if (mBuffer)
+ {
+ SecureZeroMemory(mBuffer, TEXT_IO_BLOCK);
free(mBuffer);
+ }
//if (mLocale)
// _free_locale(mLocale);
// Close() isn't called here, it will rise a "pure virtual function call" exception.
}
bool Open(LPCTSTR aFileSpec, DWORD aFlags, UINT aCodePage = CP_ACP);
void Close()
{
FlushWriteBuffer();
_Close();
}
DWORD Write(LPCTSTR aBuf, DWORD aBufLen = 0);
DWORD Write(LPCVOID aBuf, DWORD aBufLen);
DWORD Read(LPTSTR aBuf, DWORD aBufLen, int aNumLines = 0);
DWORD Read(LPVOID aBuf, DWORD aBufLen);
DWORD ReadLine(LPTSTR aBuf, DWORD aBufLen)
{
return Read(aBuf, aBufLen, 1);
}
INT_PTR FormatV(LPCTSTR fmt, va_list ap)
{
CString str;
str.FormatV(fmt, ap);
return Write(str, (DWORD)str.GetLength()) / sizeof(TCHAR);
}
INT_PTR Format(LPCTSTR fmt, ...)
{
va_list ap;
va_start(ap, fmt);
return FormatV(fmt, ap);
}
bool AtEOF()
// Returns true if there is no more data in the read buffer
// *and* the file pointer is at the end of the file.
{
if (mPos && mPos < mBuffer + mLength)
return false;
__int64 pos = _Tell();
return (pos < 0 || pos >= _Length());
}
void SetCodePage(UINT aCodePage)
{
if (aCodePage == CP_ACP)
aCodePage = g_ACP; // Required by _create_locale.
//if (!IsValidCodePage(aCodePage)) // Returns FALSE for UTF-16 and possibly other valid code pages, so leave it up to the user to pass a valid codepage.
//return;
if (mCodePage != aCodePage)
{
// Resist temptation to do the following as a way to avoid having an odd number of bytes in
// the buffer, since it breaks non-seeking devices and actually isn't sufficient for cases
// where the caller uses raw I/O in addition to text I/O (e.g. read one byte then read text).
//RollbackFilePointer();
mCodePage = aCodePage;
if (!GetCPInfo(aCodePage, &mCodePageInfo))
mCodePageInfo.LeadByte[0] = NULL;
}
}
UINT GetCodePage() { return mCodePage; }
DWORD GetFlags() { return mFlags; }
protected:
// IO abstraction
virtual bool _Open(LPCTSTR aFileSpec, DWORD &aFlags) = 0;
virtual void _Close() = 0;
virtual DWORD _Read(LPVOID aBuffer, DWORD aBufSize) = 0;
virtual DWORD _Write(LPCVOID aBuffer, DWORD aBufSize) = 0;
virtual bool _Seek(__int64 aDistance, int aOrigin) = 0;
virtual __int64 _Tell() const = 0;
virtual __int64 _Length() const = 0;
void RollbackFilePointer()
{
if (mPos) // Buffered reading was used.
{
// Discard the buffer and rollback the file pointer.
ptrdiff_t offset = (mPos - mBuffer) - mLength; // should be a value <= 0
_Seek(offset, SEEK_CUR);
// Callers expect the buffer to be cleared (e.g. to be reused for buffered writing), so if
// _Seek fails, the data is simply discarded. This can probably only happen for non-seeking
// devices such as pipes or the console, which won't typically be both read from and written to:
mPos = NULL;
mLength = 0;
}
}
void FlushWriteBuffer()
{
if (mLength && !mPos)
{
// Flush write buffer.
_Write(mBuffer, mLength);
mLength = 0;
}
mLastWriteChar = 0;
}
bool PrepareToWrite()
{
if (!mBuffer)
mBuffer = (BYTE *) malloc(TEXT_IO_BLOCK);
else if (mPos) // Buffered reading was used.
RollbackFilePointer();
return mBuffer != NULL;
}
bool PrepareToRead()
{
FlushWriteBuffer();
return true;
}
template<typename TCHR>
DWORD WriteTranslateCRLF(TCHR *aBuf, DWORD aBufLen); // Used by TextStream::Write(LPCSTR,DWORD).
// Functions for populating the read buffer.
DWORD Read(DWORD aReadSize = TEXT_IO_BLOCK)
{
ASSERT(aReadSize);
if (!mBuffer) {
mBuffer = (BYTE *) malloc(TEXT_IO_BLOCK);
if (!mBuffer)
return 0;
}
if (mLength + aReadSize > TEXT_IO_BLOCK)
aReadSize = TEXT_IO_BLOCK - mLength;
DWORD dwRead = _Read(mBuffer + mLength, aReadSize);
if (dwRead)
mLength += dwRead;
return mLastRead = dwRead; // The amount read *this time*.
}
bool ReadAtLeast(DWORD aReadSize)
{
if (!mPos)
Read(TEXT_IO_BLOCK);
else if (mPos > mBuffer + mLength - aReadSize) {
ASSERT( (DWORD)(mPos - mBuffer) <= mLength );
mLength -= (DWORD)(mPos - mBuffer);
memmove(mBuffer, mPos, mLength);
Read(TEXT_IO_BLOCK);
}
else
return true;
mPos = mBuffer;
return (mLength >= aReadSize);
}
__declspec(noinline) bool IsLeadByte(BYTE b) // noinline benchmarks slightly faster.
{
for (int i = 0; i < _countof(mCodePageInfo.LeadByte) && mCodePageInfo.LeadByte[i]; i += 2)
if (b >= mCodePageInfo.LeadByte[i] && b <= mCodePageInfo.LeadByte[i+1])
return true;
return false;
}
DWORD mFlags;
DWORD mLength; // The length of available data in the buffer, in bytes.
DWORD mLastRead;
UINT mCodePage;
CPINFO mCodePageInfo;
TCHAR mLastWriteChar;
union // Pointer to the next character to read in mBuffer.
{
LPBYTE mPos;
LPSTR mPosA;
LPWSTR mPosW;
};
union // Used by buffered/translated IO to hold raw file data.
{
LPBYTE mBuffer;
LPSTR mBufferA;
LPWSTR mBufferW;
};
};
class TextFile : public TextStream
{
public:
TextFile() : mFile(INVALID_HANDLE_VALUE) {}
virtual ~TextFile() { FlushWriteBuffer(); _Close(); }
// Text IO methods from TextStream.
using TextStream::Read;
using TextStream::Write;
// These methods are exported to provide binary file IO.
bool Seek(__int64 aDistance, int aOrigin)
{
RollbackFilePointer();
FlushWriteBuffer();
return _Seek(aDistance, aOrigin);
}
__int64 Tell()
{
__int64 pos = _Tell();
return (pos == -1) ? -1 : pos + (mPos ? mPos - (mBuffer + mLength) : (ptrdiff_t)mLength);
}
__int64 Length()
{
__int64 len = _Length();
if (!mPos && mLength) // mBuffer contains data to write.
{
// Not len+mLength, since we might not be writing at the end of the file.
// Return the current position plus the amount of buffered data, except
// when that falls short of the current actual length of the file.
__int64 buf_end = _Tell() + mLength;
if (buf_end > len)
return buf_end;
}
return len;
}
__int64 Length(__int64 aLength)
{
// Truncating the file may mean discarding some of the data in the buffer:
// data read from a position after the new end-of-file, or data which should
// have already been written after the new end-of-file, but has been buffered.
// Calculating how much data should be discarded doesn't seem worthwhile, so
// just flush the buffer:
RollbackFilePointer();
FlushWriteBuffer();
// Since the buffer was just flushed, Tell() vs _Tell() doesn't matter here.
// Otherwise, using Tell() followed by _Seek() below would advance the pointer
// by the amount of buffered data, when the intention is to not move it at all.
__int64 pos = _Tell();
if (!_Seek(aLength, SEEK_SET) || !SetEndOfFile(mFile))
return -1;
// Make sure we do not extend the file again.
_Seek(min(aLength, pos), SEEK_SET);
return _Length();
}
HANDLE Handle() { RollbackFilePointer(); FlushWriteBuffer(); return mFile; }
protected:
virtual bool _Open(LPCTSTR aFileSpec, DWORD &aFlags);
virtual void _Close();
virtual DWORD _Read(LPVOID aBuffer, DWORD aBufSize);
virtual DWORD _Write(LPCVOID aBuffer, DWORD aBufSize);
virtual bool _Seek(__int64 aDistance, int aOrigin);
virtual __int64 _Tell() const;
virtual __int64 _Length() const;
private:
HANDLE mFile;
};
// TextMem is intended to attach a memory block, which provides code pages and end-of-line conversions (CRLF <-> LF).
// It is used for reading the script data in compiled script.
// Note that TextMem doesn't have any ability to write and seek.
class TextMem : public TextStream
{
public:
// TextMem tmem;
// tmem.Open(TextMem::Buffer(buffer, length), EOL_CRLF, CP_ACP);
struct Buffer
{
Buffer(LPVOID aBuf = NULL, DWORD aBufLen = 0, bool aOwned = true)
: mBuffer((LPBYTE)aBuf), mLength(aBufLen), mOwned(aOwned)
{}
operator LPCTSTR() const { return (LPCTSTR) this; }
LPVOID mBuffer;
DWORD mLength;
bool mOwned; // If true, the memory will be freed by _Close().
};
TextMem()
{
mData.mBuffer = NULL;
mData.mLength = 0;
mData.mOwned = false;
mDataPos = NULL;
}
virtual ~TextMem() { _Close(); }
protected:
virtual bool _Open(LPCTSTR aFileSpec, DWORD &aFlags);
virtual void _Close();
virtual DWORD _Read(LPVOID aBuffer, DWORD aBufSize);
virtual DWORD _Write(LPCVOID aBuffer, DWORD aBufSize);
virtual bool _Seek(__int64 aDistance, int aOrigin);
virtual __int64 _Tell() const;
virtual __int64 _Length() const;
private:
Buffer mData;
LPBYTE mDataPos;
};
diff --git a/source/util.cpp b/source/util.cpp
index 6f29efb..d4e2740 100644
--- a/source/util.cpp
+++ b/source/util.cpp
@@ -2587,603 +2587,598 @@ LPTSTR ConvertEscapeSequences(LPTSTR aBuf, TCHAR aEscapeChar, bool aAllowEscaped
int FindNextDelimiter(LPCTSTR aBuf, TCHAR aDelimiter, int aStartIndex, LPCTSTR aLiteralMap)
// Returns the index of the next delimiter, taking into account quotes, parentheses, etc.
// If the delimiter is not found, returns the length of aBuf.
{
bool in_quotes = false;
int open_parens = 0;
for (int mark = aStartIndex; ; ++mark)
{
if (aBuf[mark] == aDelimiter)
{
if (!in_quotes && open_parens <= 0 && !(aLiteralMap && aLiteralMap[mark]))
// A delimiting comma other than one in a sub-statement or function.
return mark;
// Otherwise, its a quoted/literal comma or one in parentheses (such as function-call).
continue;
}
switch (aBuf[mark])
{
case '"': // There are sections similar this one later below; so see them for comments.
in_quotes = !in_quotes;
break;
case '(': // For our purpose, "(", "[" and "{" can be treated the same.
case '[': // If they aren't balanced properly, a later stage will detect it.
case '{': //
if (!in_quotes) // Literal parentheses inside a quoted string should not be counted for this purpose.
++open_parens;
break;
case ')':
case ']':
case '}':
if (!in_quotes)
--open_parens; // If this makes it negative, validation later on will catch the syntax error.
break;
case '\0':
// Reached the end of the string without finding a delimiter. Return the
// index of the null-terminator since that's typically what the caller wants.
return mark;
//default: some other character; just have the loop skip over it.
}
}
}
bool IsStringInList(LPTSTR aStr, LPTSTR aList, bool aFindExactMatch)
// Checks if aStr exists in aList (which is a comma-separated list).
// If aStr is blank, aList must start with a delimiting comma for there to be a match.
{
// Must use a temp. buffer because otherwise there's no easy way to properly match upon strings
// such as the following:
// if var in string,,with,,literal,,commas
TCHAR buf[LINE_SIZE];
TCHAR *next_field, *cp, *end_buf = buf + _countof(buf) - 1;
// v1.0.48.01: Performance improved by Lexikos.
for (TCHAR *this_field = aList; *this_field; this_field = next_field) // For each field in aList.
{
for (cp = buf, next_field = this_field; *next_field && cp < end_buf; ++cp, ++next_field) // For each char in the field, copy it over to temporary buffer.
{
if (*next_field == ',') // This is either a delimiter (,) or a literal comma (,,).
{
++next_field;
if (*next_field != ',') // It's "," instead of ",," so treat it as the end of this field.
break;
// Otherwise it's ",," and next_field now points at the second comma; so copy that comma
// over as a literal comma then continue copying.
}
*cp = *next_field;
}
// The end of this field has been reached (or reached the capacity of the buffer), so terminate the string
// in the buffer.
*cp = '\0';
if (*buf) // It is possible for this to be blank only for the first field. Example: if var in ,abc
{
if (aFindExactMatch)
{
if (!g_tcscmp(aStr, buf)) // Match found
return true;
}
else // Substring match
if (g_tcsstr(aStr, buf)) // Match found
return true;
}
else // First item in the list is the empty string.
if (aFindExactMatch) // In this case, this is a match if aStr is also blank.
{
if (!*aStr)
return true;
}
else // Empty string is always found as a substring in any other string.
return true;
} // for()
return false; // No match found.
}
LPTSTR InStrAny(LPTSTR aStr, LPTSTR aNeedle[], int aNeedleCount, size_t &aFoundLen)
{
// For each character in aStr:
for ( ; *aStr; ++aStr)
// For each needle:
for (int i = 0; i < aNeedleCount; ++i)
// For each character in this needle:
for (LPTSTR needle_pos = aNeedle[i], str_pos = aStr; ; ++needle_pos, ++str_pos)
{
if (!*needle_pos)
{
// All characters in needle matched aStr at this position, so we've
// found our string. If this needle is empty, it implicitly matches
// at the first position in the string.
aFoundLen = needle_pos - aNeedle[i];
return aStr;
}
// Otherwise, we haven't reached the end of the needle. If we've reached
// the end of aStr, *str_pos and *needle_pos won't match, so the check
// below will break out of the loop.
if (*needle_pos != *str_pos)
// Not a match: continue on to the next needle, or the next starting
// position in aStr if this is the last needle.
break;
}
// If the above loops completed without returning, no matches were found.
return NULL;
}
short IsDefaultType(LPTSTR aTypeDef){
static LPTSTR sTypeDef[8] = {_T(" CHAR UCHAR BOOLEAN BYTE ")
#ifndef _WIN64
,_T(" ATOM LANGID WCHAR WORD SHORT USHORT BYTE TCHAR HALF_PTR UHALF_PTR ")
#else
,_T(" ATOM LANGID WCHAR WORD SHORT USHORT BYTE TCHAR ")
#endif
,_T("")
#ifdef _WIN64
,_T(" INT UINT FLOAT INT32 LONG LONG32 HFILE HRESULT BOOL COLORREF DWORD DWORD32 LCID LCTYPE LGRPID LRESULT UINT32 ULONG ULONG32 HALF_PTR UHALF_PTR ")
#else
,_T(" INT UINT FLOAT INT32 LONG LONG32 HFILE HRESULT BOOL COLORREF DWORD DWORD32 LCID LCTYPE LGRPID LRESULT UINT32 ULONG ULONG32 PTR UPTR INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR PDWORD PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR DWORD_PTR HACCEL HANDLE HBITMAP HBRUSH HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP HENHMETAFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRGN HRSRC HSZ HWINSTA HWND LPARAM LPBOOL LPBYTE LPCOLORREF LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR LPVOID LPWORD LPWSTR PHANDLE PHKEY PINT PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 POINTER_UNSIGNED PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SIZE_T UINT_PTR ULONG_PTR VOID ")
#endif
,_T(""),_T(""),_T("")
#ifdef _WIN64
,_T(" INT64 UINT64 DOUBLE __int64 LONGLONG LONG64 USN DWORDLONG DWORD64 ULONGLONG ULONG64 PTR UPTR INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR PDWORD PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR DWORD_PTR HACCEL HANDLE HBITMAP HBRUSH HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP HENHMETAFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRGN HRSRC HSZ HWINSTA HWND LPARAM LPBOOL LPBYTE LPCOLORREF LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR LPVOID LPWORD LPWSTR PHANDLE PHKEY PINT PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 POINTER_UNSIGNED PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SIZE_T UINT_PTR ULONG_PTR VOID ")
#else
,_T(" INT64 UINT64 DOUBLE __int64 LONGLONG LONG64 USN DWORDLONG DWORD64 ULONGLONG ULONG64 ")
#endif
};
for (int i=0;i<8;i++)
{
if (tcscasestr(sTypeDef[i],aTypeDef))
return i + 1;
}
// type was not found
return NULL;
}
ResultType LoadDllFunction(LPTSTR parameter, LPTSTR aBuf)
{
LPTSTR aFuncName = omit_leading_whitespace(parameter);
// backup current function
// Func currentfunc = **g_script.mFunc;
if (!(parameter = _tcschr(parameter, ',')) || !*parameter)
return g_script.ScriptError(ERR_PARAM2_REQUIRED, aBuf);
else
parameter++;
if (_tcschr(aFuncName, ','))
*(_tcschr(aFuncName, ',')) = '\0';
ltrim(parameter);
int insert_pos;
Func *found_func = g_script.FindFunc(aFuncName, _tcslen(aFuncName), &insert_pos);
if (found_func)
return g_script.ScriptError(_T("Duplicate function definition."), aFuncName); // Seems more descriptive than "Function already defined."
else
if (!(found_func = g_script.AddFunc(aFuncName, _tcslen(aFuncName), false, insert_pos)))
return FAIL; // It already displayed the error.
void *function = NULL; // Will hold the address of the function to be called.
found_func->mBIF = (BuiltInFunctionType)BIF_DllImport;
found_func->mIsBuiltIn = true;
found_func->mMinParams = 0;
TCHAR buf[MAX_PATH];
size_t space_remaining = LINE_SIZE - (parameter - aBuf);
if (tcscasestr(parameter, _T("%A_ScriptDir%")))
{
BIV_ScriptDir(buf, _T("A_ScriptDir"));
StrReplace(parameter, _T("%A_ScriptDir%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_AppData%"))) // v1.0.45.04: This and the next were requested by Tekl to make it easier to customize scripts on a per-user basis.
{
BIV_SpecialFolderPath(buf, _T("A_AppData"));
StrReplace(parameter, _T("%A_AppData%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_AppDataCommon%"))) // v1.0.45.04.
{
BIV_SpecialFolderPath(buf, _T("A_AppDataCommon"));
StrReplace(parameter, _T("%A_AppDataCommon%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_AhkPath%"))) // v1.0.45.04.
{
BIV_AhkPath(buf, _T("A_AhkPath"));
StrReplace(parameter, _T("%A_AhkPath%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_AhkDir%"))) // v1.0.45.04.
{
BIV_AhkDir(buf, _T("A_AhkDir"));
StrReplace(parameter, _T("%A_AhkDir%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_DllDir%"))) // v1.0.45.04.
{
BIV_DllDir(buf, _T("A_DllDir"));
StrReplace(parameter, _T("%A_DllDir%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_DllPath%"))) // v1.0.45.04.
{
BIV_DllPath(buf, _T("A_DllPath"));
StrReplace(parameter, _T("%A_DllPath%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (_tcschr(parameter, '%'))
{
return g_script.ScriptError(_T("Reference not allowed here, use & where possible. Only %A_AhkPath% %A_AhkDir% %A_DllPath% %A_DllDir% %A_ScriptDir% %A_AppData[Common]% can be used here."), parameter);
}
// terminate dll\function name, find it and jump to next parameter
if (_tcschr(parameter, ','))
*(_tcschr(parameter, ',')) = '\0';
if (RegExMatch(parameter, _T("^\\s*[A-Fa-f0-9]+(:[A-Fa-f0-9]+)?\\s*$")))
{
TCHAR hex[4] = { '0', 'x' };
#ifdef _WIN64
if (_tcschr(parameter, ':'))
parameter = _tcschr(parameter, ':') + 1;
#endif
int end;
if (_tcschr(parameter, ':'))
end = (int)(_tcschr(parameter, ':') - parameter);
else
end = (int)_tcslen(parameter);
if (!(function = (void*)SimpleHeap::Malloc(end / 2)))
return g_script.ScriptError(ERR_OUTOFMEM, parameter);
if (!VirtualAlloc(function, end / 2, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
return g_script.ScriptError(_T("Could not commit memory for DllImport."), parameter);
for (int i = 0; i < end; i += 2)
{
_tcsncpy(&hex[2], parameter + i, 2);
*((char*)function + i / 2) = (char)_tcstol(hex, NULL, 16);
}
}
else
function = (void*)ATOI64(parameter);
if (!function)
{
LPTSTR dll_name = _tcsrchr(parameter, '\\');
if (dll_name)
{
*dll_name = '\0';
if (!GetModuleHandle(parameter))
LoadLibrary(parameter);
*dll_name = '\\';
}
function = (void*)GetDllProcAddress(parameter);
}
if (!function)
return g_script.ScriptError(ERR_NONEXISTENT_FUNCTION, parameter);
parameter = parameter + _tcslen(parameter) + 1;
LPTSTR parm = SimpleHeap::Malloc(parameter);
bool has_return = false;
int aParamCount = !*parm||ATOI(parm) ? 0 : 1;
if (*parm)
for (; _tcschr(parameter, ','); aParamCount++)
{
if (parameter = _tcschr(parameter, ','))
parameter++;
}
if (*parm && aParamCount < 1)
return g_script.ScriptError(ERR_PARAM3_REQUIRED, aBuf);
// Determine the type of return value.
DYNAPARM *return_attrib = (DYNAPARM*)SimpleHeap::Malloc(sizeof(DYNAPARM));
if (!return_attrib)
return g_script.ScriptError(ERR_OUTOFMEM);
memset(return_attrib, 0, sizeof(DYNAPARM)); // Init all to default in case ConvertDllArgType() isn't called below. This struct holds the type and other attributes of the function's return value.
#ifdef WIN32_PLATFORM
int dll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it.
#endif
if (!(aParamCount % 2)) // Even number of parameters indicates the return type has been omitted, so assume BOOL/INT.
return_attrib->type = DLL_ARG_INT;
else
{
// Check validity of this arg's return type:
LPTSTR return_type_string[2];
return_type_string[0] = omit_leading_whitespace(parameter);
return_type_string[1] = NULL; // Added in 1.0.48.
// 64-bit note: The calling convention detection code is preserved here for script compatibility.
if (!_tcsnicmp(return_type_string[0], _T("CDecl"), 5)) // Alternate calling convention.
{
#ifdef WIN32_PLATFORM
dll_call_mode = DC_CALL_CDECL;
#endif
return_type_string[0] = omit_leading_whitespace(return_type_string[0] + 5);
if (!*return_type_string[0])
{ // Take a shortcut since we know this empty string will be used as "Int":
return_attrib->type = DLL_ARG_INT;
goto has_valid_return_type;
}
}
ConvertDllArgType(return_type_string, *return_attrib);
if (return_attrib->type == DLL_ARG_INVALID)
return CONDITION_FALSE;
has_return = true;
has_valid_return_type:
aParamCount--;
#ifdef WIN32_PLATFORM
if (!return_attrib->passed_by_address) // i.e. the special return flags below are not needed when an address is being returned.
{
if (return_attrib->type == DLL_ARG_DOUBLE)
dll_call_mode |= DC_RETVAL_MATH8;
else if (return_attrib->type == DLL_ARG_FLOAT)
dll_call_mode |= DC_RETVAL_MATH4;
}
#endif
}
// Using stack memory, create an array of dll args large enough to hold the actual number of args present.
int arg_count = aParamCount / 2; // Might provide one extra due to first/last params, which is inconsequential.
DYNAPARM *dyna_param_def = arg_count ? (DYNAPARM *)SimpleHeap::Malloc(arg_count * sizeof(DYNAPARM)) : NULL;
DYNAPARM *dyna_param = arg_count ? (DYNAPARM *)SimpleHeap::Malloc(arg_count * sizeof(DYNAPARM)) : NULL;
if (arg_count && (!dyna_param_def || !dyna_param))
return g_script.ScriptError(ERR_OUTOFMEM);
// Above: _alloca() has been checked for code-bloat and it doesn't appear to be an issue.
// Above: Fix for v1.0.36.07: According to MSDN, on failure, this implementation of _alloca() generates a
// stack overflow exception rather than returning a NULL value. Therefore, NULL is no longer checked,
// nor is an exception block used since stack overflow in this case should be exceptionally rare (if it
// does happen, it would probably mean the script or the program has a design flaw somewhere, such as
// infinite recursion).
LPTSTR arg_type_string[2];
int i = arg_count * sizeof(void *);
// for Unicode <-> ANSI charset conversion
#ifdef UNICODE
CStringA **pStr = (CStringA **)
#else
CStringW **pStr = (CStringW **)
#endif
SimpleHeap::Malloc(i); // _alloca vs malloc can make a significant difference to performance in some cases.
if (i && !pStr)
return g_script.ScriptError(ERR_OUTOFMEM);
memset(pStr, 0, i);
// Above has already ensured that after the first parameter, there are either zero additional parameters
// or an even number of them. In other words, each arg type will have an arg value to go with it.
// It has also verified that the dyna_param array is large enough to hold all of the args.
LPTSTR this_param;
for (arg_count = 0, i = 1; i < aParamCount; ++arg_count, i += 2) // Same loop as used later below, so maintain them together.
{
this_param = _tcschr(parm, ',');
*this_param = '\0';
this_param++;
arg_type_string[0] = parm; // It will be detected as invalid below.
arg_type_string[1] = NULL;
//ExprTokenType &this_param = *aParam[i + 1]; // Resolved for performance and convenience.
DYNAPARM &this_dyna_param = dyna_param_def[arg_count]; //
// Store the each arg into a dyna_param struct, using its arg type to determine how.
ConvertDllArgType(arg_type_string, this_dyna_param);
switch (this_dyna_param.type)
{
case DLL_ARG_STR:
if (ATOI64(this_param))
{
// For now, string args must be real strings rather than floats or ints. An alternative
// to this would be to convert it to number using persistent memory from the caller (which
// is necessary because our own stack memory should not be passed to any function since
// that might cause it to return a pointer to stack memory, or update an output-parameter
// to be stack memory, which would be invalid memory upon return to the caller).
// The complexity of this doesn't seem worth the rarity of the need, so this will be
// documented in the help file.
return CONDITION_FALSE;
}
// Otherwise, it's a supported type of string.
this_dyna_param.ptr = this_param; // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions).
// NOTES ABOUT THE ABOVE:
// UPDATE: The v1.0.44.14 item below doesn't work in release mode, only debug mode (turning off
// "string pooling" doesn't help either). So it's commented out until a way is found
// to pass the address of a read-only empty string (if such a thing is possible in
// release mode). Such a string should have the following properties:
// 1) The first byte at its address should be '\0' so that functions can read it
// and recognize it as a valid empty string.
// 2) The memory address should be readable but not writable: it should throw an
// access violation if the function tries to write to it (like "" does in debug mode).
// SO INSTEAD of the following, DllCall() now checks further below for whether sEmptyString
// has been overwritten/trashed by the call, and if so displays a warning dialog.
// See note above about this: v1.0.44.14: If a variable is being passed that has no capacity, pass a
// read-only memory area instead of a writable empty string. There are two big benefits to this:
// 1) It forces an immediate exception (catchable by DllCall's exception handler) so
// that the program doesn't crash from memory corruption later on.
// 2) It avoids corrupting the program's static memory area (because sEmptyString
// resides there), which can save many hours of debugging for users when the program
// crashes on some seemingly unrelated line.
// Of course, it's not a complete solution because it doesn't stop a script from
// passing a variable whose capacity is non-zero yet too small to handle what the
// function will write to it. But it's a far cry better than nothing because it's
// common for a script to forget to call VarSetCapacity before passing a buffer to some
// function that writes a string to it.
//if (this_dyna_param.str == Var::sEmptyString) // To improve performance, compare directly to Var::sEmptyString rather than calling Capacity().
// this_dyna_param.str = _T(""); // Make it read-only to force an exception. See comments above.
break;
case DLL_ARG_xSTR:
// See the section above for comments.
if (ATOI64(this_param))
return CONDITION_FALSE;
// String needing translation: ASTR on Unicode build, WSTR on ANSI build.
pStr[arg_count] = new UorA(CStringCharFromWChar, CStringWCharFromChar)(this_param);
this_dyna_param.ptr = pStr[arg_count]->GetBuffer();
break;
case DLL_ARG_DOUBLE:
case DLL_ARG_FLOAT:
// This currently doesn't validate that this_dyna_param.is_unsigned==false, since it seems
// too rare and mostly harmless to worry about something like "Ufloat" having been specified.
this_dyna_param.value_double = ATOF(this_param);
if (this_dyna_param.type == DLL_ARG_FLOAT)
this_dyna_param.value_float = (float)this_dyna_param.value_double;
break;
case DLL_ARG_INVALID:
return CONDITION_FALSE;
default: // Namely:
//case DLL_ARG_INT:
//case DLL_ARG_SHORT:
//case DLL_ARG_CHAR:
//case DLL_ARG_INT64:
if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !ATOI64(this_param))
// The above and below also apply to BIF_NumPut(), so maintain them together.
// !IS_NUMERIC() is checked because such tokens are already signed values, so should be
// written out as signed so that whoever uses them can interpret negatives as large
// unsigned values.
// Support for unsigned values that are 32 bits wide or less is done via ATOI64() since
// it should be able to handle both signed and unsigned values. However, unsigned 64-bit
// values probably require ATOU64(), which will prevent something like -1 from being seen
// as the largest unsigned 64-bit int; but more importantly there are some other issues
// with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere,
// so unsigned values can only be partially supported for incoming parameters, but probably
// not for outgoing parameters (values the function changed) or the return value. Those
// should probably be written back out to the script as negatives so that other parts of
// the script, such as expressions, can see them as signed values. In other words, if the
// script somehow gets a 64-bit unsigned value into a variable, and that value is larger
// that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve
// it, but any output parameter should be written back out as a negative if it exceeds
// LLONG_MAX (return values can be written out as unsigned since the script can specify
// signed to avoid this, since they don't need the incoming detection for ATOU()).
this_dyna_param.value_int64 = (__int64)ATOU64(this_param); // Cast should not prevent called function from seeing it as an undamaged unsigned number.
else
this_dyna_param.value_int64 = ATOI64(this_param);
// Values less than or equal to 32-bits wide always get copied into a single 32-bit value
// because they should be right justified within it for insertion onto the call stack.
if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall().
this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below).
} // switch (this_dyna_param.type)
if ((parm = _tcschr(this_param, ',')))
*parm++ = '\0';
} // for() each arg.
if (has_return && aParamCount)
*(this_param) = '\0';
found_func->mClass = (Object*)function;
found_func->mParamCount = arg_count;
found_func->mVar = (Var**)return_attrib;
found_func->mStaticVar = (Var**)pStr;
found_func->mLazyVar = (Var**)dyna_param_def;
found_func->mParam = (FuncParam*)dyna_param;
#ifdef WIN32_PLATFORM
found_func->mVarCount = dll_call_mode;
#endif
return CONDITION_TRUE;
}
DWORD DecompressBuffer(void *aBuffer,LPVOID &aDataBuf, TCHAR *pwd[]) // LiteZip Raw compression
{
unsigned int hdrsz = 20;
TCHAR pw[1024] = {0};
if (pwd && pwd[0])
for(unsigned int i = 0;pwd[i];i++)
pw[i] = (TCHAR)*pwd[i];
ULONG aSizeCompressed = *(ULONG*)((UINT_PTR)aBuffer + 8);
DWORD aSizeEncrypted = *(DWORD*)((UINT_PTR)aBuffer + 16);
DWORD hash;
BYTE *aDataEncrypted = NULL;
HashData((LPBYTE)aBuffer + hdrsz,aSizeEncrypted?aSizeEncrypted:aSizeCompressed,(LPBYTE)&hash,4);
if (0x04034b50 == *(ULONG*)(UINT_PTR)aBuffer && hash == *(ULONG*)((UINT_PTR)aBuffer + 4))
{
HUNZIP huz;
ZIPENTRY ze;
DWORD result;
ULONG aSizeDeCompressed = *(ULONG*)((UINT_PTR)aBuffer + 12);
aDataBuf = VirtualAlloc(NULL, aSizeDeCompressed, MEM_COMMIT, PAGE_READWRITE);
if (aDataBuf)
{
+ DWORD aSizeDataEncrypted = 0;
if (aSizeEncrypted)
{
typedef BOOL (_stdcall *MyDecrypt)(HCRYPTKEY,HCRYPTHASH,BOOL,DWORD,BYTE*,DWORD*);
HMODULE advapi32 = LoadLibrary(_T("advapi32.dll"));
MyDecrypt Decrypt = (MyDecrypt)GetProcAddress(advapi32,"CryptDecrypt");
LPSTR aDataEncryptedString = (LPSTR)VirtualAlloc(NULL, aSizeEncrypted, MEM_COMMIT, PAGE_READWRITE);
+ aSizeDataEncrypted = aSizeEncrypted;
DWORD aSizeEncryptedString = aSizeEncrypted;
- DWORD aSizeEncryptedTemp = aSizeEncrypted;
HCRYPTPROV hProv;
HCRYPTKEY hKey;
HCRYPTHASH hHash;
CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_AES,CRYPT_VERIFYCONTEXT);
CryptCreateHash(hProv,CALG_SHA1,NULL,NULL,&hHash);
CryptHashData(hHash,(BYTE *) pw,(DWORD)_tcslen(pw) * sizeof(TCHAR),0);
CryptDeriveKey(hProv,CALG_AES_256,hHash,256<<16,&hKey);
CryptDestroyHash(hHash);
memmove(aDataEncryptedString,(LPBYTE)aBuffer + hdrsz,aSizeEncrypted);
- Decrypt(hKey,NULL,true,0,(BYTE*)aDataEncryptedString,&aSizeEncryptedString);
- CryptStringToBinaryA(aDataEncryptedString,NULL,CRYPT_STRING_BASE64,NULL,&aSizeEncryptedTemp,NULL,NULL);
- if (aSizeEncryptedTemp == 0)
+ Decrypt(hKey, NULL, true, 0, (BYTE*)aDataEncryptedString, &aSizeDataEncrypted);
+ CryptStringToBinaryA(aDataEncryptedString, NULL, CRYPT_STRING_BASE64, NULL, &aSizeEncryptedString, NULL, NULL);
+ if (aSizeEncryptedString == 0)
{ // incorrect password
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
- VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE);
+ VirtualFree(aDataEncryptedString, aSizeEncrypted, MEM_RELEASE);
return 0;
}
- aDataEncrypted = (BYTE*)VirtualAlloc(NULL, aSizeEncryptedTemp, MEM_COMMIT, PAGE_READWRITE);
- CryptStringToBinaryA(aDataEncryptedString,NULL,CRYPT_STRING_BASE64,aDataEncrypted,&aSizeEncryptedTemp,NULL,NULL);
+ aDataEncrypted = (BYTE*)VirtualAlloc(NULL, aSizeDataEncrypted = aSizeEncryptedString, MEM_COMMIT, PAGE_READWRITE);
+ CryptStringToBinaryA(aDataEncryptedString, NULL, CRYPT_STRING_BASE64, aDataEncrypted, &aSizeEncryptedString, NULL, NULL);
VirtualFree(aDataEncryptedString,aSizeEncrypted,MEM_RELEASE);
CryptDestroyKey(hKey);
CryptReleaseContext(hProv,0);
if (openArchive(&huz,(LPBYTE)aDataEncrypted, aSizeCompressed, ZIP_MEMORY|ZIP_RAW, 0))
{ // failed to open archive
closeArchive((TUNZIP *)huz);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
- VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE);
+ VirtualFree(aDataEncrypted, aSizeDataEncrypted, MEM_RELEASE);
return 0;
}
}
else if (openArchive(&huz,(LPBYTE)aBuffer + hdrsz, aSizeCompressed, ZIP_MEMORY|ZIP_RAW, 0))
{ // failed to open archive
closeArchive((TUNZIP *)huz);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
return 0;
}
ze.CompressedSize = aSizeDeCompressed;
ze.UncompressedSize = aSizeDeCompressed;
if ((result = unzipEntry((TUNZIP *)huz, aDataBuf, &ze, ZIP_MEMORY)))
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
else
{
closeArchive((TUNZIP *)huz);
if (aDataEncrypted)
- {
- SecureZeroMemory(aDataEncrypted, aSizeDeCompressed);
- VirtualFree(aDataEncrypted, aSizeDeCompressed, MEM_RELEASE);
- }
+ VirtualFree(aDataEncrypted, aSizeDataEncrypted, MEM_RELEASE);
return aSizeDeCompressed;
}
closeArchive((TUNZIP *)huz);
if (aDataEncrypted)
- {
- SecureZeroMemory(aDataEncrypted, aSizeDeCompressed);
- VirtualFree(aDataEncrypted, aSizeDeCompressed, MEM_RELEASE);
- }
+ VirtualFree(aDataEncrypted, aSizeDataEncrypted, MEM_RELEASE);
}
}
return 0;
}
#ifndef MINIDLL
LONG WINAPI DisableHooksOnException(PEXCEPTION_POINTERS pExceptionPtrs)
{
// Disable all hooks to avoid system/mouse freeze
if (pExceptionPtrs->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
&& pExceptionPtrs->ExceptionRecord->ExceptionFlags == EXCEPTION_NONCONTINUABLE)
AddRemoveHooks(0);
return EXCEPTION_CONTINUE_SEARCH;
}
#endif
#if defined(_MSC_VER) && defined(_DEBUG)
void OutputDebugStringFormat(LPCTSTR fmt, ...)
{
CString sMsg;
va_list ap;
va_start(ap, fmt);
sMsg.FormatV(fmt, ap);
OutputDebugString(sMsg);
}
#endif
|
tinku99/ahkdll
|
e28b6f43c23ece8d216b308c49ecd80ef68d6fb9
|
Zero memory in litezip
|
diff --git a/source/LiteUnzip.c b/source/LiteUnzip.c
index 17a3c86..900fd3f 100644
--- a/source/LiteUnzip.c
+++ b/source/LiteUnzip.c
@@ -1846,1611 +1846,1641 @@ static int inflate(Z_STREAM * z, int f)
z->state->mode = IM_DICT4;
}
case IM_DICT4:
{
IM_NEEDBYTE
z->state->sub.check.need = (ULG)IM_NEXTBYTE << 24;
z->state->mode = IM_DICT3;
}
case IM_DICT3:
{
IM_NEEDBYTE
z->state->sub.check.need += (ULG)IM_NEXTBYTE << 16;
z->state->mode = IM_DICT2;
}
case IM_DICT2:
{
IM_NEEDBYTE
z->state->sub.check.need += (ULG)IM_NEXTBYTE << 8;
z->state->mode = IM_DICT1;
}
case IM_DICT1:
{
IM_NEEDBYTE;
z->state->sub.check.need += (ULG)IM_NEXTBYTE;
// z->adler = z->state->sub.check.need;
z->state->mode = IM_DICT0;
return Z_NEED_DICT;
}
case IM_DICT0:
{
z->state->mode = IM_BAD;
#ifndef NDEBUG
z->msg = (char*)"need dictionary";
#endif
z->state->sub.marker = 0; // can try inflateSync
return Z_STREAM_ERROR;
}
case IM_BLOCKS:
{
r = inflate_blocks(z, r);
if (r == Z_DATA_ERROR)
{
z->state->mode = IM_BAD;
z->state->sub.marker = 0; // can try inflateSync
break;
}
if (r == Z_OK)
r = f;
if (r != Z_STREAM_END)
return r;
r = f;
inflate_blocks_reset(z);
// if (z->state->nowrap)
// {
z->state->mode = IM_DONE;
break;
// }
// z->state->mode = IM_CHECK4;
}
case IM_CHECK4:
{
IM_NEEDBYTE
z->state->sub.check.need = (ULG)IM_NEXTBYTE << 24;
z->state->mode = IM_CHECK3;
}
case IM_CHECK3:
{
IM_NEEDBYTE
z->state->sub.check.need += (ULG)IM_NEXTBYTE << 16;
z->state->mode = IM_CHECK2;
}
case IM_CHECK2:
{
IM_NEEDBYTE
z->state->sub.check.need += (ULG)IM_NEXTBYTE << 8;
z->state->mode = IM_CHECK1;
}
case IM_CHECK1:
{
IM_NEEDBYTE
z->state->sub.check.need += (ULG)IM_NEXTBYTE;
if (z->state->sub.check.was != z->state->sub.check.need)
{
z->state->mode = IM_BAD;
#ifndef NDEBUG
z->msg = (char*)"incorrect data check";
#endif
z->state->sub.marker = 5; // can't try inflateSync
break;
}
#ifndef NDEBUG
LuTracev((stderr, "inflate: zlib check ok\n"));
#endif
z->state->mode = IM_DONE;
}
case IM_DONE:
return(Z_STREAM_END);
case IM_BAD:
return(Z_DATA_ERROR);
default:
return(Z_STREAM_ERROR);
}
}
}
/********************** seekInZip() *********************
* Sets the current "file position" within the ZIP archive.
*/
static int seekInZip(TUNZIP *tunzip, long offset, DWORD reference)
{
if (!(tunzip->Flags & TZIP_ARCMEMORY))
{
if (reference == FILE_BEGIN) offset = SetFilePointer(tunzip->ArchivePtr, tunzip->InitialArchiveOffset + offset, 0, FILE_BEGIN);
else if (reference == FILE_CURRENT) offset = SetFilePointer(tunzip->ArchivePtr, offset, 0, FILE_CURRENT);
// else if (reference == FILE_END) offset = SetFilePointer(tunzip->ArchivePtr, offset, 0, FILE_END);
if (offset == -1) return(ZR_SEEK);
}
else
{
if (reference == FILE_BEGIN) tunzip->ArchiveBufPos = offset;
else if (reference == FILE_CURRENT) tunzip->ArchiveBufPos += offset;
// else if (reference == FILE_END) tunzip->ArchiveBufPos = tunzip->ArchiveBufLen + offset;
// if (tunzip->ArchiveBufPos > tunzip->ArchiveBufLen) tunzip->ArchiveBufPos = tunzip->ArchiveBufLen;
}
return(0);
}
/********************** readFromZip() *********************
* Reads the specified number of bytes from the ZIP archive
* (starting at the current position) and copies them to
* the specified buffer.
*
* RETURNS: The number of bytes actually read (could be less
* than the requested number if the end of file is reached)
* or 0 if no more bytes to read (or an error).
*
* NOTE: If an error, than TUNZIP->LastErr is non-zero.
*/
static DWORD readFromZip(TUNZIP *tunzip, void *ptr, DWORD toread)
{
// Reading from a handle?
if (!(tunzip->Flags & TZIP_ARCMEMORY))
{
DWORD readb;
if (!ReadFile(tunzip->ArchivePtr, ptr, toread, &readb, 0))
{
tunzip->LastErr = ZR_READ;
readb = 0;
}
return(readb);
}
// Reading from memory
if (tunzip->ArchiveBufPos + toread > tunzip->ArchiveBufLen) toread = tunzip->ArchiveBufLen - tunzip->ArchiveBufPos;
CopyMemory(ptr, (unsigned char *)tunzip->ArchivePtr + tunzip->ArchiveBufPos, toread);
tunzip->ArchiveBufPos += toread;
return(toread);
}
static unsigned char * reformat_short(unsigned char *ptr)
{
register unsigned short x;
x = (unsigned short)*ptr;
x |= (((unsigned short)*(ptr + 1)) << 8);
*((unsigned short *)ptr)++ = x;
return(ptr);
}
// Reads a short in LSB order from the given file.
static unsigned short getArchiveShort(TUNZIP *tunzip)
{
unsigned short x;
if (!tunzip->LastErr && readFromZip(tunzip, &x, sizeof(unsigned short)))
reformat_short((unsigned char *)&x);
return(x);
}
static unsigned char * reformat_long(unsigned char *ptr)
{
register unsigned long x;
x = (unsigned long)*ptr;
x |= (((unsigned long)*(ptr + 1)) << 8);
x |= (((unsigned long)*(ptr + 2)) << 16);
x |= (((unsigned long)*(ptr + 3)) << 24);
*((unsigned long *)ptr)++ = x;
return(ptr);
}
// Reads a long in LSB order from the given file
static ULG getArchiveLong(TUNZIP *tunzip)
{
ULG x;
x = 0;
if (!tunzip->LastErr && readFromZip(tunzip, &x, sizeof(ULG)))
reformat_long((unsigned char *)&x);
return(x);
}
/********************* skipToEntryEnd() *******************
* Skips the remainder of the currently selected entry's
* table in the ZIP archive.
*
* TUNZIP must be initialized to contain information about
* that entry via a call to goToFirstEntry() or goToNextEntry(),
* and getEntryInfo() must be called prior to this.
*
* NOTE: If an error, than TUNZIP->LastErr is set non-zero,
* so caller must clear it first if needed.
*/
/*
static void skipToEntryEnd(TUNZIP *tunzip, char **extraField)
{
register DWORD lSeek;
lSeek = tunzip->CurrentEntryInfo.size_file_extra;
// If he doesn't want extra info returned, then he wants to skip past the
// extra header, and comment fields. Otherwise, we read just the extra
// header (and don't bother skipping the comment). Caller is responsible
// for GlobalFree'ing the extra info
if (extraField)
{
char *extra;
if (!(extra = GlobalAlloc(GMEM_FIXED, lSeek)))
tunzip->LastErr = ZR_NOALLOC;
else
{
if (readFromZip(tunzip, extra, lSeek) != lSeek)
{
GlobalFree(extra);
goto bad;
}
*extraField = extra;
}
}
// Skip the extra header and comment
else if ((lSeek += tunzip->CurrentEntryInfo.size_file_comment) && seekInZip(tunzip, lSeek, FILE_CURRENT))
bad: tunzip->LastErr = ZR_CORRUPT;
}
*/
/********************* getEntryFN() *******************
* Gets the currently selected entry's filename in the
* zip archive.
*
* TUNZIP must be initialized to contain information about
* that entry via a call to goToFirstEntry() or goToNextEntry(),
* and getEntryInfo() must be called prior to this.
*
* NOTE: If an error, than TUNZIP->LastErr is set non-zero,
* so caller must clear it first if needed.
*/
static void getEntryFN(TUNZIP *tunzip, char *szFileName)
{
register DWORD uSizeRead;
register DWORD lSeek;
lSeek = tunzip->CurrentEntryInfo.size_filename;
// Make sure filename will fit in the supplied buffer (MAX_PATH)
if (lSeek < MAX_PATH)
uSizeRead = lSeek;
else
uSizeRead = MAX_PATH - 1;
// Read the filename
if (uSizeRead && readFromZip(tunzip, szFileName, uSizeRead) != uSizeRead)
bad: tunzip->LastErr = ZR_CORRUPT;
else
{
// If there are any bytes left that we didn't read, skip them
lSeek -= uSizeRead;
if (lSeek && seekInZip(tunzip, lSeek, FILE_CURRENT)) goto bad;
}
szFileName[uSizeRead] = 0;
}
/********************* getEntryInfo() *******************
* Gets info about the currently selected entry in the
* zip archive.
*
* TUNZIP must be initialized to contain information about
* that entry via a call to goToFirstEntry() or goToNextEntry().
*
* NOTE: If an error, than TUNZIP->LastErr is set non-zero,
* so caller must clear it first.
*/
static void getEntryInfo(register TUNZIP *tunzip)
{
DWORD uSizeRead;
DWORD lSeek;
// Seek to the start of this entry's info in the Central Directory
if (!seekInZip(tunzip, tunzip->CurrEntryPosInCentralDir + tunzip->ByteBeforeZipArchive, FILE_BEGIN))
{
if (tunzip->Flags & TZIP_GZIP)
{
BYTE flag, chr;
ZeroMemory(&tunzip->CurrentEntryInfo, sizeof(ZIPENTRYINFO));
if (tunzip->Flags & TZIP_RAW)
{
tunzip->CurrentEntryInfo.compression_method = Z_DEFLATED;
tunzip->CurrentEntryInfo.offset = tunzip->CurrEntryPosInCentralDir + tunzip->ByteBeforeZipArchive;
goto out;
}
if (readFromZip(tunzip, &flag, 1) != 1 ||
readFromZip(tunzip, &tunzip->CurrentEntryInfo.dosDate, 4) != 4 ||
seekInZip(tunzip, 2, FILE_CURRENT))
{
goto bad;
}
if ((flag & 0x04) && (readFromZip(tunzip, &tunzip->CurrentEntryInfo.disk_num_start, 2) != 2 || seekInZip(tunzip, tunzip->CurrentEntryInfo.disk_num_start, FILE_CURRENT))) goto bad;
// Save offset to filename
if (!(tunzip->Flags & TZIP_ARCMEMORY))
uSizeRead = SetFilePointer(tunzip->ArchivePtr, 0, 0, FILE_CURRENT);
else
uSizeRead = tunzip->ArchiveBufPos;
// Skip over filename, counting length
if (flag & 0x08)
{
for (;;)
{
if (readFromZip(tunzip, &chr, 1) != 1) goto bad;
if (!chr) break;
++tunzip->CurrentEntryInfo.size_filename;
}
}
// Skip over comment
if (flag & 0x10)
{
do
{
if (readFromZip(tunzip, &chr, 1) != 1) goto bad;
} while (chr);
}
// Skip compress info and OS bytes
if ((flag & 0x02) && seekInZip(tunzip, 2, FILE_CURRENT)) goto bad;
tunzip->CurrentEntryInfo.compression_method = Z_DEFLATED;
if (!(tunzip->Flags & TZIP_ARCMEMORY))
{
// Save offset to data
tunzip->CurrentEntryInfo.offset = SetFilePointer(tunzip->ArchivePtr, 0, 0, FILE_CURRENT);
tunzip->CurrentEntryInfo.compressed_size = SetFilePointer(tunzip->ArchivePtr, -8, 0, FILE_END) - tunzip->CurrentEntryInfo.offset;
tunzip->CurrentEntryInfo.crc = getArchiveLong(tunzip);
tunzip->CurrentEntryInfo.uncompressed_size = getArchiveLong(tunzip);
}
else
{
tunzip->CurrentEntryInfo.offset = tunzip->ArchiveBufPos;
tunzip->CurrentEntryInfo.compressed_size = tunzip->ArchiveBufLen - tunzip->ArchiveBufPos - 8;
CopyMemory((void *)tunzip->CurrentEntryInfo.crc, (unsigned char *)tunzip->ArchivePtr + tunzip->ArchiveBufLen - 8, 4);
reformat_long((unsigned char *)&tunzip->CurrentEntryInfo.crc);
CopyMemory((void *)tunzip->CurrentEntryInfo.uncompressed_size, (unsigned char *)tunzip->ArchivePtr + tunzip->ArchiveBufLen - 4, 4);
reformat_long((unsigned char *)&tunzip->CurrentEntryInfo.uncompressed_size);
}
// Seek to name offset upon return
seekInZip(tunzip, uSizeRead, FILE_BEGIN);
goto out;
}
// Get the ZIP signature and check it
uSizeRead = getArchiveLong(tunzip);
if (uSizeRead == 0x02014b50 &&
// Read in the ZIPENTRYINFO
readFromZip(tunzip, &tunzip->CurrentEntryInfo, sizeof(ZIPENTRYINFO)) == sizeof(ZIPENTRYINFO))
{
unsigned char *ptr;
// Adjust the various fields to this CPU's byte order
uSizeRead = ZIP_FIELDS_REFORMAT;
ptr = (unsigned char *)&tunzip->CurrentEntryInfo;
for (lSeek = 0; lSeek < NUM_FIELDS_REFORMAT; lSeek++)
{
if (0x00000001 & uSizeRead) ptr = reformat_long(ptr);
else ptr = reformat_short(ptr);
uSizeRead >>= 1;
}
out: return;
}
}
bad:
tunzip->LastErr = ZR_CORRUPT;
}
/******************** goToFirstEntry() *******************
* Set the current entry to the first entry in the ZIP
* archive.
*/
static void goToFirstEntry(register TUNZIP *tunzip)
{
if (tunzip->TotalEntries)
{
tunzip->CurrEntryPosInCentralDir = tunzip->CentralDirOffset;
tunzip->CurrentEntryNum = 0;
getEntryInfo(tunzip);
}
else
tunzip->LastErr = ZR_NOTFOUND;
}
/******************** goToNextEntry() *******************
* Set the current entry to the next entry in the ZIP
* archive.
*/
static void goToNextEntry(register TUNZIP *tunzip)
{
if (tunzip->CurrentEntryNum + 1 < tunzip->TotalEntries)
{
tunzip->CurrEntryPosInCentralDir += SIZECENTRALDIRITEM + tunzip->CurrentEntryInfo.size_filename + tunzip->CurrentEntryInfo.size_file_extra + tunzip->CurrentEntryInfo.size_file_comment;
++tunzip->CurrentEntryNum;
getEntryInfo(tunzip);
}
else
tunzip->LastErr = ZR_NOTFOUND;
}
/******************* inflateEnd() ********************
* Frees low level DEFLATE buffers/structs.
*
* NOTE: Must not alter TUNZIP->LastErr!
*/
static void inflateEnd(register ENTRYREADVARS *entryReadVars)
{
register void *ptr;
if (entryReadVars->stream.state)
{
switch (entryReadVars->stream.state->blocks.mode)
{
case IBM_BTREE:
case IBM_DTREE:
- if ((ptr = entryReadVars->stream.state->blocks.sub.trees.blens)) GlobalFree(ptr);
+ if ((ptr = entryReadVars->stream.state->blocks.sub.trees.blens))
+ {
+ SecureZeroMemory(ptr, GlobalSize(ptr));
+ GlobalFree(ptr);
+ }
break;
case IBM_CODES:
- if ((ptr = entryReadVars->stream.state->blocks.sub.decode.codes)) GlobalFree(ptr);
+ if ((ptr = entryReadVars->stream.state->blocks.sub.decode.codes))
+ {
+ SecureZeroMemory(ptr, GlobalSize(ptr));
+ GlobalFree(ptr);
+ }
}
- if ((ptr = entryReadVars->stream.state->blocks.window)) GlobalFree(ptr);
- if ((ptr = entryReadVars->stream.state->blocks.hufts)) GlobalFree(ptr);
-
+ if ((ptr = entryReadVars->stream.state->blocks.window))
+ {
+ SecureZeroMemory(ptr, GlobalSize(ptr));
+ GlobalFree(ptr);
+ }
+ if ((ptr = entryReadVars->stream.state->blocks.hufts))
+ {
+ SecureZeroMemory(ptr, GlobalSize(ptr));
+ GlobalFree(ptr);
+ }
+ SecureZeroMemory(entryReadVars->stream.state, GlobalSize(entryReadVars->stream.state));
GlobalFree(entryReadVars->stream.state);
#ifndef NDEBUG
LuTracev((stderr, "inflate: freed\n"));
#endif
}
}
/****************** cleanupEntry() ******************
* Frees resources allocated by initEntry().
*
* NOTE: Must not alter TUNZIP->LastErr!
*/
static void cleanupEntry(register TUNZIP * tunzip)
{
// Free the input buffer
- if (tunzip->EntryReadVars.InputBuffer) GlobalFree(tunzip->EntryReadVars.InputBuffer);
+ if (tunzip->EntryReadVars.InputBuffer)
+ {
+ SecureZeroMemory(tunzip->EntryReadVars.InputBuffer, GlobalSize(tunzip->EntryReadVars.InputBuffer));
+ GlobalFree(tunzip->EntryReadVars.InputBuffer);
+ }
tunzip->EntryReadVars.InputBuffer = 0;
// Free stuff allocated for decompressing in DEFLATE mode
if (tunzip->EntryReadVars.stream.state) inflateEnd(&tunzip->EntryReadVars);
tunzip->EntryReadVars.stream.state = 0;
// No currently selected entry
tunzip->CurrentEntryNum = (DWORD)-1;
}
/********************** initEntry() *********************
* Initializes structures in preparation of unzipping
* the current entry.
*
* NOTE: Sets TUNZIP->LastErr non-zero if an error, so this
* must be cleared before calling.
*/
static void initEntry(register TUNZIP *tunzip, ZIPENTRY *ze)
{
register DWORD offset;
// Clear out the ENTRYREADVARS struct
ZeroMemory(&tunzip->EntryReadVars, sizeof(ENTRYREADVARS));
// Get a read buffer to input, and decrypt, bytes from the ZIP archive
if (!(tunzip->EntryReadVars.InputBuffer = (unsigned char *)GlobalAlloc(GMEM_FIXED, UNZ_BUFSIZE)))
{
badalloc:
tunzip->LastErr = ZR_NOALLOC;
badout: cleanupEntry(tunzip);
return;
}
// If DEFLATE compression method, we need to get some resources for the deflate routines
if (tunzip->CurrentEntryInfo.compression_method)
{
if (!(tunzip->EntryReadVars.stream.state = (INTERNAL_STATE *)GlobalAlloc(GMEM_FIXED, sizeof(INTERNAL_STATE)))) goto badalloc;
ZeroMemory(tunzip->EntryReadVars.stream.state, sizeof(INTERNAL_STATE));
// MAX_WBITS: 32K LZ77 window
tunzip->EntryReadVars.stream.state->wbits = 15;
// Handle undocumented nowrap option (no zlib header or check)
// tunzip->EntryReadVars.stream->state.nowrap = 1;
tunzip->EntryReadVars.stream.state->mode = IM_BLOCKS;
// tunzip->EntryReadVars.stream.state->mode = tunzip->EntryReadVars.stream.state->nowrap ? IM_BLOCKS : IM_METHOD;
// Initialize INFLATE_BLOCKS_STATE
tunzip->EntryReadVars.stream.state->blocks.mode = IBM_TYPE;
if (!(tunzip->EntryReadVars.stream.state->blocks.hufts = (INFLATE_HUFT *)GlobalAlloc(GMEM_FIXED, sizeof(INFLATE_HUFT) * MANY))) goto badalloc;
if (!(tunzip->EntryReadVars.stream.state->blocks.window = (UCH *)GlobalAlloc(GMEM_FIXED, 1 << 15))) goto badalloc;
tunzip->EntryReadVars.stream.state->blocks.end = tunzip->EntryReadVars.stream.state->blocks.window + (1 << 15);
tunzip->EntryReadVars.stream.state->blocks.read = tunzip->EntryReadVars.stream.state->blocks.write = tunzip->EntryReadVars.stream.state->blocks.window;
#ifndef NDEBUG
LuTracev((stderr, "inflate: allocated\n"));
#endif
}
// If raw mode, app must supply the compressed and uncompressed sizes
if (tunzip->Flags & TZIP_RAW)
{
tunzip->CurrentEntryInfo.compressed_size = ze->CompressedSize;
tunzip->CurrentEntryInfo.uncompressed_size = ze->UncompressedSize;
}
// Initialize running counts
tunzip->EntryReadVars.RemainingCompressed = tunzip->CurrentEntryInfo.compressed_size;
tunzip->EntryReadVars.RemainingUncompressed = tunzip->CurrentEntryInfo.uncompressed_size;
// Initialize for CRC checksum
if (tunzip->CurrentEntryInfo.flag & 8) tunzip->EntryReadVars.CrcEncTest = (char)((tunzip->CurrentEntryInfo.dosDate >> 8) & 0xff);
else tunzip->EntryReadVars.CrcEncTest = (char)(tunzip->CurrentEntryInfo.crc >> 24);
if (tunzip->Flags & TZIP_GZIP)
offset = tunzip->CurrentEntryInfo.offset;
else
{
{
// Initialize encryption stuff
register const unsigned char *cp;
// Entry is encrypted?
if (tunzip->CurrentEntryInfo.flag & 1)
{
tunzip->EntryReadVars.RemainingEncrypt = 12; // There is an additional 12 bytes at the beginning of each local header
tunzip->EntryReadVars.Keys[0] = 305419896L;
tunzip->EntryReadVars.Keys[1] = 591751049L;
tunzip->EntryReadVars.Keys[2] = 878082192L;
if ((cp = tunzip->Password))
{
while(*cp) Uupdate_keys(&tunzip->EntryReadVars.Keys[0], *(cp)++);
}
}
}
{
unsigned short extra_offset;
// Seek to the entry's LOCALHEADER->extra_field_size
if (seekInZip(tunzip, tunzip->CurrentEntryInfo.offset + tunzip->ByteBeforeZipArchive + 28, FILE_BEGIN) ||
!readFromZip(tunzip, &extra_offset, sizeof(unsigned short)))
{
badseek: tunzip->LastErr = ZR_READ;
goto badout;
}
// Get the offset to where the entry's compressed data starts within the archive
// tunzip->EntryReadVars.PosInArchive = (DWORD)tunzip->CurrentEntryInfo.offset + SIZEZIPLOCALHEADER + (DWORD)tunzip->CurrentEntryInfo.size_filename + (DWORD)extra_offset;
offset = (DWORD)tunzip->CurrentEntryInfo.offset + SIZEZIPLOCALHEADER + (DWORD)tunzip->CurrentEntryInfo.size_filename + (DWORD)extra_offset;
}
}
// Seek so that a subsequent call to readEntry() will be at the correct position. (ie, We assume that
// the DEFLATE routines will not be seeking around within the archive while the entry is decompressed)
// if (seekInZip(tunzip, tunzip->EntryReadVars.PosInArchive, FILE_BEGIN)) goto badseek;
if (seekInZip(tunzip, offset, FILE_BEGIN)) goto badseek;
}
/************************* readEntry() **********************
* Reads bytes from the current position of the currently
* selected entry (within the archive), unencrypts them,
* and decompresses them into the passed buffer.
*
* buf = Pointer to buffer where data must be copied.
* len = The size of buf.
*
* RETURNS: The number of byte copied. Could be 0 if the
* end of file was reached. Sets TUNZIP->LastErr if an
* error.
*/
DWORD readEntry(register TUNZIP *tunzip, void *buf, DWORD len)
{
int err;
DWORD iRead;
iRead = 0;
tunzip->EntryReadVars.stream.next_out = (UCH *)buf;
// Caller is asking for more bytes than remaining? If so, just give him the
// remaining bytes
if (len > tunzip->EntryReadVars.RemainingUncompressed) len = tunzip->EntryReadVars.RemainingUncompressed;
tunzip->EntryReadVars.stream.avail_out = len;
// More room in the output buffer?
while (tunzip->EntryReadVars.stream.avail_out)
{
// Input buffer is empty? Fill it
if (!tunzip->EntryReadVars.stream.avail_in && tunzip->EntryReadVars.RemainingCompressed)
{
DWORD uReadThis;
// Fill up the input buffer, or read as much as is available
uReadThis = UNZ_BUFSIZE;
if (uReadThis > tunzip->EntryReadVars.RemainingCompressed) uReadThis = tunzip->EntryReadVars.RemainingCompressed;
// No more input (ie, done decompressing the entry)?
if (!uReadThis)
{
// Check that checksum works out to what we expected
if (tunzip->EntryReadVars.RunningCrc != tunzip->CurrentEntryInfo.crc)
tunzip->LastErr = ZR_FLATE;
none: return(0);
}
// Seek to where we last left off in the ZIP archive and fill the input buffer
if (!readFromZip(tunzip, tunzip->EntryReadVars.InputBuffer, uReadThis))
// if (seekInZip(tunzip, tunzip->EntryReadVars.PosInArchive + tunzip->ByteBeforeZipArchive, FILE_BEGIN) ||
// !readFromZip(tunzip, tunzip->EntryReadVars.InputBuffer, uReadThis))
{
tunzip->LastErr = ZR_READ;
goto none;
}
// Increment current position within archive
// tunzip->EntryReadVars.PosInArchive += uReadThis;
// Decrement remaining bytes to be decompressed
tunzip->EntryReadVars.RemainingCompressed -= uReadThis;
tunzip->EntryReadVars.stream.next_in = tunzip->EntryReadVars.InputBuffer;
tunzip->EntryReadVars.stream.avail_in = uReadThis;
// If encryption was applied, then decrypt the bytes
if (tunzip->CurrentEntryInfo.flag & 1)
{
DWORD i;
for (i=0; i < uReadThis; i++)
{
DWORD temp;
temp = ((DWORD)tunzip->EntryReadVars.Keys[2] & 0xffff) | 2;
tunzip->EntryReadVars.InputBuffer[i] ^= (char)(((temp * (temp ^ 1)) >> 8) & 0xff);
Uupdate_keys(&tunzip->EntryReadVars.Keys[0], tunzip->EntryReadVars.InputBuffer[i]);
}
}
}
// Read the encrpytion header that is at the start of the entry, if we haven't already done so
{
register DWORD uDoEncHead;
uDoEncHead = tunzip->EntryReadVars.RemainingEncrypt;
if (uDoEncHead > tunzip->EntryReadVars.stream.avail_in) uDoEncHead = tunzip->EntryReadVars.stream.avail_in;
if (uDoEncHead)
{
char bufcrc;
bufcrc = tunzip->EntryReadVars.stream.next_in[uDoEncHead - 1];
tunzip->EntryReadVars.RemainingUncompressed -= uDoEncHead;
tunzip->EntryReadVars.stream.avail_in -= uDoEncHead;
tunzip->EntryReadVars.stream.next_in += uDoEncHead;
tunzip->EntryReadVars.RemainingEncrypt -= uDoEncHead;
// If we've finished the encryption header, then do the CRC check with the password
if (!tunzip->EntryReadVars.RemainingEncrypt && bufcrc != tunzip->EntryReadVars.CrcEncTest)
{
tunzip->LastErr = ZR_PASSWORD;
goto none;
}
}
}
// STORE?
if (!tunzip->CurrentEntryInfo.compression_method)
{
DWORD uDoCopy;
if (tunzip->EntryReadVars.stream.avail_out < tunzip->EntryReadVars.stream.avail_in)
uDoCopy = tunzip->EntryReadVars.stream.avail_out;
else
uDoCopy = tunzip->EntryReadVars.stream.avail_in;
CopyMemory(tunzip->EntryReadVars.stream.next_out, tunzip->EntryReadVars.stream.next_in, uDoCopy);
tunzip->EntryReadVars.RunningCrc = ucrc32(tunzip->EntryReadVars.RunningCrc, tunzip->EntryReadVars.stream.next_out, uDoCopy);
tunzip->EntryReadVars.RemainingUncompressed -= uDoCopy;
tunzip->EntryReadVars.stream.avail_in -= uDoCopy;
tunzip->EntryReadVars.stream.avail_out -= uDoCopy;
tunzip->EntryReadVars.stream.next_out += uDoCopy;
tunzip->EntryReadVars.stream.next_in += uDoCopy;
tunzip->EntryReadVars.stream.total_out += uDoCopy;
iRead += uDoCopy;
if (!tunzip->EntryReadVars.RemainingUncompressed) break;
}
// DEFLATE
else
{
DWORD uTotalOutBefore,uTotalOutAfter;
const UCH *bufBefore;
DWORD uOutThis;
uTotalOutBefore = tunzip->EntryReadVars.stream.total_out;
bufBefore = tunzip->EntryReadVars.stream.next_out;
if ((err = inflate(&tunzip->EntryReadVars.stream, Z_SYNC_FLUSH)) && err != Z_STREAM_END)
{
tunzip->LastErr = ZR_FLATE;
goto none;
}
uTotalOutAfter = tunzip->EntryReadVars.stream.total_out;
uOutThis = uTotalOutAfter - uTotalOutBefore;
tunzip->EntryReadVars.RunningCrc = ucrc32(tunzip->EntryReadVars.RunningCrc, bufBefore, uOutThis);
tunzip->EntryReadVars.RemainingUncompressed -= uOutThis;
iRead += (uTotalOutAfter - uTotalOutBefore);
if (err == Z_STREAM_END || !tunzip->EntryReadVars.RemainingUncompressed) break;
}
}
return(iRead);
}
// Get the global comment string of the ZipFile, in the szComment buffer.
// uSizeBuf is the size of the szComment buffer.
// return the number of byte copied or an error code <0
/*
int unzGetGlobalComment(TUNZIP * tunzip, char *szComment, ULG uSizeBuf)
{
DWORD uReadThis;
uReadThis = uSizeBuf;
if (uReadThis > tunzip->CommentSize) uReadThis = tunzip->CommentSize;
if (seekInZip(tunzip, tunzip->CentralDirPos + 22, FILE_BEGIN)) return ZR_CORRUPT;
*szComment = 0;
if (readFromZip(tunzip, szComment, uReadThis) != uReadThis) return ZR_READ;
if (szComment && uSizeBuf > tunzip->CommentSize) *(szComment + tunzip->CommentSize) = 0;
return((int)uReadThis);
}
*/
/************************ findEntry() ***********************
* Locates an entry (within the archive) by name.
*
* flags = 1 (case-insensitive) perhaps OR'ed with ZIP_UNICODE.
* index = Where to return the index number of the located entry.
* ze = Where to return a filled in ZIPENTRY.
*
* NOTE: ZIPENTRY->Name[] must contain the name to match. This
* will be overwritten.
*
* RETURNS: ZR_OK if success, ZR_NOTFOUND if not located, or some
* other error.
*/
static DWORD findEntry(TUNZIP *tunzip, ZIPENTRY *ze, DWORD flags)
{
char name[MAX_PATH];
if (flags & ZIP_UNICODE)
WideCharToMultiByte(CP_UTF8, 0, (const WCHAR *)&ze->Name[0], -1, &name[0], MAX_PATH, 0, 0);
else
lstrcpyA(&name[0], (const char *)&ze->Name[0]);
if (lstrlenA(&name[0]) >= UNZ_MAXFILENAMEINZIP) return(ZR_ARGS);
{
register char *d;
// Next we need to replace '\' with '/' chars
d = name;
while (*d)
{
if (*d == '\\') *d = '/';
++d;
}
}
// If there's a currently selected entry, free it
cleanupEntry(tunzip);
// No error yet
tunzip->LastErr = 0;
// Start with first entry and read its table from the Central Directory
goToFirstEntry(tunzip);
while (!tunzip->LastErr)
{
// Get this entry's filename
getEntryFN(tunzip, (char *)&ze->Name[0]);
if (!tunzip->LastErr)
{
// Do names match?
if (!(flags & 0x01 ? lstrcmpiA(&name[0], (const char *)&ze->Name[0]) : lstrcmpA(&name[0], (const char *)&ze->Name[0])))
{
// Fill in caller's ZIPENTRY
ze->Index = tunzip->CurrentEntryNum;
return(setCurrentEntry(tunzip, ze, (flags & ZIP_UNICODE) | ZIP_ALREADYINIT));
}
goToNextEntry(tunzip);
/*
// Another entry?
if (tunzip->CurrentEntryNum + 1 < tunzip->TotalEntries)
{
// Skip the remainder of the current entry's table
skipToEntryEnd(tunzip, 0);
if (!tunzip->LastErr)
{
// Read the info for the next entry
tunzip->CurrEntryPosInCentralDir += SIZECENTRALDIRITEM + tunzip->CurrentEntryInfo.size_filename + tunzip->CurrentEntryInfo.size_file_extra + tunzip->CurrentEntryInfo.size_file_comment;
++tunzip->CurrentEntryNum;
getEntryInfo(tunzip);
}
}
else
tunzip->LastErr = ZR_NOTFOUND;
*/
}
}
cleanupEntry(tunzip);
return(tunzip->LastErr);
}
/********************** setCurrentEntry() *********************
* Sets the specified entry to the currently selected
* entry within the ZIP archive, and fills in the
* passed ZIPENTRY with information about that entry.
*
* tunzip = Handle returned by UnzipOpen*() functions.
* ze = Pointer to a ZIPENTRY to fill in.
* flags = One of the following:
* ZIP_ALREADYINIT - ZIPENTRY already filled
* in by a call to findEntry().
* ZIP_UNICODE - Caller's ZIPENTRY uses UNICODE name.
*
* RETURNS: Z_OK if success, otherwise an error code.
*
* NOTE: ZIPENTRY->Index must be set to the desired
* entry number before calling setCurrentEntry(). The value -1
* means to return how many entries are in the ZIP archive.
*/
static DWORD setCurrentEntry(register TUNZIP *tunzip, ZIPENTRY *ze, DWORD flags)
{
unsigned char *extra;
// No error yet
tunzip->LastErr = 0;
// Did findEntry() already init the ZIPENTRY?
if (!(flags & ZIP_ALREADYINIT))
{
// Does caller want general information about the ZIP archive?
if (ze->Index == (DWORD)-1)
{
ze->Index = tunzip->TotalEntries;
goto good;
}
// If there is currently a selected entry, free its resources
cleanupEntry(tunzip);
// Seek to the point in the ZIP archive where this entry is found
// and fill in the TUNZIP->CurrentEntryNum
if (ze->Index < tunzip->CurrentEntryNum) goToFirstEntry(tunzip);
while (!tunzip->LastErr && tunzip->CurrentEntryNum < ze->Index) goToNextEntry(tunzip);
if (tunzip->LastErr)
{
reterr: cleanupEntry(tunzip);
return(tunzip->LastErr);
}
// Get the entry's filename
getEntryFN(tunzip, (char *)&ze->Name[0]);
}
// We support only STORE and DEFLATE compression methods
if (tunzip->CurrentEntryInfo.compression_method && tunzip->CurrentEntryInfo.compression_method != Z_DEFLATED)
tunzip->LastErr = ZR_NOTSUPPORTED;
if (tunzip->LastErr) goto reterr;
// If raw mode, app must supply the compressed and uncompressed sizes
if (tunzip->Flags & TZIP_RAW) goto good2;
// Get the extra header (which may contain some extra timestamp stuff)
{
DWORD size;
extra = 0;
if ((size = tunzip->CurrentEntryInfo.size_file_extra))
{
if (!(extra = GlobalAlloc(GMEM_FIXED, size)))
{
tunzip->LastErr = ZR_NOALLOC;
goto reterr;
}
if (readFromZip(tunzip, extra, size) != size)
{
GlobalFree(extra);
tunzip->LastErr = ZR_CORRUPT;
goto reterr;
}
}
}
// Copy the entry's name to ZIPENTRY->name[] (UNICODE or ANSI)
{
register char *sfn;
register char *dfn;
char fn[MAX_PATH];
unsigned char previous;
// As a safety feature: if the zip filename had sneaky stuff like "c:\windows\file.txt" or
// "\windows\file.txt" or "fred\..\..\..\windows\file.txt" then we get rid of them all. That
// way, when the application does UnzipItem(), it won't be a problem. (If the
// programmer really does want to get the full evil information, then he can edit out this
// security feature below). In particular, we chop off any prefixes that are "c:\" or
// "\" or "/" or "[stuff]\.." or "[stuff]/.."
// Copy the root dir name
lstrcpyA(&fn[0], (const char *)&tunzip->Rootdir[0]);
// Prepare to append entry's name
sfn = &fn[0] + lstrlenA(&fn[0]);
dfn = (char *)&ze->Name[0];
// Skip the drive
if (dfn[0] && dfn[1] == ':') dfn += 2;
previous = DIRSLASH_CHAR; // Skip leading slashes
while (*dfn)
{
// Skip any "\..\" or "/../"
if (dfn[0] == '\\' || dfn[0] == '/')
{
dfn[0] = DIRSLASH_CHAR; // Change all '/' to '\' for Windows
if (dfn[1] == '.' && dfn[2] == '.' && (dfn[3] == '\\' || dfn[3] == '/'))
{
dfn += 4;
lstrcpyA(&fn[0], (const char *)&tunzip->Rootdir[0]);
sfn = &fn[0] + lstrlenA(&fn[0]);
previous = DIRSLASH_CHAR;
continue;
}
if (previous == DIRSLASH_CHAR)
{
previous = 0;
continue;
}
}
*(sfn)++ = previous = *(dfn)++;
}
*sfn = 0;
if (flags & ZIP_UNICODE)
{
MultiByteToWideChar(CP_UTF8, 0, &fn[0], -1, (WCHAR *)&ze->Name[0], MAX_PATH);
}
else
lstrcpyA((char *)&ze->Name[0], &fn[0]);
// Copy the attributes. zip has an 'attribute' 32bit value. Its lower half
// is windows stuff. Its upper half is standard unix stat.st_mode. We use the
// UNIX half, but in normal hostmodes these are overridden by the lower half
{
unsigned long host;
host = tunzip->CurrentEntryInfo.version >> 8;
if (!host || host==6 || host==10 || host==14)
ze->Attributes = tunzip->CurrentEntryInfo.external_fa & (FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_ARCHIVE);
else
{
ze->Attributes = FILE_ATTRIBUTE_ARCHIVE;
if (tunzip->CurrentEntryInfo.external_fa & 0x40000000) ze->Attributes = FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_DIRECTORY;
if (!(tunzip->CurrentEntryInfo.external_fa & 0x00800000)) ze->Attributes |= FILE_ATTRIBUTE_READONLY;
}
}
// Copy sizes
ze->CompressedSize = tunzip->CurrentEntryInfo.compressed_size;
ze->UncompressedSize = tunzip->CurrentEntryInfo.uncompressed_size;
// Copy timestamp
{
FILETIME ftd;
FILETIME ft;
dosdatetime2filetime(&ftd, (tunzip->CurrentEntryInfo.dosDate >> 16) & 0xFFFF, tunzip->CurrentEntryInfo.dosDate & 0xFFFF);
LocalFileTimeToFileTime(&ftd, &ft);
ze->AccessTime = ft;
ze->CreateTime = ft;
ze->ModifyTime = ft;
}
{
// the zip will always have at least that dostime. But if it also has
// an extra header, then we'll instead get the info from that
DWORD epos;
epos = 0;
while (epos + 4 < tunzip->CurrentEntryInfo.size_file_extra)
{
char etype[3];
DWORD flags;
int size;
etype[0] = extra[epos+0];
etype[1] = extra[epos+1];
etype[2] = 0;
size = extra[epos+2];
if (!lstrcmpA(etype, "UT"))
{
flags = extra[epos + 4];
epos += 5;
if ((flags & 1) && epos < tunzip->CurrentEntryInfo.size_file_extra)
{
lutime_t modifyTime = ((extra[epos+0])<<0) | ((extra[epos+1])<<8) |((extra[epos+2])<<16) | ((extra[epos+3])<<24);
timet2filetime(&ze->ModifyTime, modifyTime);
epos += 4;
}
if ((flags & 2) && epos < tunzip->CurrentEntryInfo.size_file_extra)
{
lutime_t accessTime = ((extra[epos+0])<<0) | ((extra[epos+1])<<8) |((extra[epos+2])<<16) | ((extra[epos+3])<<24);
timet2filetime(&ze->AccessTime, accessTime);
epos += 4;
}
if ((flags & 4) && epos < tunzip->CurrentEntryInfo.size_file_extra)
{
lutime_t createTime = ((extra[epos+0])<<0) | ((extra[epos+1])<<8) |((extra[epos+2])<<16) | ((extra[epos+3])<<24);
timet2filetime(&ze->CreateTime, createTime);
epos += 4;
}
break;
}
epos += 4 + size;
}
}
if (extra) GlobalFree(extra);
}
good2:
// We clear the internal_fa field as a signal to unzipEntry() that a memory-buffer unzip is
// starting for the first time
tunzip->CurrentEntryInfo.internal_fa = 0;
good:
return(ZR_OK);
}
/************************ str_chrA **********************
* Searches for the first occurence of 'chr' in
* nul-terminated 'str'. Same as C library's strchr().
*
* str = pointer to string to search
* chr = character to search for
*
* RETURNS: pointer to where 'chr' is found in 'str', or 0
* if not found.
*/
static char * str_chrA(char *str, char chr)
{
register char tempch;
if ((tempch = *str))
{
do
{
if (tempch == chr) return(str);
} while ((tempch = *(++str)));
}
// Not found
return(0);
}
/********************* createMultDirsA() *******************
* Creates as many dirs as are specified in the
* nul-terminated string pointed to by dirname.
*
* dirname = The names of directories to create, each
* separated by a backslash (but no backslash
* at the head or tail of the string).
*
* RETURNS: 1 if success, 0 if error.
*/
unsigned long createMultDirsA(char *dirname, BOOL isDir)
{
register char * ptr;
register char * pathbuf;
SECURITY_ATTRIBUTES sc;
sc.nLength = sizeof(SECURITY_ATTRIBUTES);
sc.lpSecurityDescriptor = 0;
sc.bInheritHandle = TRUE;
pathbuf = dirname;
// Skip drive
if (dirname[0] && dirname[1] == ':') dirname += 2;
if (dirname[0] == DIRSLASH_CHAR) ++dirname;
// Another sub-dir to create?
while (*dirname)
{
// Isolate next sub-dir name
if (!(ptr = str_chrA(dirname, DIRSLASH_CHAR)))
{
if (!isDir) break;
}
else
{
// Nul-term path
*ptr = 0;
}
if (!CreateDirectoryA(pathbuf, &sc) && GetLastError() != ERROR_ALREADY_EXISTS)
{
if (ptr) *ptr = DIRSLASH_CHAR;
return(0);
}
if (!ptr) break;
// Restore overwritten char
*ptr = DIRSLASH_CHAR;
dirname = ++ptr;
}
return(1);
}
/************************ str_chrW **********************
* Wide character version of str_chrA().
*/
static WCHAR * str_chrW(WCHAR *str, WCHAR chr)
{
register WCHAR ch;
if ((ch = *str))
{
do
{
if (ch == chr) return(str);
} while ((ch = *(++str)));
}
// Not found
return(0);
}
/********************* createMultDirsW *******************
* Wide character version of createMultDirsA().
*/
unsigned long createMultDirsW(WCHAR *dirname, BOOL isDir)
{
register WCHAR * ptr;
register WCHAR * pathbuf;
SECURITY_ATTRIBUTES sc;
sc.nLength = sizeof(SECURITY_ATTRIBUTES);
sc.lpSecurityDescriptor = 0;
sc.bInheritHandle = TRUE;
pathbuf = dirname;
// Skip drive
if (dirname[0] && dirname[1] == ':') dirname += 2;
if (dirname[0] == DIRSLASH_CHAR) ++dirname;
// Another sub-dir to create?
while (*dirname)
{
// Isolate next sub-dir name
if (!(ptr = str_chrW(dirname, DIRSLASH_CHAR)))
{
if (!isDir) break;
}
else
{
// Nul-term path
*ptr = 0;
}
if (!CreateDirectoryW(pathbuf, &sc) && GetLastError() != ERROR_ALREADY_EXISTS)
{
if (ptr) *ptr = DIRSLASH_CHAR;
return(0);
}
if (!ptr) break;
// Restore overwritten char
*ptr = DIRSLASH_CHAR;
dirname = ++ptr;
}
return(1);
}
/********************* unzipEntry() *******************
* Unzips the specified entry in the specified ZIP
* archive. Can be unzipped to a pipe/handle, disk file,
* or memory buffer.
*
* dst = Handle to file where the entry is decompressed,
* or filename, or memory buffer pointer.
* ze = Filled in ZIPENTRY struct.
* flags = ZIP_MEMORY, ZIP_FILENAME, or ZIP_HANDLE. Also
* may be ZIP_UNICODE.
*/
DWORD unzipEntry(register TUNZIP *tunzip, void *dst, ZIPENTRY *ze, DWORD flags)
{
HANDLE h;
// Make sure TUNZIP if valid
if (IsBadReadPtr(tunzip, 1) ||
// Make sure we have a currently selected entry
tunzip->CurrentEntryNum == (DWORD)-1)
{
return(ZR_ARGS);
}
// No error
tunzip->LastErr = 0;
// ============ Unzipping to memory ============
if (flags & ZIP_MEMORY)
{
// Don't reinitialize if this is called as a result of ZR_MORE
if (!tunzip->CurrentEntryInfo.internal_fa)
{
initEntry(tunzip, ze);
if (tunzip->LastErr) goto out;
tunzip->CurrentEntryInfo.internal_fa = 1;
}
ze->CompressedSize = readEntry(tunzip, dst, ze->CompressedSize);
+
if (tunzip->LastErr || !tunzip->EntryReadVars.RemainingUncompressed)
{
tunzip->CurrentEntryInfo.internal_fa = 0;
goto out;
}
// Filled the output buffer. Return ZR_MORE so the caller can flush it somewhere,
// but don't close the entry, and leave internal_fa set to 1
return(ZR_MORE);
}
// ============ Unzipping to disk/pipe ============
// Is this entry a directory name?
if (ze->Attributes & FILE_ATTRIBUTE_DIRECTORY)
{
// NOTE: We can't create a directory when spooling to a pipe
if (flags & ZIP_FILENAME)
{
if (flags & ZIP_UNICODE) flags = createMultDirsW((WCHAR *)dst, 1);
else flags = createMultDirsA((char *)dst, 1);
if (!flags) goto badf;
}
return(ZR_OK);
}
// Write the entry to a file/handle
if (flags == ZIP_HANDLE)
h = (HANDLE)dst;
else
{
DWORD res;
// Create any needed directories
if (flags & ZIP_UNICODE) res = createMultDirsW((WCHAR *)dst, 0);
else res = createMultDirsA((char *)dst, 0);
if (!res) goto badf;
// Create the file to which we'll write the uncompressed entry
if (flags & ZIP_UNICODE)
h = CreateFileW((WCHAR *)dst, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, ze->Attributes, 0);
else
h = CreateFileA((char *)dst, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, ze->Attributes, 0);
}
if (h == INVALID_HANDLE_VALUE)
badf: tunzip->LastErr = ZR_NOFILE;
else
{
// Allocate resources for decompressing
initEntry(tunzip, ze);
if (!tunzip->LastErr)
{
// Get an output buffer (where we decompress bytes)
if (!tunzip->OutBuffer && !(tunzip->OutBuffer = (unsigned char *)GlobalAlloc(GMEM_FIXED, 16384))) tunzip->LastErr = ZR_NOALLOC;
while (!tunzip->LastErr)
{
DWORD writ;
register DWORD read;
// Decompress the bytes into the input buffer. If EOF, then get out of this loop
if (!(read = readEntry(tunzip, tunzip->OutBuffer, 16384))) break;
// Write the bytes
if (!WriteFile(h, tunzip->OutBuffer, read, &writ, 0) || writ != read)
tunzip->LastErr = ZR_WRITE;
}
}
// Set the file's timestamp
if (!tunzip->LastErr)
SetFileTime(h, &ze->CreateTime, &ze->AccessTime, &ze->ModifyTime); // may fail if it was a pipe
// Close the file if we opened it above
if (flags != ZIP_HANDLE)
CloseHandle(h);
}
out:
cleanupEntry(tunzip);
return(tunzip->LastErr);
}
/********************* closeArchive() *****************
* Closes the ZIP archive opened with openArchive().
*/
void closeArchive(register TUNZIP *tunzip)
{
cleanupEntry(tunzip);
if (tunzip->Flags & TZIP_ARCCLOSEFH)
CloseHandle(tunzip->ArchivePtr);
- if (tunzip->Password) GlobalFree(tunzip->Password);
- if (tunzip->OutBuffer) GlobalFree(tunzip->OutBuffer);
+ if (tunzip->Password)
+ {
+ SecureZeroMemory(tunzip->Password, GlobalSize(tunzip->Password));
+ GlobalFree(tunzip->Password);
+ }
+ if (tunzip->OutBuffer)
+ {
+ SecureZeroMemory(tunzip->OutBuffer, GlobalSize(tunzip->OutBuffer));
+ GlobalFree(tunzip->OutBuffer);
+ }
+ SecureZeroMemory(tunzip, GlobalSize(tunzip));
GlobalFree(tunzip);
}
/******************* openArchive() ********************
* Opens a ZIP archive, in preparation of unzipping
* its entries.
*
* z = A handle, pointer to filename, or pointer to a
* memory buffer where the ZIP archive resides.
* len = If a memory buffer, its size.
* flags = ZIP_HANDLE, ZIP_FILENAME, or ZIP_MEMORY. Also,
* can be OR'd with ZIP_UNICODE.
*
* RETURNS: Z_OK if success, otherwise an error number.
*/
#define BUFREADCOMMENT (0x400)
DWORD openArchive(HANDLE *ptr, void *z, DWORD len, DWORD flags, const char *pwd)
{
register TUNZIP *tunzip;
DWORD centralDirPos;
// Get a TUNZIP
if (!(tunzip = (TUNZIP *)GlobalAlloc(GMEM_FIXED, sizeof(TUNZIP))))
return ZR_NOALLOC;
ZeroMemory(tunzip, sizeof(TUNZIP) - MAX_PATH);
// Store password if supplied
if (pwd)
{
if (!(tunzip->Password = (unsigned char *)GlobalAlloc(GMEM_FIXED, lstrlenA(pwd) + 1)))
{
GlobalFree(tunzip);
return flags;
}
lstrcpyA((char *)tunzip->Password, pwd);
}
// No currently selected entry
tunzip->CurrentEntryNum = (DWORD)-1;
// If buffer pointer is supplied, then he passed the ZIP archive
if ((tunzip->ArchivePtr = z))
tunzip->ArchiveBufLen = len;
else
return ZR_ARGS;
tunzip->Flags = TZIP_ARCMEMORY;
// If RAW flag, then it's assumed there is only one file in the archive, no central directory,
// and not even any GZIP indentification ID3 tag compression seems to be this way. Sigh... Wish
// some programmers put a little more thought into their dodgy file formats _before_ releasing
// code
ZeroMemory(&tunzip->CurrentEntryInfo, sizeof(ZIPENTRYINFO));
tunzip->CurrentEntryInfo.compression_method = Z_DEFLATED;
tunzip->CurrentEntryInfo.offset = tunzip->InitialArchiveOffset;
tunzip->Flags |= TZIP_RAW;
tunzip->CurrentEntryNum = 0;
tunzip->ByteBeforeZipArchive = tunzip->InitialArchiveOffset;
tunzip->LastErr = 0;
tunzip->Flags |= TZIP_GZIP;
tunzip->TotalEntries = 1;
// Set Rootdir to current directory. (Assume we unzip there)
if (!(centralDirPos = GetCurrentDirectoryA(MAX_PATH - 1, (LPSTR)&tunzip->Rootdir[0])) ||
tunzip->Rootdir[centralDirPos - 1] != '\\')
{
tunzip->Rootdir[centralDirPos++] = DIRSLASH_CHAR;
tunzip->Rootdir[centralDirPos] = 0;
}
// Return the TUNZIP
*ptr = tunzip;
return(ZR_OK);
}
\ No newline at end of file
diff --git a/source/util.cpp b/source/util.cpp
index cdb68a1..6f29efb 100644
--- a/source/util.cpp
+++ b/source/util.cpp
@@ -2639,545 +2639,551 @@ bool IsStringInList(LPTSTR aStr, LPTSTR aList, bool aFindExactMatch)
TCHAR buf[LINE_SIZE];
TCHAR *next_field, *cp, *end_buf = buf + _countof(buf) - 1;
// v1.0.48.01: Performance improved by Lexikos.
for (TCHAR *this_field = aList; *this_field; this_field = next_field) // For each field in aList.
{
for (cp = buf, next_field = this_field; *next_field && cp < end_buf; ++cp, ++next_field) // For each char in the field, copy it over to temporary buffer.
{
if (*next_field == ',') // This is either a delimiter (,) or a literal comma (,,).
{
++next_field;
if (*next_field != ',') // It's "," instead of ",," so treat it as the end of this field.
break;
// Otherwise it's ",," and next_field now points at the second comma; so copy that comma
// over as a literal comma then continue copying.
}
*cp = *next_field;
}
// The end of this field has been reached (or reached the capacity of the buffer), so terminate the string
// in the buffer.
*cp = '\0';
if (*buf) // It is possible for this to be blank only for the first field. Example: if var in ,abc
{
if (aFindExactMatch)
{
if (!g_tcscmp(aStr, buf)) // Match found
return true;
}
else // Substring match
if (g_tcsstr(aStr, buf)) // Match found
return true;
}
else // First item in the list is the empty string.
if (aFindExactMatch) // In this case, this is a match if aStr is also blank.
{
if (!*aStr)
return true;
}
else // Empty string is always found as a substring in any other string.
return true;
} // for()
return false; // No match found.
}
LPTSTR InStrAny(LPTSTR aStr, LPTSTR aNeedle[], int aNeedleCount, size_t &aFoundLen)
{
// For each character in aStr:
for ( ; *aStr; ++aStr)
// For each needle:
for (int i = 0; i < aNeedleCount; ++i)
// For each character in this needle:
for (LPTSTR needle_pos = aNeedle[i], str_pos = aStr; ; ++needle_pos, ++str_pos)
{
if (!*needle_pos)
{
// All characters in needle matched aStr at this position, so we've
// found our string. If this needle is empty, it implicitly matches
// at the first position in the string.
aFoundLen = needle_pos - aNeedle[i];
return aStr;
}
// Otherwise, we haven't reached the end of the needle. If we've reached
// the end of aStr, *str_pos and *needle_pos won't match, so the check
// below will break out of the loop.
if (*needle_pos != *str_pos)
// Not a match: continue on to the next needle, or the next starting
// position in aStr if this is the last needle.
break;
}
// If the above loops completed without returning, no matches were found.
return NULL;
}
short IsDefaultType(LPTSTR aTypeDef){
static LPTSTR sTypeDef[8] = {_T(" CHAR UCHAR BOOLEAN BYTE ")
#ifndef _WIN64
,_T(" ATOM LANGID WCHAR WORD SHORT USHORT BYTE TCHAR HALF_PTR UHALF_PTR ")
#else
,_T(" ATOM LANGID WCHAR WORD SHORT USHORT BYTE TCHAR ")
#endif
,_T("")
#ifdef _WIN64
,_T(" INT UINT FLOAT INT32 LONG LONG32 HFILE HRESULT BOOL COLORREF DWORD DWORD32 LCID LCTYPE LGRPID LRESULT UINT32 ULONG ULONG32 HALF_PTR UHALF_PTR ")
#else
,_T(" INT UINT FLOAT INT32 LONG LONG32 HFILE HRESULT BOOL COLORREF DWORD DWORD32 LCID LCTYPE LGRPID LRESULT UINT32 ULONG ULONG32 PTR UPTR INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR PDWORD PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR DWORD_PTR HACCEL HANDLE HBITMAP HBRUSH HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP HENHMETAFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRGN HRSRC HSZ HWINSTA HWND LPARAM LPBOOL LPBYTE LPCOLORREF LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR LPVOID LPWORD LPWSTR PHANDLE PHKEY PINT PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 POINTER_UNSIGNED PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SIZE_T UINT_PTR ULONG_PTR VOID ")
#endif
,_T(""),_T(""),_T("")
#ifdef _WIN64
,_T(" INT64 UINT64 DOUBLE __int64 LONGLONG LONG64 USN DWORDLONG DWORD64 ULONGLONG ULONG64 PTR UPTR INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR PDWORD PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR DWORD_PTR HACCEL HANDLE HBITMAP HBRUSH HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP HENHMETAFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRGN HRSRC HSZ HWINSTA HWND LPARAM LPBOOL LPBYTE LPCOLORREF LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR LPVOID LPWORD LPWSTR PHANDLE PHKEY PINT PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 POINTER_UNSIGNED PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SIZE_T UINT_PTR ULONG_PTR VOID ")
#else
,_T(" INT64 UINT64 DOUBLE __int64 LONGLONG LONG64 USN DWORDLONG DWORD64 ULONGLONG ULONG64 ")
#endif
};
for (int i=0;i<8;i++)
{
if (tcscasestr(sTypeDef[i],aTypeDef))
return i + 1;
}
// type was not found
return NULL;
}
ResultType LoadDllFunction(LPTSTR parameter, LPTSTR aBuf)
{
LPTSTR aFuncName = omit_leading_whitespace(parameter);
// backup current function
// Func currentfunc = **g_script.mFunc;
if (!(parameter = _tcschr(parameter, ',')) || !*parameter)
return g_script.ScriptError(ERR_PARAM2_REQUIRED, aBuf);
else
parameter++;
if (_tcschr(aFuncName, ','))
*(_tcschr(aFuncName, ',')) = '\0';
ltrim(parameter);
int insert_pos;
Func *found_func = g_script.FindFunc(aFuncName, _tcslen(aFuncName), &insert_pos);
if (found_func)
return g_script.ScriptError(_T("Duplicate function definition."), aFuncName); // Seems more descriptive than "Function already defined."
else
if (!(found_func = g_script.AddFunc(aFuncName, _tcslen(aFuncName), false, insert_pos)))
return FAIL; // It already displayed the error.
void *function = NULL; // Will hold the address of the function to be called.
found_func->mBIF = (BuiltInFunctionType)BIF_DllImport;
found_func->mIsBuiltIn = true;
found_func->mMinParams = 0;
TCHAR buf[MAX_PATH];
size_t space_remaining = LINE_SIZE - (parameter - aBuf);
if (tcscasestr(parameter, _T("%A_ScriptDir%")))
{
BIV_ScriptDir(buf, _T("A_ScriptDir"));
StrReplace(parameter, _T("%A_ScriptDir%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_AppData%"))) // v1.0.45.04: This and the next were requested by Tekl to make it easier to customize scripts on a per-user basis.
{
BIV_SpecialFolderPath(buf, _T("A_AppData"));
StrReplace(parameter, _T("%A_AppData%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_AppDataCommon%"))) // v1.0.45.04.
{
BIV_SpecialFolderPath(buf, _T("A_AppDataCommon"));
StrReplace(parameter, _T("%A_AppDataCommon%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_AhkPath%"))) // v1.0.45.04.
{
BIV_AhkPath(buf, _T("A_AhkPath"));
StrReplace(parameter, _T("%A_AhkPath%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_AhkDir%"))) // v1.0.45.04.
{
BIV_AhkDir(buf, _T("A_AhkDir"));
StrReplace(parameter, _T("%A_AhkDir%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_DllDir%"))) // v1.0.45.04.
{
BIV_DllDir(buf, _T("A_DllDir"));
StrReplace(parameter, _T("%A_DllDir%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_DllPath%"))) // v1.0.45.04.
{
BIV_DllPath(buf, _T("A_DllPath"));
StrReplace(parameter, _T("%A_DllPath%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (_tcschr(parameter, '%'))
{
return g_script.ScriptError(_T("Reference not allowed here, use & where possible. Only %A_AhkPath% %A_AhkDir% %A_DllPath% %A_DllDir% %A_ScriptDir% %A_AppData[Common]% can be used here."), parameter);
}
// terminate dll\function name, find it and jump to next parameter
if (_tcschr(parameter, ','))
*(_tcschr(parameter, ',')) = '\0';
if (RegExMatch(parameter, _T("^\\s*[A-Fa-f0-9]+(:[A-Fa-f0-9]+)?\\s*$")))
{
TCHAR hex[4] = { '0', 'x' };
#ifdef _WIN64
if (_tcschr(parameter, ':'))
parameter = _tcschr(parameter, ':') + 1;
#endif
int end;
if (_tcschr(parameter, ':'))
end = (int)(_tcschr(parameter, ':') - parameter);
else
end = (int)_tcslen(parameter);
if (!(function = (void*)SimpleHeap::Malloc(end / 2)))
return g_script.ScriptError(ERR_OUTOFMEM, parameter);
if (!VirtualAlloc(function, end / 2, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
return g_script.ScriptError(_T("Could not commit memory for DllImport."), parameter);
for (int i = 0; i < end; i += 2)
{
_tcsncpy(&hex[2], parameter + i, 2);
*((char*)function + i / 2) = (char)_tcstol(hex, NULL, 16);
}
}
else
function = (void*)ATOI64(parameter);
if (!function)
{
LPTSTR dll_name = _tcsrchr(parameter, '\\');
if (dll_name)
{
*dll_name = '\0';
if (!GetModuleHandle(parameter))
LoadLibrary(parameter);
*dll_name = '\\';
}
function = (void*)GetDllProcAddress(parameter);
}
if (!function)
return g_script.ScriptError(ERR_NONEXISTENT_FUNCTION, parameter);
parameter = parameter + _tcslen(parameter) + 1;
LPTSTR parm = SimpleHeap::Malloc(parameter);
bool has_return = false;
int aParamCount = !*parm||ATOI(parm) ? 0 : 1;
if (*parm)
for (; _tcschr(parameter, ','); aParamCount++)
{
if (parameter = _tcschr(parameter, ','))
parameter++;
}
if (*parm && aParamCount < 1)
return g_script.ScriptError(ERR_PARAM3_REQUIRED, aBuf);
// Determine the type of return value.
DYNAPARM *return_attrib = (DYNAPARM*)SimpleHeap::Malloc(sizeof(DYNAPARM));
if (!return_attrib)
return g_script.ScriptError(ERR_OUTOFMEM);
memset(return_attrib, 0, sizeof(DYNAPARM)); // Init all to default in case ConvertDllArgType() isn't called below. This struct holds the type and other attributes of the function's return value.
#ifdef WIN32_PLATFORM
int dll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it.
#endif
if (!(aParamCount % 2)) // Even number of parameters indicates the return type has been omitted, so assume BOOL/INT.
return_attrib->type = DLL_ARG_INT;
else
{
// Check validity of this arg's return type:
LPTSTR return_type_string[2];
return_type_string[0] = omit_leading_whitespace(parameter);
return_type_string[1] = NULL; // Added in 1.0.48.
// 64-bit note: The calling convention detection code is preserved here for script compatibility.
if (!_tcsnicmp(return_type_string[0], _T("CDecl"), 5)) // Alternate calling convention.
{
#ifdef WIN32_PLATFORM
dll_call_mode = DC_CALL_CDECL;
#endif
return_type_string[0] = omit_leading_whitespace(return_type_string[0] + 5);
if (!*return_type_string[0])
{ // Take a shortcut since we know this empty string will be used as "Int":
return_attrib->type = DLL_ARG_INT;
goto has_valid_return_type;
}
}
ConvertDllArgType(return_type_string, *return_attrib);
if (return_attrib->type == DLL_ARG_INVALID)
return CONDITION_FALSE;
has_return = true;
has_valid_return_type:
aParamCount--;
#ifdef WIN32_PLATFORM
if (!return_attrib->passed_by_address) // i.e. the special return flags below are not needed when an address is being returned.
{
if (return_attrib->type == DLL_ARG_DOUBLE)
dll_call_mode |= DC_RETVAL_MATH8;
else if (return_attrib->type == DLL_ARG_FLOAT)
dll_call_mode |= DC_RETVAL_MATH4;
}
#endif
}
// Using stack memory, create an array of dll args large enough to hold the actual number of args present.
int arg_count = aParamCount / 2; // Might provide one extra due to first/last params, which is inconsequential.
DYNAPARM *dyna_param_def = arg_count ? (DYNAPARM *)SimpleHeap::Malloc(arg_count * sizeof(DYNAPARM)) : NULL;
DYNAPARM *dyna_param = arg_count ? (DYNAPARM *)SimpleHeap::Malloc(arg_count * sizeof(DYNAPARM)) : NULL;
if (arg_count && (!dyna_param_def || !dyna_param))
return g_script.ScriptError(ERR_OUTOFMEM);
// Above: _alloca() has been checked for code-bloat and it doesn't appear to be an issue.
// Above: Fix for v1.0.36.07: According to MSDN, on failure, this implementation of _alloca() generates a
// stack overflow exception rather than returning a NULL value. Therefore, NULL is no longer checked,
// nor is an exception block used since stack overflow in this case should be exceptionally rare (if it
// does happen, it would probably mean the script or the program has a design flaw somewhere, such as
// infinite recursion).
LPTSTR arg_type_string[2];
int i = arg_count * sizeof(void *);
// for Unicode <-> ANSI charset conversion
#ifdef UNICODE
CStringA **pStr = (CStringA **)
#else
CStringW **pStr = (CStringW **)
#endif
SimpleHeap::Malloc(i); // _alloca vs malloc can make a significant difference to performance in some cases.
if (i && !pStr)
return g_script.ScriptError(ERR_OUTOFMEM);
memset(pStr, 0, i);
// Above has already ensured that after the first parameter, there are either zero additional parameters
// or an even number of them. In other words, each arg type will have an arg value to go with it.
// It has also verified that the dyna_param array is large enough to hold all of the args.
LPTSTR this_param;
for (arg_count = 0, i = 1; i < aParamCount; ++arg_count, i += 2) // Same loop as used later below, so maintain them together.
{
this_param = _tcschr(parm, ',');
*this_param = '\0';
this_param++;
arg_type_string[0] = parm; // It will be detected as invalid below.
arg_type_string[1] = NULL;
//ExprTokenType &this_param = *aParam[i + 1]; // Resolved for performance and convenience.
DYNAPARM &this_dyna_param = dyna_param_def[arg_count]; //
// Store the each arg into a dyna_param struct, using its arg type to determine how.
ConvertDllArgType(arg_type_string, this_dyna_param);
switch (this_dyna_param.type)
{
case DLL_ARG_STR:
if (ATOI64(this_param))
{
// For now, string args must be real strings rather than floats or ints. An alternative
// to this would be to convert it to number using persistent memory from the caller (which
// is necessary because our own stack memory should not be passed to any function since
// that might cause it to return a pointer to stack memory, or update an output-parameter
// to be stack memory, which would be invalid memory upon return to the caller).
// The complexity of this doesn't seem worth the rarity of the need, so this will be
// documented in the help file.
return CONDITION_FALSE;
}
// Otherwise, it's a supported type of string.
this_dyna_param.ptr = this_param; // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions).
// NOTES ABOUT THE ABOVE:
// UPDATE: The v1.0.44.14 item below doesn't work in release mode, only debug mode (turning off
// "string pooling" doesn't help either). So it's commented out until a way is found
// to pass the address of a read-only empty string (if such a thing is possible in
// release mode). Such a string should have the following properties:
// 1) The first byte at its address should be '\0' so that functions can read it
// and recognize it as a valid empty string.
// 2) The memory address should be readable but not writable: it should throw an
// access violation if the function tries to write to it (like "" does in debug mode).
// SO INSTEAD of the following, DllCall() now checks further below for whether sEmptyString
// has been overwritten/trashed by the call, and if so displays a warning dialog.
// See note above about this: v1.0.44.14: If a variable is being passed that has no capacity, pass a
// read-only memory area instead of a writable empty string. There are two big benefits to this:
// 1) It forces an immediate exception (catchable by DllCall's exception handler) so
// that the program doesn't crash from memory corruption later on.
// 2) It avoids corrupting the program's static memory area (because sEmptyString
// resides there), which can save many hours of debugging for users when the program
// crashes on some seemingly unrelated line.
// Of course, it's not a complete solution because it doesn't stop a script from
// passing a variable whose capacity is non-zero yet too small to handle what the
// function will write to it. But it's a far cry better than nothing because it's
// common for a script to forget to call VarSetCapacity before passing a buffer to some
// function that writes a string to it.
//if (this_dyna_param.str == Var::sEmptyString) // To improve performance, compare directly to Var::sEmptyString rather than calling Capacity().
// this_dyna_param.str = _T(""); // Make it read-only to force an exception. See comments above.
break;
case DLL_ARG_xSTR:
// See the section above for comments.
if (ATOI64(this_param))
return CONDITION_FALSE;
// String needing translation: ASTR on Unicode build, WSTR on ANSI build.
pStr[arg_count] = new UorA(CStringCharFromWChar, CStringWCharFromChar)(this_param);
this_dyna_param.ptr = pStr[arg_count]->GetBuffer();
break;
case DLL_ARG_DOUBLE:
case DLL_ARG_FLOAT:
// This currently doesn't validate that this_dyna_param.is_unsigned==false, since it seems
// too rare and mostly harmless to worry about something like "Ufloat" having been specified.
this_dyna_param.value_double = ATOF(this_param);
if (this_dyna_param.type == DLL_ARG_FLOAT)
this_dyna_param.value_float = (float)this_dyna_param.value_double;
break;
case DLL_ARG_INVALID:
return CONDITION_FALSE;
default: // Namely:
//case DLL_ARG_INT:
//case DLL_ARG_SHORT:
//case DLL_ARG_CHAR:
//case DLL_ARG_INT64:
if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !ATOI64(this_param))
// The above and below also apply to BIF_NumPut(), so maintain them together.
// !IS_NUMERIC() is checked because such tokens are already signed values, so should be
// written out as signed so that whoever uses them can interpret negatives as large
// unsigned values.
// Support for unsigned values that are 32 bits wide or less is done via ATOI64() since
// it should be able to handle both signed and unsigned values. However, unsigned 64-bit
// values probably require ATOU64(), which will prevent something like -1 from being seen
// as the largest unsigned 64-bit int; but more importantly there are some other issues
// with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere,
// so unsigned values can only be partially supported for incoming parameters, but probably
// not for outgoing parameters (values the function changed) or the return value. Those
// should probably be written back out to the script as negatives so that other parts of
// the script, such as expressions, can see them as signed values. In other words, if the
// script somehow gets a 64-bit unsigned value into a variable, and that value is larger
// that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve
// it, but any output parameter should be written back out as a negative if it exceeds
// LLONG_MAX (return values can be written out as unsigned since the script can specify
// signed to avoid this, since they don't need the incoming detection for ATOU()).
this_dyna_param.value_int64 = (__int64)ATOU64(this_param); // Cast should not prevent called function from seeing it as an undamaged unsigned number.
else
this_dyna_param.value_int64 = ATOI64(this_param);
// Values less than or equal to 32-bits wide always get copied into a single 32-bit value
// because they should be right justified within it for insertion onto the call stack.
if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall().
this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below).
} // switch (this_dyna_param.type)
if ((parm = _tcschr(this_param, ',')))
*parm++ = '\0';
} // for() each arg.
if (has_return && aParamCount)
*(this_param) = '\0';
found_func->mClass = (Object*)function;
found_func->mParamCount = arg_count;
found_func->mVar = (Var**)return_attrib;
found_func->mStaticVar = (Var**)pStr;
found_func->mLazyVar = (Var**)dyna_param_def;
found_func->mParam = (FuncParam*)dyna_param;
#ifdef WIN32_PLATFORM
found_func->mVarCount = dll_call_mode;
#endif
return CONDITION_TRUE;
}
DWORD DecompressBuffer(void *aBuffer,LPVOID &aDataBuf, TCHAR *pwd[]) // LiteZip Raw compression
{
unsigned int hdrsz = 20;
TCHAR pw[1024] = {0};
if (pwd && pwd[0])
for(unsigned int i = 0;pwd[i];i++)
pw[i] = (TCHAR)*pwd[i];
ULONG aSizeCompressed = *(ULONG*)((UINT_PTR)aBuffer + 8);
DWORD aSizeEncrypted = *(DWORD*)((UINT_PTR)aBuffer + 16);
DWORD hash;
BYTE *aDataEncrypted = NULL;
HashData((LPBYTE)aBuffer + hdrsz,aSizeEncrypted?aSizeEncrypted:aSizeCompressed,(LPBYTE)&hash,4);
if (0x04034b50 == *(ULONG*)(UINT_PTR)aBuffer && hash == *(ULONG*)((UINT_PTR)aBuffer + 4))
{
HUNZIP huz;
ZIPENTRY ze;
DWORD result;
ULONG aSizeDeCompressed = *(ULONG*)((UINT_PTR)aBuffer + 12);
aDataBuf = VirtualAlloc(NULL, aSizeDeCompressed, MEM_COMMIT, PAGE_READWRITE);
if (aDataBuf)
{
if (aSizeEncrypted)
{
typedef BOOL (_stdcall *MyDecrypt)(HCRYPTKEY,HCRYPTHASH,BOOL,DWORD,BYTE*,DWORD*);
HMODULE advapi32 = LoadLibrary(_T("advapi32.dll"));
MyDecrypt Decrypt = (MyDecrypt)GetProcAddress(advapi32,"CryptDecrypt");
LPSTR aDataEncryptedString = (LPSTR)VirtualAlloc(NULL, aSizeEncrypted, MEM_COMMIT, PAGE_READWRITE);
DWORD aSizeEncryptedString = aSizeEncrypted;
DWORD aSizeEncryptedTemp = aSizeEncrypted;
HCRYPTPROV hProv;
HCRYPTKEY hKey;
HCRYPTHASH hHash;
CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_AES,CRYPT_VERIFYCONTEXT);
CryptCreateHash(hProv,CALG_SHA1,NULL,NULL,&hHash);
CryptHashData(hHash,(BYTE *) pw,(DWORD)_tcslen(pw) * sizeof(TCHAR),0);
CryptDeriveKey(hProv,CALG_AES_256,hHash,256<<16,&hKey);
CryptDestroyHash(hHash);
memmove(aDataEncryptedString,(LPBYTE)aBuffer + hdrsz,aSizeEncrypted);
Decrypt(hKey,NULL,true,0,(BYTE*)aDataEncryptedString,&aSizeEncryptedString);
CryptStringToBinaryA(aDataEncryptedString,NULL,CRYPT_STRING_BASE64,NULL,&aSizeEncryptedTemp,NULL,NULL);
if (aSizeEncryptedTemp == 0)
{ // incorrect password
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE);
return 0;
}
aDataEncrypted = (BYTE*)VirtualAlloc(NULL, aSizeEncryptedTemp, MEM_COMMIT, PAGE_READWRITE);
CryptStringToBinaryA(aDataEncryptedString,NULL,CRYPT_STRING_BASE64,aDataEncrypted,&aSizeEncryptedTemp,NULL,NULL);
VirtualFree(aDataEncryptedString,aSizeEncrypted,MEM_RELEASE);
CryptDestroyKey(hKey);
CryptReleaseContext(hProv,0);
if (openArchive(&huz,(LPBYTE)aDataEncrypted, aSizeCompressed, ZIP_MEMORY|ZIP_RAW, 0))
{ // failed to open archive
closeArchive((TUNZIP *)huz);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE);
return 0;
}
}
else if (openArchive(&huz,(LPBYTE)aBuffer + hdrsz, aSizeCompressed, ZIP_MEMORY|ZIP_RAW, 0))
{ // failed to open archive
closeArchive((TUNZIP *)huz);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
return 0;
}
ze.CompressedSize = aSizeDeCompressed;
ze.UncompressedSize = aSizeDeCompressed;
if ((result = unzipEntry((TUNZIP *)huz, aDataBuf, &ze, ZIP_MEMORY)))
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
else
{
closeArchive((TUNZIP *)huz);
if (aDataEncrypted)
- VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE);
+ {
+ SecureZeroMemory(aDataEncrypted, aSizeDeCompressed);
+ VirtualFree(aDataEncrypted, aSizeDeCompressed, MEM_RELEASE);
+ }
return aSizeDeCompressed;
}
closeArchive((TUNZIP *)huz);
if (aDataEncrypted)
- VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE);
+ {
+ SecureZeroMemory(aDataEncrypted, aSizeDeCompressed);
+ VirtualFree(aDataEncrypted, aSizeDeCompressed, MEM_RELEASE);
+ }
}
}
return 0;
}
#ifndef MINIDLL
LONG WINAPI DisableHooksOnException(PEXCEPTION_POINTERS pExceptionPtrs)
{
// Disable all hooks to avoid system/mouse freeze
if (pExceptionPtrs->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
&& pExceptionPtrs->ExceptionRecord->ExceptionFlags == EXCEPTION_NONCONTINUABLE)
AddRemoveHooks(0);
return EXCEPTION_CONTINUE_SEARCH;
}
#endif
#if defined(_MSC_VER) && defined(_DEBUG)
void OutputDebugStringFormat(LPCTSTR fmt, ...)
{
CString sMsg;
va_list ap;
va_start(ap, fmt);
sMsg.FormatV(fmt, ap);
OutputDebugString(sMsg);
}
#endif
|
tinku99/ahkdll
|
cdbd556f64b3a6b977089350dbc3d4598b839e48
|
BugFix for compressed source
|
diff --git a/source/script.cpp b/source/script.cpp
index 9a1a382..f661ade 100644
--- a/source/script.cpp
+++ b/source/script.cpp
@@ -2512,2873 +2512,2921 @@ ResultType Script::LoadIncludedText(LPTSTR aScript,LPCTSTR aPathToShow)
one_char_string[0] = g_DerefChar;
two_char_string[0] = g_EscapeChar;
two_char_string[1] = g_DerefChar;
replacement_count += StrReplace(next_buf, one_char_string, two_char_string, SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
}
if (literal_delimiters)
{
one_char_string[0] = g_delimiter;
two_char_string[0] = g_EscapeChar;
two_char_string[1] = g_delimiter;
replacement_count += StrReplace(next_buf, one_char_string, two_char_string, SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
}
if (replacement_count) // Update the length if any actual replacements were done.
next_buf_length = _tcslen(next_buf);
} // Handling of a normal line within a continuation section.
// Must check the combined length only after anything that might have expanded the string above.
if (buf_length + next_buf_length + suffix_length >= LINE_SIZE)
return ScriptError(ERR_CONTINUATION_SECTION_TOO_LONG, cp);
++continuation_line_count;
// Append this continuation line onto the primary line.
// The suffix for the previous line gets written immediately prior writing this next line,
// which allows the suffix to be omitted for the final line. But if this is the first line,
// No suffix is written because there is no previous line in the continuation section.
// In addition, cp!=next_buf, this is the special line whose text occurs to the right of the
// continuation section's closing parenthesis. In this case too, the previous line doesn't
// get a suffix.
if (continuation_line_count > 1 && suffix_length && cp == next_buf)
{
tmemcpy(buf + buf_length, suffix, suffix_length + 1); // Append and include the zero terminator.
buf_length += suffix_length; // Must be done only after the old value of buf_length was used above.
}
if (next_buf_length)
{
tmemcpy(buf + buf_length, cp, next_buf_length + 1); // Append this line to prev. and include the zero terminator.
buf_length += next_buf_length; // Must be done only after the old value of buf_length was used above.
}
} // for() each sub-line (continued line) that composes this line.
process_completed_line:
// buf_length can't be -1 (though next_buf_length can) because outer loop's condition prevents it:
if (!buf_length) // Done only after the line number increments above so that the physical line number is properly tracked.
goto continue_main_loop; // In lieu of "continue", for performance.
// Since neither of the above executed, or they did but didn't "continue",
// buf now contains a non-commented line, either by itself or built from
// any continuation sections/lines that might have been present. Also note that
// by design, phys_line_number will be greater than mCombinedLineNumber whenever
// a continuation section/lines were used to build this combined line.
// If there's a previous line waiting to be processed, its fate can now be determined based on the
// nature of *this* line:
if (*pending_buf)
{
// Somewhat messy to decrement then increment later, but it's probably easier than the
// alternatives due to the use of "continue" in some places above. NOTE: phys_line_number
// would not need to be decremented+incremented even if the below resulted in a recursive
// call to us (though it doesn't currently) because line_number's only purpose is to
// remember where this layer left off when the recursion collapses back to us.
// Fix for v1.0.31.05: It's not enough just to decrement mCombinedLineNumber because there
// might be some blank lines or commented-out lines between this function call/definition
// and the line that follows it, each of which will have previously incremented mCombinedLineNumber.
saved_line_number = mCombinedLineNumber;
mCombinedLineNumber = pending_buf_line_number; // Done so that any syntax errors that occur during the calls below will report the correct line number.
// Open brace means this is a function definition. NOTE: buf was already ltrimmed by GetLine().
// Could use *g_act[ACT_BLOCK_BEGIN].Name instead of '{', but it seems too elaborate to be worth it.
if (*buf == '{' || pending_buf_has_brace) // v1.0.41: Support one-true-brace, e.g. fn(...) {
{
switch (pending_buf_type)
{
case Pending_Class:
if (!DefineClass(pending_buf))
return FAIL;
break;
case Pending_Property:
if (!DefineClassProperty(pending_buf))
return FAIL;
break;
case Pending_Func:
// Note that two consecutive function definitions aren't possible:
// fn1()
// fn2()
// {
// ...
// }
// In the above, the first would automatically be deemed a function call by means of
// the check higher above (by virtue of the fact that the line after it isn't an open-brace).
if (g->CurrentFunc)
{
// Though it might be allowed in the future -- perhaps to have nested functions have
// access to their parent functions' local variables, or perhaps just to improve
// script readability and maintainability -- it's currently not allowed because of
// the practice of maintaining the func_global_var list on our stack:
return ScriptError(_T("Functions cannot contain functions."), pending_buf);
}
if (!DefineFunc(pending_buf, func_global_var))
return FAIL;
if (pending_buf_has_brace) // v1.0.41: Support one-true-brace for function def, e.g. fn() {
{
if (!AddLine(ACT_BLOCK_BEGIN))
return FAIL;
mCurrLine = NULL; // L30: Prevents showing misleading vicinity lines if the line after a OTB function def is a syntax error.
}
break;
#ifdef _DEBUG
default:
return ScriptError(_T("DEBUG: pending_buf_type has an unexpected value."));
#endif
}
}
else // It's a function call on a line by itself, such as fn(x). It can't be if(..) because another section checked that.
{
if (pending_buf_type != Pending_Func) // Missing open-brace for class definition.
return ScriptError(ERR_MISSING_OPEN_BRACE, pending_buf);
if (mClassObjectCount && !g->CurrentFunc) // Unexpected function call in class definition.
return ScriptError(mClassProperty ? ERR_MISSING_OPEN_BRACE : ERR_INVALID_LINE_IN_CLASS_DEF, pending_buf);
if (!ParseAndAddLine(pending_buf, ACT_EXPRESSION))
return FAIL;
mCurrLine = NULL; // Prevents showing misleading vicinity lines if the line after a function call is a syntax error.
}
*pending_buf = '\0'; // Reset now that it's been fully handled, as an indicator for subsequent iterations.
if (pending_buf_type != Pending_Func) // Class or property.
{
if (!pending_buf_has_brace)
{
// This is the open-brace of a class definition, so requires no further processing.
if (!*(cp = omit_leading_whitespace(buf + 1)))
{
mCombinedLineNumber = saved_line_number;
goto continue_main_loop;
}
// Otherwise, there's something following the "{", possibly "}" or a function definition.
tmemmove(buf, cp, (buf_length = _tcslen(cp)) + 1);
}
}
mCombinedLineNumber = saved_line_number;
// Now fall through to the below so that *this* line (the one after it) will be processed.
// Note that this line might be a pre-processor directive, label, etc. that won't actually
// become a runtime line per se.
} // if (*pending_function)
if (*buf == '}' && mClassObjectCount && !g->CurrentFunc)
{
cp = buf;
if (mClassProperty)
{
// Close this property definition.
mClassProperty = NULL;
if (mClassPropertyDef)
{
free(mClassPropertyDef);
mClassPropertyDef = NULL;
}
cp = omit_leading_whitespace(cp + 1);
}
// Handling this before the two sections below allows a function or class definition
// to begin immediately after the close-brace of a previous class definition.
// This loop allows something like }}} to terminate multiple nested classes:
for (; *cp == '}' && mClassObjectCount; cp = omit_leading_whitespace(cp + 1))
{
// End of class definition.
--mClassObjectCount;
mClassObject[mClassObjectCount]->EndClassDefinition(); // Remove instance variables from the class object.
mClassObject[mClassObjectCount]->Release();
// Revert to the name of the class this class is nested inside, or "" if none.
if (cp1 = _tcsrchr(mClassName, '.'))
*cp1 = '\0';
else
*mClassName = '\0';
}
// cp now points at the next non-whitespace char after the brace.
if (!*cp)
goto continue_main_loop;
// Otherwise, there is something following this close-brace, so continue on below to process it.
tmemmove(buf, cp, buf_length = _tcslen(cp));
}
if (mClassProperty && !g->CurrentFunc) // This is checked before IsFunction() to prevent method definitions inside a property.
{
if (!_tcsnicmp(buf, _T("Get"), 3) || !_tcsnicmp(buf, _T("Set"), 3))
{
LPTSTR cp = omit_leading_whitespace(buf + 3);
if (!*cp || (*cp == '{' && !cp[1]))
{
// Defer this line until the next line comes in to simplify handling of '{' and OTB.
// For simplicity, pass the property definition to DefineFunc instead of the actual
// line text, even though it makes some error messages a bit inaccurate. (That would
// happen anyway when DefineFunc() finds a syntax error in the parameter list.)
_tcscpy(pending_buf, mClassPropertyDef);
LPTSTR dot = _tcschr(pending_buf, '.');
dot[1] = *buf; // Replace the x in property.xet(params).
pending_buf_line_number = mCombinedLineNumber;
pending_buf_has_brace = *cp == '{';
pending_buf_type = Pending_Func;
goto continue_main_loop;
}
}
return ScriptError(ERR_INVALID_LINE_IN_PROPERTY_DEF, buf);
}
// By doing the following section prior to checking for hotkey and hotstring labels, double colons do
// not need to be escaped inside naked function calls and function definitions such as the following:
// fn("::") ; Function call.
// fn(Str="::") ; Function definition with default value for its parameter.
if (IsFunction(buf, &pending_buf_has_brace)) // If true, it's either a function definition or a function call (to be distinguished later).
{
// Defer this line until the next line comes in, which helps determine whether this line is
// a function call vs. definition:
_tcscpy(pending_buf, buf);
pending_buf_line_number = mCombinedLineNumber;
pending_buf_type = Pending_Func;
goto continue_main_loop; // In lieu of "continue", for performance.
}
if (!g->CurrentFunc)
{
if (LPTSTR class_name = IsClassDefinition(buf, pending_buf_has_brace))
{
// Defer this line until the next line comes in to simplify handling of '{' and OTB:
_tcscpy(pending_buf, class_name);
pending_buf_line_number = mCombinedLineNumber;
pending_buf_type = Pending_Class;
goto continue_main_loop; // In lieu of "continue", for performance.
}
if (mClassObjectCount)
{
// Check for assignment first, in case of something like "Static := 123".
for (cp = buf; cisalnum(*cp) || *cp == '_' || *cp == '.'; ++cp);
if (cp > buf) // i.e. buf begins with an identifier.
{
cp = omit_leading_whitespace(cp);
if (*cp == ':' && cp[1] == '=') // This is an assignment.
{
if (!DefineClassVars(buf, false)) // See above for comments.
return FAIL;
goto continue_main_loop;
}
if (!*cp || *cp == '[' || (*cp == '{' && !cp[1])) // Property
{
size_t length = _tcslen(buf);
if (pending_buf_has_brace = (buf[length - 1] == '{'))
{
// Omit '{' and trailing whitespace from further consideration.
rtrim(buf, length - 1);
}
// Defer this line until the next line comes in to simplify handling of '{' and OTB:
_tcscpy(pending_buf, buf);
pending_buf_line_number = mCombinedLineNumber;
pending_buf_type = Pending_Property;
goto continue_main_loop; // In lieu of "continue", for performance.
}
}
if (!_tcsnicmp(buf, _T("Static"), 6) && IS_SPACE_OR_TAB(buf[6]))
{
if (!DefineClassVars(buf + 7, true))
return FAIL; // Above already displayed the error.
goto continue_main_loop; // In lieu of "continue", for performance.
}
if (*buf == '#') // See the identical section further below for comments.
{
saved_line_number = mCombinedLineNumber;
switch(IsDirective(buf))
{
case CONDITION_TRUE:
mCurrFileIndex = source_file_index;
mCombinedLineNumber = saved_line_number;
goto continue_main_loop;
case FAIL:
return FAIL;
}
}
// Anything not already handled above is not valid directly inside a class definition.
return ScriptError(ERR_INVALID_LINE_IN_CLASS_DEF, buf);
}
}
// The following "examine_line" label skips the following parts above:
// 1) IsFunction() because that's only for a function call or definition alone on a line
// e.g. not "if fn()" or x := fn(). Those who goto this label don't need that processing.
// 2) The "if (*pending_function)" block: Doesn't seem applicable for the callers of this label.
// 3) The inner loop that handles continuation sections: Not needed by the callers of this label.
// 4) Things like the following should be skipped because callers of this label don't want the
// physical line number changed (which would throw off the count of lines that lie beneath a remap):
// mCombinedLineNumber = phys_line_number + 1;
// ++phys_line_number;
// 5) "mCurrLine = NULL": Probably not necessary since it's only for error reporting. Worst thing
// that could happen is that syntax errors would be thrown off, which testing shows isn't the case.
examine_line:
#ifndef MINIDLL
// "::" alone isn't a hotstring, it's a label whose name is colon.
// Below relies on the fact that no valid hotkey can start with a colon, since
// ": & somekey" is not valid (since colon is a shifted key) and colon itself
// should instead be defined as "+;::". It also relies on short-circuit boolean:
hotstring_start = NULL;
hotstring_options = NULL; // Set default as "no options were specified for this hotstring".
hotkey_flag = NULL;
if (buf[0] == ':' && buf[1])
{
if (buf[1] != ':')
{
hotstring_options = buf + 1; // Point it to the hotstring's option letters.
// The following relies on the fact that options should never contain a literal colon.
// ALSO, the following doesn't use IS_HOTSTRING_OPTION() for backward compatibility,
// performance, and because it seems seldom if ever necessary at this late a stage.
if ( !(hotstring_start = _tcschr(hotstring_options, ':')) )
hotstring_start = NULL; // Indicate that this isn't a hotstring after all.
else
++hotstring_start; // Points to the hotstring itself.
}
else // Double-colon, so it's a hotstring if there's more after this (but this means no options are present).
if (buf[2])
hotstring_start = buf + 2; // And leave hotstring_options at its default of NULL to indicate no options.
//else it's just a naked "::", which is considered to be an ordinary label whose name is colon.
}
if (hotstring_start)
{
// Find the hotstring's final double-colon by considering escape sequences from left to right.
// This is necessary for to handles cases such as the following:
// ::abc```::::Replacement String
// The above hotstring translates literally into "abc`::".
LPTSTR escaped_double_colon = NULL;
for (cp = hotstring_start; ; ++cp) // Increment to skip over the symbol just found by the inner for().
{
for (; *cp && *cp != g_EscapeChar && *cp != ':'; ++cp); // Find the next escape char or colon.
if (!*cp) // end of string.
break;
cp1 = cp + 1;
if (*cp == ':')
{
if (*cp1 == ':') // Found a non-escaped double-colon, so this is the right one.
{
hotkey_flag = cp++; // Increment to have loop skip over both colons.
// and the continue with the loop so that escape sequences in the replacement
// text (if there is replacement text) are also translated.
}
// else just a single colon, or the second colon of an escaped pair (`::), so continue.
continue;
}
switch (*cp1)
{
// Only lowercase is recognized for these:
case 'a': *cp1 = '\a'; break; // alert (bell) character
case 'b': *cp1 = '\b'; break; // backspace
case 'f': *cp1 = '\f'; break; // formfeed
case 'n': *cp1 = '\n'; break; // newline
case 'r': *cp1 = '\r'; break; // carriage return
case 't': *cp1 = '\t'; break; // horizontal tab
case 'v': *cp1 = '\v'; break; // vertical tab
// Otherwise, if it's not one of the above, the escape-char is considered to
// mark the next character as literal, regardless of what it is. Examples:
// `` -> `
// `:: -> :: (effectively)
// `; -> ;
// `c -> c (i.e. unknown escape sequences resolve to the char after the `)
}
// Below has a final +1 to include the terminator:
tmemmove(cp, cp1, _tcslen(cp1) + 1);
// Since single colons normally do not need to be escaped, this increments one extra
// for double-colons to skip over the entire pair so that its second colon
// is not seen as part of the hotstring's final double-colon. Example:
// ::ahc```::::Replacement String
if (*cp == ':' && *cp1 == ':')
++cp;
} // for()
if (!hotkey_flag)
hotstring_start = NULL; // Indicate that this isn't a hotstring after all.
}
if (!hotstring_start) // Not a hotstring (hotstring_start is checked *again* in case above block changed it; otherwise hotkeys like ": & x" aren't recognized).
{
// Note that there may be an action following the HOTKEY_FLAG (on the same line).
if (hotkey_flag = _tcsstr(buf, HOTKEY_FLAG)) // Find the first one from the left, in case there's more than 1.
{
if (hotkey_flag == buf && hotkey_flag[2] == ':') // v1.0.46: Support ":::" to mean "colon is a hotkey".
++hotkey_flag;
// v1.0.40: It appears to be a hotkey, but validate it as such before committing to processing
// it as a hotkey. If it fails validation as a hotkey, treat it as a command that just happens
// to contain a double-colon somewhere. This avoids the need to escape double colons in scripts.
// Note: Hotstrings can't suffer from this type of ambiguity because a leading colon or pair of
// colons makes them easier to detect.
cp = omit_trailing_whitespace(buf, hotkey_flag); // For maintainability.
orig_char = *cp;
*cp = '\0'; // Temporarily terminate.
if (!Hotkey::TextInterpret(omit_leading_whitespace(buf), NULL, false)) // Passing NULL calls it in validate-only mode.
hotkey_flag = NULL; // It's not a valid hotkey, so indicate that it's a command (i.e. one that contains a literal double-colon, which avoids the need to escape the double-colon).
*cp = orig_char; // Undo the temp. termination above.
}
}
// Treat a naked "::" as a normal label whose label name is colon:
if (is_label = (hotkey_flag && hotkey_flag > buf)) // It's a hotkey/hotstring label.
{
if (g->CurrentFunc)
{
// Even if it weren't for the reasons below, the first hotkey/hotstring label in a script
// will end the auto-execute section with a "return". Therefore, if this restriction here
// is ever removed, be sure that that extra return doesn't get put inside the function.
//
// The reason for not allowing hotkeys and hotstrings inside a function's body is that
// when the subroutine is launched, the hotstring/hotkey would be using the function's
// local variables. But that is not appropriate and it's likely to cause problems even
// if it were. It doesn't seem useful in any case. By contrast, normal labels can
// safely exist inside a function body and since the body is a block, other validation
// ensures that a Gosub or Goto can't jump to it from outside the function.
return ScriptError(_T("Hotkeys/hotstrings are not allowed inside functions."), buf);
}
if (mLastLine && mLastLine->mActionType == ACT_IFWINACTIVE)
{
mCurrLine = mLastLine; // To show vicinity lines.
return ScriptError(_T("IfWin should be #IfWin."), buf);
}
*hotkey_flag = '\0'; // Terminate so that buf is now the label itself.
hotkey_flag += HOTKEY_FLAG_LENGTH; // Now hotkey_flag is the hotkey's action, if any.
if (!hotstring_start)
{
ltrim(hotkey_flag); // Has already been rtrimmed by GetLine().
rtrim(buf); // Trim the new substring inside of buf (due to temp termination). It has already been ltrimmed.
cp = hotkey_flag; // Set default, conditionally overridden below (v1.0.44.07).
// v1.0.40: Check if this is a remap rather than hotkey:
if ( *hotkey_flag // This hotkey's action is on the same line as its label.
&& (remap_source_vk = TextToVK(cp1 = Hotkey::TextToModifiers(buf, NULL)))
&& (remap_dest_vk = hotkey_flag[1] ? TextToVK(cp = Hotkey::TextToModifiers(hotkey_flag, NULL)) : 0xFF) ) // And the action appears to be a remap destination rather than a command.
// For above:
// Fix for v1.0.44.07: Set remap_dest_vk to 0xFF if hotkey_flag's length is only 1 because:
// 1) It allows a destination key that doesn't exist in the keyboard layout (such as 6::ð in
// English).
// 2) It improves performance a little by not calling TextToVK except when the destination key
// might be a mouse button or some longer key name whose actual/correct VK value is relied
// upon by other places below.
// Fix for v1.0.40.01: Since remap_dest_vk is also used as the flag to indicate whether
// this line qualifies as a remap, must do it last in the statement above. Otherwise,
// the statement might short-circuit and leave remap_dest_vk as non-zero even though
// the line shouldn't be a remap. For example, I think a hotkey such as "x & y::return"
// would trigger such a bug.
{
// These will be ignored in other stages if it turns out not to be a remap later below:
remap_source_is_mouse = IsMouseVK(remap_source_vk);
remap_dest_is_mouse = IsMouseVK(remap_dest_vk);
remap_keybd_to_mouse = !remap_source_is_mouse && remap_dest_is_mouse;
sntprintf(remap_source, _countof(remap_source), _T("%s%s")
, _tcslen(cp1) == 1 && IsCharUpper(*cp1) ? _T("+") : _T("") // Allow A::b to be different than a::b.
, buf); // Include any modifiers too, e.g. ^b::c.
tcslcpy(remap_dest, cp, _countof(remap_dest)); // But exclude modifiers here; they're wanted separately.
tcslcpy(remap_dest_modifiers, hotkey_flag, _countof(remap_dest_modifiers));
if (cp - hotkey_flag < _countof(remap_dest_modifiers)) // Avoid reading beyond the end.
remap_dest_modifiers[cp - hotkey_flag] = '\0'; // Terminate at the proper end of the modifier string.
remap_stage = 0; // Init for use in the next stage.
// In the unlikely event that the dest key has the same name as a command, disqualify it
// from being a remap (as documented). v1.0.40.05: If the destination key has any modifiers,
// it is unambiguously a key name rather than a command, so the switch() isn't necessary.
if (*remap_dest_modifiers)
goto continue_main_loop; // It will see that remap_dest_vk is non-zero and act accordingly.
switch (remap_dest_vk)
{
case VK_CONTROL: // Checked in case it was specified as "Control" rather than "Ctrl".
case VK_SLEEP:
if (StrChrAny(hotkey_flag, _T(" \t,"))) // Not using g_delimiter (reduces code size/complexity).
break; // Any space, tab, or enter means this is a command rather than a remap destination.
goto continue_main_loop; // It will see that remap_dest_vk is non-zero and act accordingly.
// "Return" and "Pause" as destination keys are always considered commands instead.
// This is documented and is done to preserve backward compatibility.
case VK_RETURN:
// v1.0.40.05: Although "Return" can't be a destination, "Enter" can be. Must compare
// to "Return" not "Enter" so that things like "vk0d" (the VK of "Enter") can also be a
// destination key:
if (!_tcsicmp(remap_dest, _T("Return")))
break;
goto continue_main_loop; // It will see that remap_dest_vk is non-zero and act accordingly.
case VK_PAUSE: // Used for both "Pause" and "Break"
break;
default: // All other VKs are valid destinations and thus the remap is valid.
goto continue_main_loop; // It will see that remap_dest_vk is non-zero and act accordingly.
}
// Since above didn't goto, indicate that this is not a remap after all:
remap_dest_vk = 0;
}
}
// else don't trim hotstrings since literal spaces in both substrings are significant.
// If this is the first hotkey label encountered, Add a return before
// adding the label, so that the auto-execute section is terminated.
// Only do this if the label is a hotkey because, for example,
// the user may want to fully execute a normal script that contains
// no hotkeys but does contain normal labels to which the execution
// should fall through, if specified, rather than returning.
// But this might result in weirdness? Example:
//testlabel:
// Sleep, 1
// return
// ^a::
// return
// It would put the hard return in between, which is wrong. But in the case above,
// the first sub shouldn't have a return unless there's a part up top that ends in Exit.
// So if Exit is encountered before the first hotkey, don't add the return?
// Even though wrong, the return is harmless because it's never executed? Except when
// falling through from above into a hotkey (which probably isn't very valid anyway)?
// Update: Below must check if there are any true hotkey labels, not just regular labels.
// Otherwise, a normal (non-hotkey) label in the autoexecute section would count and
// thus the RETURN would never be added here, even though it should be:
// Notes about the below macro:
// Fix for v1.0.34: Don't point labels to this particular RETURN so that labels
// can point to the very first hotkey or hotstring in a script. For example:
// Goto Test
// Test:
// ^!z::ToolTip Without the fix`, this is never displayed by "Goto Test".
// UCHAR_MAX signals it not to point any pending labels to this RETURN.
// mCurrLine = NULL -> signifies that we're in transition, trying to load a new one.
- #define CHECK_mNoHotkeyLabels \
+ #define CHECK_Text_mNoHotkeyLabels \
if (mNoHotkeyLabels)\
{\
mNoHotkeyLabels = false;\
if (!AddLine(ACT_RETURN, NULL, UCHAR_MAX))\
return FAIL;\
mCurrLine = NULL;\
}
- CHECK_mNoHotkeyLabels
+ CHECK_Text_mNoHotkeyLabels
// For hotstrings, the below makes the label include leading colon(s) and the full option
// string (if any) so that the uniqueness of labels is preserved. For example, we want
// the following two hotstring labels to be unique rather than considered duplicates:
// ::abc::
// :c:abc::
if (!AddLabel(buf, true)) // Always add a label before adding the first line of its section.
return FAIL;
hook_action = 0; // Set default.
if (*hotkey_flag) // This hotkey's action is on the same line as its label.
{
if (!hotstring_start)
// Don't add the alt-tabs as a line, since it has no meaning as a script command.
// But do put in the Return regardless, in case this label is ever jumped to
// via Goto/Gosub:
if ( !(hook_action = Hotkey::ConvertAltTab(hotkey_flag, false)) )
if (!ParseAndAddLine(hotkey_flag))
return FAIL;
// Also add a Return that's implicit for a single-line hotkey. This is also
// done for auto-replace hotstrings in case gosub/goto is ever used to jump
// to their labels:
if (!AddLine(ACT_RETURN))
return FAIL;
}
if (hotstring_start)
{
if (!*hotstring_start)
{
// The following error message won't indicate the correct line number because
// the hotstring (as a label) does not actually exist as a line. But it seems
// best to report it this way in case the hotstring is inside a #Include file,
// so that the correct file name and approximate line number are shown:
return ScriptError(_T("This hotstring is missing its abbreviation."), buf); // Display buf vs. hotkey_flag in case the line is simply "::::".
}
// In the case of hotstrings, hotstring_start is the beginning of the hotstring itself,
// i.e. the character after the second colon. hotstring_options is NULL if no options,
// otherwise it's the first character in the options list (option string is not terminated,
// but instead ends in a colon). hotkey_flag is blank if it's not an auto-replace
// hotstring, otherwise it contains the auto-replace text.
// v1.0.42: Unlike hotkeys, duplicate hotstrings are not detected. This is because
// hotstrings are less commonly used and also because it requires more code to find
// hotstring duplicates (and performs a lot worse if a script has thousands of
// hotstrings) because of all the hotstring options.
if (!Hotstring::AddHotstring(mLastLabel, hotstring_options ? hotstring_options : _T("")
, hotstring_start, hotkey_flag, has_continuation_section))
return FAIL;
}
else // It's a hotkey vs. hotstring.
{
if (hk = Hotkey::FindHotkeyByTrueNature(buf, suffix_has_tilde, hook_is_mandatory)) // Parent hotkey found. Add a child/variant hotkey for it.
{
if (hook_action) // suffix_has_tilde has always been ignored for these types (alt-tab hotkeys).
{
// Hotkey::Dynamic() contains logic and comments similar to this, so maintain them together.
// An attempt to add an alt-tab variant to an existing hotkey. This might have
// merit if the intention is to make it alt-tab now but to later disable that alt-tab
// aspect via the Hotkey cmd to let the context-sensitive variants shine through
// (take effect).
hk->mHookAction = hook_action;
}
else
{
// Detect duplicate hotkey variants to help spot bugs in scripts.
if (hk->FindVariant()) // See if there's already a variant matching the current criteria (suffix_has_tilde does not make variants distinct form each other because it would require firing two hotkey IDs in response to pressing one hotkey, which currently isn't in the design).
{
mCurrLine = NULL; // Prevents showing unhelpful vicinity lines.
return ScriptError(_T("Duplicate hotkey."), buf);
}
if (!hk->AddVariant(mLastLabel, suffix_has_tilde))
return ScriptError(ERR_OUTOFMEM, buf);
if (hook_is_mandatory || (!g_os.IsWin9x() && g_ForceKeybdHook))
{
// Require the hook for all variants of this hotkey if any variant requires it.
// This seems more intuitive than the old behaviour, which required $ or #UseHook
// to be used on the *first* variant, even though it affected all variants.
#ifdef CONFIG_WIN9X
if (g_os.IsWin9x())
hk->mUnregisterDuringThread = true;
else
#endif
hk->mKeybdHookMandatory = true;
}
}
}
else // No parent hotkey yet, so create it.
if ( !(hk = Hotkey::AddHotkey(mLastLabel, hook_action, NULL, suffix_has_tilde, false)) )
return FAIL; // It already displayed the error.
}
goto continue_main_loop; // In lieu of "continue", for performance.
} // if (is_label = ...)
#endif
// Otherwise, not a hotkey or hotstring. Check if it's a generic, non-hotkey label:
if (buf[buf_length - 1] == ':') // Labels must end in a colon (buf was previously rtrimmed).
{
if (buf_length == 1) // v1.0.41.01: Properly handle the fact that this line consists of only a colon.
return ScriptError(ERR_UNRECOGNIZED_ACTION, buf);
// Labels (except hotkeys) must contain no whitespace, delimiters, or escape-chars.
// This is to avoid problems where a legitimate action-line ends in a colon,
// such as "WinActivate SomeTitle" and "#Include c:".
// We allow hotkeys to violate this since they may contain commas, and since a normal
// script line (i.e. just a plain command) is unlikely to ever end in a double-colon:
for (cp = buf, is_label = true; *cp; ++cp)
if (IS_SPACE_OR_TAB(*cp) || *cp == g_delimiter || *cp == g_EscapeChar)
{
is_label = false;
break;
}
if (is_label) // It's a generic, non-hotkey/non-hotstring label.
{
// v1.0.44.04: Fixed this check by moving it after the above loop.
// Above has ensured buf_length>1, so it's safe to check for double-colon:
// v1.0.44.03: Don't allow anything that ends in "::" (other than a line consisting only
// of "::") to be a normal label. Assume it's a command instead (if it actually isn't, a
// later stage will report it as "invalid hotkey"). This change avoids the situation in
// which a hotkey like ^!ä:: is seen as invalid because the current keyboard layout doesn't
// have a "ä" key. Without this change, if such a hotkey appears at the top of the script,
// its subroutine would execute immediately as a normal label, which would be especially
// bad if the hotkey were something like the "Shutdown" command.
if (buf[buf_length - 2] == ':' && buf_length > 2) // i.e. allow "::" as a normal label, but consider anything else with double-colon to be a failed-hotkey label that terminates the auto-exec section.
{
//CHECK_mNoHotkeyLabels // Terminate the auto-execute section since this is a failed hotkey vs. a mere normal label.
sntprintf(msg_text, _countof(msg_text), _T("Note: The hotkey %s will not be active because it does not exist in the current keyboard layout."), buf);
MsgBox(msg_text);
}
buf[--buf_length] = '\0'; // Remove the trailing colon.
rtrim(buf, buf_length); // Has already been ltrimmed.
if (!AddLabel(buf, false))
return FAIL;
goto continue_main_loop; // In lieu of "continue", for performance.
}
}
// Since above didn't "goto", it's not a label.
if (*buf == '#')
{
saved_line_number = mCombinedLineNumber; // Backup in case IsDirective() processes an include file, which would change mCombinedLineNumber's value.
switch(IsDirective(buf)) // Note that it may alter the contents of buf, at least in the case of #IfWin.
{
case CONDITION_TRUE:
// Since the directive may have been a #include which called us recursively,
// restore the class's values for these two, which are maintained separately
// like this to avoid having to specify them in various calls, especially the
// hundreds of calls to ScriptError() and LineError():
mCurrFileIndex = source_file_index;
mCombinedLineNumber = saved_line_number;
goto continue_main_loop; // In lieu of "continue", for performance.
case FAIL: // IsDirective() already displayed the error.
return FAIL;
//case CONDITION_FALSE: Do nothing; let processing below handle it.
}
}
// Otherwise, treat it as a normal script line.
if (*buf == '{' || *buf == '}')
{
if (!AddLine(*buf == '{' ? ACT_BLOCK_BEGIN : ACT_BLOCK_END))
return FAIL;
// Allow any command/action, directive or label to the right of "{" or "}":
if ( *(buf = omit_leading_whitespace(buf + 1)) )
{
buf_length = _tcslen(buf); // Update.
mCurrLine = NULL; // To signify that we're in transition, trying to load a new line.
goto process_completed_line; // Have the main loop process the contents of "buf" as though it came in from the script.
}
goto continue_main_loop; // It's just a naked "{" or "}", so no more processing needed for this line.
}
// First do a little special handling to support actions on the same line as their
// ELSE or TRY, e.g.:
// else if x = 1
// try someFunction()
// This is done here rather than in ParseAndAddLine() because it's fairly
// complicated to do there (already tried it) mostly due to the fact that
// literal_map has to be properly passed in a recursive call to itself, as well
// as properly detecting special commands that don't have keywords such as
// IF comparisons, ACT_ASSIGN, +=, -=, etc.
// v1.0.41: '{' was added to the line below to support no spaces inside "}else{".
if (!(action_end = StrChrAny(buf, _T("\t ,{")))) // Position of first tab/space/comma/open-brace. For simplicity, a non-standard g_delimiter is not supported.
action_end = buf + buf_length; // It's done this way so that ELSE can be fully handled here; i.e. that ELSE does not have to be in the list of commands recognizable by ParseAndAddLine().
// The following method ensures that words or variables that start with "Else", e.g. ElseAction, are not
// incorrectly detected as an Else command:
int try_cmp = 1, finally_cmp = 1;
if (tcslicmp(buf, _T("Else"), action_end - buf) // It's not an ELSE, a TRY or a FINALLY. ("Else"/"Try"/"Finally" is used vs. g_act[ACT_ELSE/TRY/FINALLY].Name for performance).
&& (try_cmp = tcslicmp(buf, _T("Try"), action_end - buf))
&& (finally_cmp = tcslicmp(buf, _T("Finally"), action_end - buf)))
{
if (!ParseAndAddLine(buf))
return FAIL;
}
else // This line is an ELSE, a TRY or a FINALLY, possibly with another command immediately after it (on the same line).
{
// Add the ELSE, TRY or FINALLY directly rather than calling ParseAndAddLine() because that function
// would resolve escape sequences throughout the entire length of <buf>, which we
// don't want because we wouldn't have access to the corresponding literal-map to
// figure out the proper use of escaped characters:
if (!AddLine(try_cmp ? (finally_cmp ? ACT_ELSE : ACT_FINALLY) : ACT_TRY))
return FAIL;
mCurrLine = NULL; // To signify that we're in transition, trying to load a new one.
buf = omit_leading_whitespace(action_end); // Now buf is the word after the ELSE or TRY.
if (*buf == g_delimiter) // Allow "else, action", "try, action" and "finally, action"
buf = omit_leading_whitespace(buf + 1);
// Allow any command/action to the right of "else", "try" or "finally", including "{":
if (*buf)
{
// This is done rather than calling ParseAndAddLine() as it handles "{" in a way that
// anything to the right of it is considered an arg of that line and is basically ignored.
buf_length = _tcslen(buf); // Update.
mCurrLine = NULL; // To signify that we're in transition, trying to load a new line.
goto examine_line; // Have the main loop process the contents of "buf" as though it came in from the script.
}
// Otherwise, there was either no same-line action, so do nothing.
}
continue_main_loop: // This method is used in lieu of "continue" for performance and code size reduction.
#ifndef MINIDLL
if (remap_dest_vk)
{
// For remapping, decided to use a "macro expansion" approach because I think it's considerably
// smaller in code size and complexity than other approaches would be. I originally wanted to
// do it with the hook by changing the incoming event prior to passing it back out again (for
// example, a::b would transform an incoming 'a' keystroke into 'b' directly without having
// to suppress the original keystroke and simulate a new one). Unfortunately, the low-level
// hooks apparently do not allow this. Here is the test that confirmed it:
// if (event.vkCode == 'A')
// {
// event.vkCode = 'B';
// event.scanCode = 0x30; // Or use vk_to_sc(event.vkCode).
// return CallNextHookEx(g_KeybdHook, aCode, wParam, lParam);
// }
switch (++remap_stage)
{
case 1: // Stage 1: Add key-down hotkey label, e.g. *LButton::
buf_length = _stprintf(buf, _T("*%s::"), remap_source); // Should be no risk of buffer overflow due to prior validation.
goto examine_line; // Have the main loop process the contents of "buf" as though it came in from the script.
case 2: // Stage 2.
// Copied into a writable buffer for maintainability: AddLine() might rely on this.
// Also, it seems unnecessary to set press-duration to -1 even though the auto-exec section might
// have set it to something higher than -1 because:
// 1) Press-duration doesn't apply to normal remappings since they use down-only and up-only events.
// 2) Although it does apply to remappings such as a::B and a::^b (due to press-duration being
// applied after a change to modifier state), those remappings are fairly rare and supporting
// a non-negative-one press-duration (almost always 0) probably adds a degree of flexibility
// that may be desirable to keep.
// 3) SendInput may become the predominant SendMode, so press-duration won't often be in effect anyway.
// 4) It has been documented that remappings use the auto-execute section's press-duration.
_tcscpy(buf, _T("-1")); // Does NOT need to be "-1, -1" for SetKeyDelay (see above).
// The primary reason for adding Key/MouseDelay -1 is to minimize the chance that a one of
// these hotkey threads will get buried under some other thread such as a timer, which
// would disrupt the remapping if #MaxThreadsPerHotkey is at its default of 1.
AddLine(remap_dest_is_mouse ? ACT_SETMOUSEDELAY : ACT_SETKEYDELAY, &buf, 1, NULL); // PressDuration doesn't need to be specified because it doesn't affect down-only and up-only events.
if (remap_keybd_to_mouse)
{
// Since source is keybd and dest is mouse, prevent keyboard auto-repeat from auto-repeating
// the mouse button (since that would be undesirable 90% of the time). This is done
// by inserting a single extra IF-statement above the Send that produces the down-event:
buf_length = _stprintf(buf, _T("if not GetKeyState(\"%s\")"), remap_dest); // Should be no risk of buffer overflow due to prior validation.
remap_stage = 9; // Have it hit special stage 9+1 next time for code reduction purposes.
goto examine_line; // Have the main loop process the contents of "buf" as though it came in from the script.
}
// Otherwise, remap_keybd_to_mouse==false, so fall through to next case.
case 10:
extra_event = _T(""); // Set default.
switch (remap_dest_vk)
{
case VK_LMENU:
case VK_RMENU:
case VK_MENU:
switch (remap_source_vk)
{
case VK_LCONTROL:
case VK_CONTROL:
extra_event = _T("{LCtrl up}"); // Somewhat surprisingly, this is enough to make "Ctrl::Alt" properly remap both right and left control.
break;
case VK_RCONTROL:
extra_event = _T("{RCtrl up}");
break;
// Below is commented out because its only purpose was to allow a shift key remapped to alt
// to be able to alt-tab. But that wouldn't work correctly due to the need for the following
// hotkey, which does more harm than good by impacting the normal Alt key's ability to alt-tab
// (if the normal Alt key isn't remapped): *Tab::Send {Blind}{Tab}
//case VK_LSHIFT:
//case VK_SHIFT:
// extra_event = "{LShift up}";
// break;
//case VK_RSHIFT:
// extra_event = "{RShift up}";
// break;
}
break;
}
mCurrLine = NULL; // v1.0.40.04: Prevents showing misleading vicinity lines for a syntax-error such as %::%
_stprintf(buf, _T("{Blind}%s%s{%s DownTemp}"), extra_event, remap_dest_modifiers, remap_dest); // v1.0.44.05: DownTemp vs. Down. See Send's DownTemp handler for details.
if (!AddLine(ACT_SEND, &buf, 1, NULL)) // v1.0.40.04: Check for failure due to bad remaps such as %::%.
return FAIL;
AddLine(ACT_RETURN);
// Add key-up hotkey label, e.g. *LButton up::
buf_length = _stprintf(buf, _T("*%s up::"), remap_source); // Should be no risk of buffer overflow due to prior validation.
remap_stage = 2; // Adjust to hit stage 3 next time (in case this is stage 10).
goto examine_line; // Have the main loop process the contents of "buf" as though it came in from the script.
case 3: // Stage 3.
_tcscpy(buf, _T("-1"));
AddLine(remap_dest_is_mouse ? ACT_SETMOUSEDELAY : ACT_SETKEYDELAY, &buf, 1, NULL);
_stprintf(buf, _T("{Blind}{%s Up}"), remap_dest); // Unlike the down-event above, remap_dest_modifiers is not included for the up-event; e.g. ^{b up} is inappropriate.
AddLine(ACT_SEND, &buf, 1, NULL);
AddLine(ACT_RETURN);
remap_dest_vk = 0; // Reset to signal that the remapping expansion is now complete.
break; // Fall through to the next section so that script loading can resume at the next line.
}
} // if (remap_dest_vk)
#endif
// Since above didn't "continue", resume loading script line by line:
buf = next_buf;
buf_length = next_buf_length;
next_buf = (buf == buf1) ? buf2 : buf1;
// The line above alternates buffers (toggles next_buf to be the unused buffer), which helps
// performance because it avoids memcpy from buf2 to buf1.
} // for each whole/constructed line.
if (*pending_buf) // Since this is the last non-comment line, the pending function must be a function call, not a function definition.
{
// Somewhat messy to decrement then increment later, but it's probably easier than the
// alternatives due to the use of "continue" in some places above.
saved_line_number = mCombinedLineNumber;
mCombinedLineNumber = pending_buf_line_number; // Done so that any syntax errors that occur during the calls below will report the correct line number.
if (pending_buf_type != Pending_Func)
return ScriptError(pending_buf_has_brace ? ERR_MISSING_CLOSE_BRACE : ERR_MISSING_OPEN_BRACE, pending_buf);
if (!ParseAndAddLine(pending_buf, ACT_EXPRESSION)) // Must be function call vs. definition since otherwise the above would have detected the opening brace beneath it and already cleared pending_function.
return FAIL;
mCombinedLineNumber = saved_line_number;
}
if (mClassObjectCount && !source_file_index) // or mClassProperty, which implies mClassObjectCount != 0.
{
// A class definition has not been closed with "}". Previously this was detected by adding
// the open and close braces as lines, but this way is simpler and has less overhead.
// The downside is that the line number won't be shown; however, the class name will.
// Seems okay not to show mClassProperty->mName since the class is missing "}" as well.
return ScriptError(ERR_MISSING_CLOSE_BRACE, mClassName);
}
++mCombinedLineNumber; // L40: Put the implicit ACT_EXIT on the line after the last physical line (for the debugger).
// This is not required, it is called by the destructor.
// fp->Close();
return OK;
}
#endif
ResultType Script::LoadIncludedFile(LPTSTR aFileSpec, bool aAllowDuplicateInclude, bool aIgnoreLoadFailure)
// Returns OK or FAIL.
// Below: Use double-colon as delimiter to set these apart from normal labels.
// The main reason for this is that otherwise the user would have to worry
// about a normal label being unintentionally valid as a hotkey, e.g.
// "Shift:" might be a legitimate label that the user forgot is also
// a valid hotkey:
#define HOTKEY_FLAG _T("::")
#define HOTKEY_FLAG_LENGTH 2
{
if (!aFileSpec || !*aFileSpec) return FAIL;
#ifndef AUTOHOTKEYSC
if (Line::sSourceFileCount >= Line::sMaxSourceFiles)
{
if (Line::sSourceFileCount >= ABSOLUTE_MAX_SOURCE_FILES)
return ScriptError(_T("Too many includes.")); // Short msg since so rare.
int new_max;
if (Line::sMaxSourceFiles)
{
new_max = 2*Line::sMaxSourceFiles;
if (new_max > ABSOLUTE_MAX_SOURCE_FILES)
new_max = ABSOLUTE_MAX_SOURCE_FILES;
}
else
new_max = 100;
// For simplicity and due to rarity of every needing to, expand by reallocating the array.
// Use a temp var. because realloc() returns NULL on failure but leaves original block allocated.
LPTSTR *realloc_temp = (LPTSTR *)realloc(Line::sSourceFile, new_max * sizeof(LPTSTR)); // If passed NULL, realloc() will do a malloc().
if (!realloc_temp)
return ScriptError(ERR_OUTOFMEM); // Short msg since so rare.
Line::sSourceFile = realloc_temp;
Line::sMaxSourceFiles = new_max;
}
TCHAR full_path[MAX_PATH];
#endif
// Keep this var on the stack due to recursion, which allows newly created lines to be given the
// correct file number even when some #include's have been encountered in the middle of the script:
int source_file_index = Line::sSourceFileCount;
if (!source_file_index)
// Since this is the first source file, it must be the main script file. Just point it to the
// location of the filespec already dynamically allocated:
Line::sSourceFile[source_file_index] = mFileSpec;
#ifndef AUTOHOTKEYSC // The "else" part below should never execute for compiled scripts since they never include anything (other than the main/combined script).
else
{
// Get the full path in case aFileSpec has a relative path. This is done so that duplicates
// can be reliably detected (we only want to avoid including a given file more than once):
LPTSTR filename_marker;
GetFullPathName(aFileSpec, _countof(full_path), full_path, &filename_marker);
// Check if this file was already included. If so, it's not an error because we want
// to support automatic "include once" behavior. So just ignore repeats:
if (!aAllowDuplicateInclude)
for (int f = 0; f < source_file_index; ++f) // Here, source_file_index==Line::sSourceFileCount
if (!lstrcmpi(Line::sSourceFile[f], full_path)) // Case insensitive like the file system (testing shows that "Ä" == "ä" in the NTFS, which is hopefully how lstrcmpi works regardless of locale).
return OK;
// The file is added to the list further below, after the file has been opened, in case the
// opening fails and aIgnoreLoadFailure==true.
}
#endif
// <buf> should be no larger than LINE_SIZE because some later functions rely upon that:
TCHAR msg_text[MAX_PATH + 256], buf1[LINE_SIZE], buf2[LINE_SIZE], suffix[16], pending_buf[LINE_SIZE] = _T("");
LPTSTR buf = buf1, next_buf = buf2; // Oscillate between bufs to improve performance (avoids memcpy from buf2 to buf1).
size_t buf_length, next_buf_length, suffix_length;
bool pending_buf_has_brace;
TextStream *fp;
TextFile tfile;
TextMem tmem;
+ DWORD aSizeDeCompressed = 0;
+ TextMem::Buffer textbuf(NULL, 0, false);
enum {
Pending_Func,
Pending_Class,
Pending_Property
} pending_buf_type;
#ifndef AUTOHOTKEYSC
if (!g_hResource || Line::sSourceFileCount) // It is not a compiled exe or main script was already loaded
{
if (!tfile.Open(aFileSpec, DEFAULT_READ_FLAGS, g_DefaultScriptCodepage))
{
if (aIgnoreLoadFailure)
return OK;
sntprintf(msg_text, _countof(msg_text), _T("%s file \"%s\" cannot be opened.")
, Line::sSourceFileCount > 0 ? _T("#Include") : _T("Script"), aFileSpec);
return ScriptError(msg_text);
}
fp = &tfile;
// This is done only after the file has been successfully opened in case aIgnoreLoadFailure==true:
if (source_file_index > 0)
{
Line::sSourceFile[source_file_index] = tmalloc(_tcslen(full_path)+1); //SimpleHeap::Malloc(full_path);
if (Line::sSourceFile[source_file_index] == 0)
{
ScriptError(ERR_OUTOFMEM);
return FAIL;
}
_tcscpy(Line::sSourceFile[source_file_index],full_path);
}
}
else
{
HGLOBAL hResData;
- TextMem::Buffer textbuf(NULL, 0, false);
if ( !( (textbuf.mLength = SizeofResource(g_hInstance, g_hResource))
&& (hResData = LoadResource(g_hInstance, g_hResource))
&& (textbuf.mBuffer = LockResource(hResData)) ) )
{
MsgBox(_T("Could not extract script from EXE."), 0, aFileSpec);
return FAIL;
}
- DWORD aSizeDeCompressed = 0;
if (*(unsigned int*)textbuf.mBuffer == 0x04034b50)
{
LPVOID aDataBuf;
aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf,g_default_pwd);
if (aSizeDeCompressed)
{
LPVOID buff = _alloca(aSizeDeCompressed); // will be freed when function returns
memmove(buff,aDataBuf,aSizeDeCompressed);
SecureZeroMemory(aDataBuf, aSizeDeCompressed);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
textbuf.mLength = aSizeDeCompressed;
textbuf.mBuffer = buff;
}
}
fp = &tmem;
// NOTE: Ahk2Exe strips off the UTF-8 BOM.
tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF8);
- if (aSizeDeCompressed)
- SecureZeroMemory(textbuf.mBuffer, textbuf.mLength);
}
//else the first file was already taken care of by another means.
#else // Stand-alone mode (there are no include files in this mode since all of them were merged into the main script at the time of compiling).
- TextMem::Buffer textbuf(NULL, 0, false);
-
HRSRC hRes;
HGLOBAL hResData;
#ifdef _DEBUG
if (hRes = FindResource(NULL, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA)))
#else
if (hRes = FindResource(NULL, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA)))
#endif
mCompiledHasCustomIcon = false;
else if (hRes = FindResource(NULL, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA)))
mCompiledHasCustomIcon = true;
if ( !( hRes
&& (textbuf.mLength = SizeofResource(NULL, hRes))
&& (hResData = LoadResource(NULL, hRes))
&& (textbuf.mBuffer = LockResource(hResData)) ) )
{
MsgBox(_T("Could not extract script from EXE."), 0, aFileSpec);
return FAIL;
}
- DWORD aSizeDeCompressed = 0;
if (*(unsigned int*)textbuf.mBuffer == 0x04034b50)
{
LPVOID aDataBuf;
aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf,g_default_pwd);
if (aSizeDeCompressed)
{
LPVOID buff = _alloca(aSizeDeCompressed); // will be freed when function returns
memmove(buff,aDataBuf,aSizeDeCompressed);
SecureZeroMemory(aDataBuf, aSizeDeCompressed);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
textbuf.mLength = aSizeDeCompressed;
textbuf.mBuffer = buff;
}
}
fp = &tmem;
// NOTE: Ahk2Exe strips off the UTF-8 BOM.
tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF8);
- if (aSizeDeCompressed)
- SecureZeroMemory(textbuf.mBuffer, textbuf.mLength);
#endif
++Line::sSourceFileCount;
// File is now open, read lines from it.
#ifndef MINIDLL
LPTSTR hotkey_flag, cp, cp1, action_end, hotstring_start, hotstring_options;
Hotkey *hk;
#else
LPTSTR hotkey_flag, cp, cp1, action_end;
#endif
LineNumberType pending_buf_line_number, saved_line_number;
#ifndef MINIDLL
HookActionType hook_action;
bool is_label, suffix_has_tilde, hook_is_mandatory, in_comment_section, hotstring_options_all_valid;
#else
bool is_label, in_comment_section;
#endif
#ifndef MINIDLL
// For the remap mechanism, e.g. a::b
int remap_stage;
vk_type remap_source_vk, remap_dest_vk = 0; // Only dest is initialized to enforce the fact that it is the flag/signal to indicate whether remapping is in progress.
TCHAR remap_source[32], remap_dest[32], remap_dest_modifiers[8]; // Must fit the longest key name (currently Browser_Favorites [17]), but buffer overflow is checked just in case.
LPTSTR extra_event;
bool remap_source_is_mouse, remap_dest_is_mouse, remap_keybd_to_mouse;
#endif
// For the line continuation mechanism:
bool do_ltrim, do_rtrim, literal_escapes, literal_derefs, literal_delimiters
, has_continuation_section, is_continuation_line;
#define CONTINUATION_SECTION_WITHOUT_COMMENTS 1 // MUST BE 1 because it's the default set by anything that's boolean-true.
#define CONTINUATION_SECTION_WITH_COMMENTS 2 // Zero means "not in a continuation section".
int in_continuation_section;
LPTSTR next_option, option_end;
TCHAR orig_char, one_char_string[2], two_char_string[3]; // Line continuation mechanism's option parsing.
one_char_string[1] = '\0'; // Pre-terminate these to simplify code later below.
two_char_string[2] = '\0'; //
int continuation_line_count;
#define MAX_FUNC_VAR_GLOBALS 2000
Var *func_global_var[MAX_FUNC_VAR_GLOBALS];
// Init both for main file and any included files loaded by this function:
mCurrFileIndex = source_file_index; // source_file_index is kept on the stack due to recursion (from #include).
#ifdef AUTOHOTKEYSC
// -1 (MAX_UINT in this case) to compensate for the fact that there is a comment containing
// the version number added to the top of each compiled script:
LineNumberType phys_line_number = -1;
#else
LineNumberType phys_line_number = 0;
#endif
buf_length = GetLine(buf, LINE_SIZE - 1, 0, fp);
if (in_comment_section = !_tcsncmp(buf, _T("/*"), 2))
{
// Fixed for v1.0.35.08. Must reset buffer to allow a script's first line to be "/*".
*buf = '\0';
buf_length = 0;
}
while (buf_length != -1) // Compare directly to -1 since length is unsigned.
{
// For each whole line (a line with continuation section is counted as only a single line
// for the purpose of this outer loop).
// Keep track of this line's *physical* line number within its file for A_LineNumber and
// error reporting purposes. This must be done only in the outer loop so that it tracks
// the topmost line of any set of lines merged due to continuation section/line(s)..
mCombinedLineNumber = phys_line_number + 1;
// This must be reset for each iteration because a prior iteration may have changed it, even
// indirectly by calling something that changed it:
mCurrLine = NULL; // To signify that we're in transition, trying to load a new one.
// v1.0.44.13: An additional call to IsDirective() is now made up here so that #CommentFlag affects
// the line beneath it the same way as other lines (#EscapeChar et. al. didn't have this bug).
// It's best not to process ALL directives up here because then they would no longer support a
// continuation section beneath them (and possibly other drawbacks because it was never thoroughly
// tested).
if (!_tcsnicmp(buf, _T("#CommentFlag"), 12)) // Have IsDirective() process this now (it will also process it again later, which is harmless).
if (IsDirective(buf) == FAIL) // IsDirective() already displayed the error.
- return FAIL;
+ goto FAIL;
// Read in the next line (if that next line is the start of a continuation section, append
// it to the line currently being processed:
for (has_continuation_section = false, in_continuation_section = 0;;)
{
// This increment relies on the fact that this loop always has at least one iteration:
++phys_line_number; // Tracks phys. line number in *this* file (independent of any recursion caused by #Include).
next_buf_length = GetLine(next_buf, LINE_SIZE - 1, in_continuation_section, fp);
if (next_buf_length && next_buf_length != -1 // Prevents infinite loop when file ends with an unclosed "/*" section. Compare directly to -1 since length is unsigned.
&& !in_continuation_section) // Multi-line comments can't be used in continuation sections. This line fixes '*/' being discarded in continuation sections (broken by L54).
{
if (!_tcsncmp(next_buf, _T("*/"), 2) // Check this even if !in_comment_section so it can be ignored (for convenience) and not treated as a line-continuation operator.
&& (in_comment_section || next_buf[2] != ':' || next_buf[3] != ':')) // ...but support */:: as a hotkey.
{
in_comment_section = false;
next_buf_length -= 2; // Adjust for removal of /* from the beginning of the string.
tmemmove(next_buf, next_buf + 2, next_buf_length + 1); // +1 to include the string terminator.
next_buf_length = ltrim(next_buf, next_buf_length); // Get rid of any whitespace that was between the comment-end and remaining text.
if (!*next_buf) // The rest of the line is empty, so it was just a naked comment-end.
continue;
}
else if (in_comment_section)
continue;
if (!_tcsncmp(next_buf, _T("/*"), 2))
{
in_comment_section = true;
continue; // It's now commented out, so the rest of this line is ignored.
}
}
if (in_comment_section) // Above has incremented and read the next line, which is everything needed while inside /* .. */
{
if (next_buf_length == -1) // Compare directly to -1 since length is unsigned.
break; // By design, it's not an error. This allows "/*" to be used to comment out the bottommost portion of the script without needing a matching "*/".
// Otherwise, continue reading lines so that they can be merged with the line above them
// if they qualify as continuation lines.
continue;
}
if (!in_continuation_section) // This is either the first iteration or the line after the end of a previous continuation section.
{
// v1.0.38.06: The following has been fixed to exclude "(:" and "(::". These should be
// labels/hotkeys, not the start of a continuation section. In addition, a line that starts
// with '(' but that ends with ':' should be treated as a label because labels such as
// "(label):" are far more common than something obscure like a continuation section whose
// join character is colon, namely "(Join:".
if ( !(in_continuation_section = (next_buf_length != -1 && *next_buf == '(' // Compare directly to -1 since length is unsigned.
&& next_buf[1] != ':' && next_buf[next_buf_length - 1] != ':')) ) // Relies on short-circuit boolean order.
{
if (next_buf_length == -1) // Compare directly to -1 since length is unsigned.
break;
if (!next_buf_length)
// It is permitted to have blank lines and comment lines in between the line above
// and any continuation section/line that might come after the end of the
// comment/blank lines:
continue;
// SINCE ABOVE DIDN'T BREAK/CONTINUE, NEXT_BUF IS NON-BLANK.
if (next_buf[next_buf_length - 1] == ':' && *next_buf != ',')
// With the exception of lines starting with a comma, the last character of any
// legitimate continuation line can't be a colon because expressions can't end
// in a colon. The only exception is the ternary operator's colon, but that is
// very rare because it requires the line after it also be a continuation line
// or section, which is unusual to say the least -- so much so that it might be
// too obscure to even document as a known limitation. Anyway, by excluding lines
// that end with a colon from consideration ambiguity with normal labels
// and non-single-line hotkeys and hotstrings is eliminated.
break;
is_continuation_line = false; // Set default.
switch(ctoupper(*next_buf)) // Above has ensured *next_buf != '\0' (toupper might have problems with '\0').
{
case 'A': // "AND".
// See comments in the default section further below.
if (!_tcsnicmp(next_buf, _T("and"), 3) && IS_SPACE_OR_TAB_OR_NBSP(next_buf[3])) // Relies on short-circuit boolean order.
{
cp = omit_leading_whitespace(next_buf + 3);
// v1.0.38.06: The following was fixed to use EXPR_CORE vs. EXPR_OPERAND_TERMINATORS
// to properly detect a continuation line whose first char after AND/OR is "!~*&-+()":
if (!_tcschr(EXPR_CORE, *cp))
// This check recognizes the following examples as NON-continuation lines by checking
// that AND/OR aren't followed immediately by something that's obviously an operator:
// and := x, and = 2 (but not and += 2 since the an operand can have a unary plus/minus).
// This is done for backward compatibility. Also, it's documented that
// AND/OR/NOT aren't supported as variable names inside expressions.
is_continuation_line = true; // Override the default set earlier.
}
break;
case 'O': // "OR".
// See comments in the default section further below.
if (ctoupper(next_buf[1]) == 'R' && IS_SPACE_OR_TAB_OR_NBSP(next_buf[2])) // Relies on short-circuit boolean order.
{
cp = omit_leading_whitespace(next_buf + 2);
// v1.0.38.06: The following was fixed to use EXPR_CORE vs. EXPR_OPERAND_TERMINATORS
// to properly detect a continuation line whose first char after AND/OR is "!~*&-+()":
if (!_tcschr(EXPR_CORE, *cp)) // See comment in the "AND" case above.
is_continuation_line = true; // Override the default set earlier.
}
break;
default:
// Desired line continuation operators:
// Pretty much everything, namely:
// +, -, *, /, //, **, <<, >>, &, |, ^, <, >, <=, >=, =, ==, <>, !=, :=, +=, -=, /=, *=, ?, :
// And also the following remaining unaries (i.e. those that aren't also binaries): !, ~
// The first line below checks for ::, ++, and --. Those can't be continuation lines because:
// "::" isn't a valid operator (this also helps performance if there are many hotstrings).
// ++ and -- are ambiguous with an isolated line containing ++Var or --Var (and besides,
// wanting to use ++ to continue an expression seems extremely rare, though if there's ever
// demand for it, might be able to look at what lies to the right of the operator's operand
// -- though that would produce inconsistent continuation behavior since ++Var itself still
// could never be a continuation line due to ambiguity).
//
// The logic here isn't smart enough to differentiate between a leading ! or - that's
// meant as a continuation character and one that isn't. Even if it were, it would
// still be ambiguous in some cases because the author's intent isn't known; for example,
// the leading minus sign on the second line below is ambiguous, so will probably remain
// a continuation character in both v1 and v2:
// x := y
// -z ? a:=1 : func()
if ((*next_buf == ':' || *next_buf == '+' || *next_buf == '-') && next_buf[1] == *next_buf // See above.
// L31: '.' and '?' no longer require spaces; '.' without space is member-access (object) operator.
//|| (*next_buf == '.' || *next_buf == '?') && !IS_SPACE_OR_TAB_OR_NBSP(next_buf[1]) // The "." and "?" operators require a space or tab after them to be legitimate. For ".", this is done in case period is ever a legal character in var names, such as struct support. For "?", it's done for backward compatibility since variable names can contain question marks (though "?" by itself is not considered a variable in v1.0.46).
//&& next_buf[1] != '=' // But allow ".=" (and "?=" too for code simplicity), since ".=" is the concat-assign operator.
|| !_tcschr(CONTINUATION_LINE_SYMBOLS, *next_buf)) // Line doesn't start with a continuation char.
break; // Leave is_continuation_line set to its default of false.
// Some of the above checks must be done before the next ones.
if ( !(hotkey_flag = _tcsstr(next_buf, HOTKEY_FLAG)) ) // Without any "::", it can't be a hotkey or hotstring.
{
is_continuation_line = true; // Override the default set earlier.
break;
}
#ifndef MINIDLL
if (*next_buf == ':') // First char is ':', so it's more likely a hotstring than a hotkey.
{
// Remember that hotstrings can contain what *appear* to be quoted literal strings,
// so detecting whether a "::" is in a quoted/literal string in this case would
// be more complicated. That's one reason this other method is used.
for (hotstring_options_all_valid = true, cp = next_buf + 1; *cp && *cp != ':'; ++cp)
if (!IS_HOTSTRING_OPTION(*cp)) // Not a perfect test, but eliminates most of what little remaining ambiguity exists between ':' as a continuation character vs. ':' as the start of a hotstring. It especially eliminates the ":=" operator.
{
hotstring_options_all_valid = false;
break;
}
if (hotstring_options_all_valid && *cp == ':') // It's almost certainly a hotstring.
break; // So don't treat it as a continuation line.
//else it's not a hotstring but it might still be a hotkey such as ": & x::".
// So continue checking below.
}
#endif
// Since above didn't "break", this line isn't a hotstring but it is probably a hotkey
// because above already discovered that it contains "::" somewhere. So try to find out
// if there's anything that disqualifies this from being a hotkey, such as some
// expression line that contains a quoted/literal "::" (or a line starting with
// a comma that contains an unquoted-but-literal "::" such as for FileAppend).
if (*next_buf == ',')
{
cp = omit_leading_whitespace(next_buf + 1);
// The above has set cp to the position of the non-whitespace item to the right of
// this comma. Normal (single-colon) labels can't contain commas, so only hotkey
// labels are sources of ambiguity. In addition, normal labels and hotstrings have
// already been checked for, higher above.
#ifndef MINIDLL
if ( _tcsncmp(cp, HOTKEY_FLAG, HOTKEY_FLAG_LENGTH) // It's not a hotkey such as ",::action".
&& _tcsncmp(cp - 1, COMPOSITE_DELIMITER, COMPOSITE_DELIMITER_LENGTH) ) // ...and it's not a hotkey such as ", & y::action".
#endif
is_continuation_line = true; // Override the default set earlier.
}
else // First symbol in line isn't a comma but some other operator symbol.
{
// Check if the "::" found earlier appears to be inside a quoted/literal string.
// This check is NOT done for a line beginning with a comma since such lines
// can contain an unquoted-but-literal "::". In addition, this check is done this
// way to detect hotkeys such as the following:
// +keyname:: (and other hotkey modifier symbols such as ! and ^)
// +keyname1 & keyname2::
// +^:: (i.e. a modifier symbol followed by something that is a hotkey modifier and/or a hotkey suffix and/or an expression operator).
// <:: and &:: (i.e. hotkeys that are also expression-continuation symbols)
// By contrast, expressions that qualify as continuation lines can look like:
// . "xxx::yyy"
// + x . "xxx::yyy"
// In addition, hotkeys like the following should continue to be supported regardless
// of how things are done here:
// ^"::
// . & "::
// Finally, keep in mind that an expression-continuation line can start with two
// consecutive unary operators like !! or !*. It can also start with a double-symbol
// operator such as <=, <>, !=, &&, ||, //, **.
for (cp = next_buf; cp < hotkey_flag && *cp != '"'; ++cp);
if (cp == hotkey_flag) // No '"' found to left of "::", so this "::" appears to be a real hotkey flag rather than part of a literal string.
break; // Treat this line as a normal line vs. continuation line.
for (cp = hotkey_flag + HOTKEY_FLAG_LENGTH; *cp && *cp != '"'; ++cp);
if (*cp)
{
// Closing quote was found so "::" is probably inside a literal string of an
// expression (further checking seems unnecessary given the fairly extreme
// rarity of using '"' as a key in a hotkey definition).
is_continuation_line = true; // Override the default set earlier.
}
//else no closing '"' found, so this "::" probably belongs to something like +":: or
// . & "::. Treat this line as a normal line vs. continuation line.
}
} // switch(toupper(*next_buf))
if (is_continuation_line)
{
if (buf_length + next_buf_length >= LINE_SIZE - 1) // -1 to account for the extra space added below.
+ {
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(ERR_CONTINUATION_SECTION_TOO_LONG, next_buf);
+ }
if (*next_buf != ',') // Insert space before expression operators so that built/combined expression works correctly (some operators like 'and', 'or', '.', and '?' currently require spaces on either side) and also for readability of ListLines.
buf[buf_length++] = ' ';
tmemcpy(buf + buf_length, next_buf, next_buf_length + 1); // Append this line to prev. and include the zero terminator.
buf_length += next_buf_length;
continue; // Check for yet more continuation lines after this one.
}
// Since above didn't continue, there is no continuation line or section. In addition,
// since this line isn't blank, no further searching is needed.
break;
} // if (!in_continuation_section)
// OTHERWISE in_continuation_section != 0, so the above has found the first line of a new
// continuation section.
continuation_line_count = 0; // Reset for this new section.
// Otherwise, parse options. First set the defaults, which can be individually overridden
// by any options actually present. RTrim defaults to ON for two reasons:
// 1) Whitespace often winds up at the end of a lines in a text editor by accident. In addition,
// whitespace at the end of any consolidated/merged line will be rtrim'd anyway, since that's
// how command parsing works.
// 2) Copy & paste from the forum and perhaps other web sites leaves a space at the end of each
// line. Although this behavior is probably site/browser-specific, it's a consideration.
do_ltrim = g_ContinuationLTrim; // Start off at global default.
do_rtrim = true; // Seems best to rtrim even if this line is a hotstring, since it is very rare that trailing spaces and tabs would ever be desirable.
// For hotstrings (which could be detected via *buf==':'), it seems best not to default the
// escape character (`) to be literal because the ability to have `t `r and `n inside the
// hotstring continuation section seems more useful/common than the ability to use the
// accent character by itself literally (which seems quite rare in most languages).
literal_escapes = false;
literal_derefs = false;
literal_delimiters = true; // This is the default even for hotstrings because although using (*buf != ':') would improve loading performance, it's not a 100% reliable way to detect hotstrings.
// The default is linefeed because:
// 1) It's the best choice for hotstrings, for which the line continuation mechanism is well suited.
// 2) It's good for FileAppend.
// 3) Minor: Saves memory in large sections by being only one character instead of two.
suffix[0] = '\n';
suffix[1] = '\0';
suffix_length = 1;
for (next_option = omit_leading_whitespace(next_buf + 1); *next_option; next_option = omit_leading_whitespace(option_end))
{
// Find the end of this option item:
if ( !(option_end = StrChrAny(next_option, _T(" \t"))) ) // Space or tab.
option_end = next_option + _tcslen(next_option); // Set to position of zero terminator instead.
// Temporarily terminate to help eliminate ambiguity for words contained inside other words,
// such as hypothetical "Checked" inside of "CheckedGray":
orig_char = *option_end;
*option_end = '\0';
if (!_tcsnicmp(next_option, _T("Join"), 4))
{
next_option += 4;
tcslcpy(suffix, next_option, _countof(suffix)); // The word "Join" by itself will product an empty string, as documented.
// Passing true for the last parameter supports `s as the special escape character,
// which allows space to be used by itself and also at the beginning or end of a string
// containing other chars.
ConvertEscapeSequences(suffix, g_EscapeChar, true);
suffix_length = _tcslen(suffix);
}
else if (!_tcsnicmp(next_option, _T("LTrim"), 5))
do_ltrim = (next_option[5] != '0'); // i.e. Only an explicit zero will turn it off.
else if (!_tcsnicmp(next_option, _T("RTrim"), 5))
do_rtrim = (next_option[5] != '0');
else
{
// Fix for v1.0.36.01: Missing "else" above, because otherwise, the option Join`r`n
// would be processed above but also be processed again below, this time seeing the
// accent and thinking it's the signal to treat accents literally for the entire
// continuation section rather than as escape characters.
// Within this terminated option substring, allow the characters to be adjacent to
// improve usability:
for (; *next_option; ++next_option)
{
switch (*next_option)
{
case '`': // Although not using g_EscapeChar (reduces code size/complexity), #EscapeChar is still supported by continuation sections; it's just that enabling the option uses '`' rather than the custom escape-char (one reason is that that custom escape-char might be ambiguous with future/past options if it's something weird like an alphabetic character).
literal_escapes = true;
break;
case '%': // Same comment as above.
literal_derefs = true;
break;
case ',': // Same comment as above.
literal_delimiters = false;
break;
case 'C': // v1.0.45.03: For simplicity, anything that begins with "C" is enough to
case 'c': // identify it as the option to allow comments in the section.
in_continuation_section = CONTINUATION_SECTION_WITH_COMMENTS; // Override the default, which is boolean true (i.e. 1).
break;
case ')':
// Probably something like (x.y)[z](), which is not intended as the beginning of
// a continuation section. Doing this only when ")" is found should remove the
// need to escape "(" in most real-world expressions while still allowing new
// options to be added later with minimal risk of breaking scripts.
in_continuation_section = 0;
*option_end = orig_char; // Undo the temporary termination.
goto process_completed_line;
}
}
}
// If the item was not handled by the above, ignore it because it is unknown.
*option_end = orig_char; // Undo the temporary termination.
} // for() each item in option list
// "has_continuation_section" indicates whether the line we're about to construct is partially
// composed of continuation lines beneath it. It's separate from continuation_line_count
// in case there is another continuation section immediately after/adjacent to the first one,
// but the second one doesn't have any lines in it:
has_continuation_section = true;
continue; // Now that the open-parenthesis of this continuation section has been processed, proceed to the next line.
} // if (!in_continuation_section)
// Since above didn't "continue", we're in the continuation section and thus next_buf contains
// either a line to be appended onto buf or the closing parenthesis of this continuation section.
if (next_buf_length == -1) // Compare directly to -1 since length is unsigned.
+ {
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(ERR_MISSING_CLOSE_PAREN, buf);
+ }
if (next_buf_length == -2) // v1.0.45.03: Special flag that means "this is a commented-out line to be
continue; // entirely omitted from the continuation section." Compare directly to -2 since length is unsigned.
if (*next_buf == ')')
{
in_continuation_section = 0; // Facilitates back-to-back continuation sections and proper incrementing of phys_line_number.
next_buf_length = rtrim(next_buf); // Done because GetLine() wouldn't have done it due to have told it we're in a continuation section.
// Anything that lies to the right of the close-parenthesis gets appended verbatim, with
// no trimming (for flexibility) and no options-driven translation:
cp = next_buf + 1; // Use temp var cp to avoid altering next_buf (for maintainability).
--next_buf_length; // This is now the length of cp, not next_buf.
}
else
{
cp = next_buf;
// The following are done in this block only because anything that comes after the closing
// parenthesis (i.e. the block above) is exempt from translations and custom trimming.
// This means that commas are always delimiters and percent signs are always deref symbols
// in the previous block.
if (do_rtrim)
next_buf_length = rtrim(next_buf, next_buf_length);
if (do_ltrim)
next_buf_length = ltrim(next_buf, next_buf_length);
// Escape each comma and percent sign in the body of the continuation section so that
// the later parsing stages will see them as literals. Although, it's not always
// necessary to do this (e.g. commas in the last parameter of a command don't need to
// be escaped, nor do percent signs in hotstrings' auto-replace text), the settings
// are applied unconditionally because:
// 1) Determining when its safe to omit the translation would add a lot of code size and complexity.
// 2) The translation doesn't affect the functionality of the script since escaped literals
// are always de-escaped at a later stage, at least for everything that's likely to matter
// or that's reasonable to put into a continuation section (e.g. a hotstring's replacement text).
// UPDATE for v1.0.44.11: #EscapeChar, #DerefChar, #Delimiter are now supported by continuation
// sections because there were some requests for that in forum.
int replacement_count = 0;
if (literal_escapes) // literal_escapes must be done FIRST because otherwise it would also replace any accents added for literal_delimiters or literal_derefs.
{
one_char_string[0] = g_EscapeChar; // These strings were terminated earlier, so no need to
two_char_string[0] = g_EscapeChar; // do it here. In addition, these strings must be set by
two_char_string[1] = g_EscapeChar; // each iteration because the #EscapeChar (and similar directives) can occur multiple times, anywhere in the script.
replacement_count += StrReplace(next_buf, one_char_string, two_char_string, SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
}
if (literal_derefs)
{
one_char_string[0] = g_DerefChar;
two_char_string[0] = g_EscapeChar;
two_char_string[1] = g_DerefChar;
replacement_count += StrReplace(next_buf, one_char_string, two_char_string, SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
}
if (literal_delimiters)
{
one_char_string[0] = g_delimiter;
two_char_string[0] = g_EscapeChar;
two_char_string[1] = g_delimiter;
replacement_count += StrReplace(next_buf, one_char_string, two_char_string, SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
}
if (replacement_count) // Update the length if any actual replacements were done.
next_buf_length = _tcslen(next_buf);
} // Handling of a normal line within a continuation section.
// Must check the combined length only after anything that might have expanded the string above.
if (buf_length + next_buf_length + suffix_length >= LINE_SIZE)
+ {
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(ERR_CONTINUATION_SECTION_TOO_LONG, cp);
+ }
++continuation_line_count;
// Append this continuation line onto the primary line.
// The suffix for the previous line gets written immediately prior writing this next line,
// which allows the suffix to be omitted for the final line. But if this is the first line,
// No suffix is written because there is no previous line in the continuation section.
// In addition, cp!=next_buf, this is the special line whose text occurs to the right of the
// continuation section's closing parenthesis. In this case too, the previous line doesn't
// get a suffix.
if (continuation_line_count > 1 && suffix_length && cp == next_buf)
{
tmemcpy(buf + buf_length, suffix, suffix_length + 1); // Append and include the zero terminator.
buf_length += suffix_length; // Must be done only after the old value of buf_length was used above.
}
if (next_buf_length)
{
tmemcpy(buf + buf_length, cp, next_buf_length + 1); // Append this line to prev. and include the zero terminator.
buf_length += next_buf_length; // Must be done only after the old value of buf_length was used above.
}
} // for() each sub-line (continued line) that composes this line.
process_completed_line:
// buf_length can't be -1 (though next_buf_length can) because outer loop's condition prevents it:
if (!buf_length) // Done only after the line number increments above so that the physical line number is properly tracked.
goto continue_main_loop; // In lieu of "continue", for performance.
// Since neither of the above executed, or they did but didn't "continue",
// buf now contains a non-commented line, either by itself or built from
// any continuation sections/lines that might have been present. Also note that
// by design, phys_line_number will be greater than mCombinedLineNumber whenever
// a continuation section/lines were used to build this combined line.
// If there's a previous line waiting to be processed, its fate can now be determined based on the
// nature of *this* line:
if (*pending_buf)
{
// Somewhat messy to decrement then increment later, but it's probably easier than the
// alternatives due to the use of "continue" in some places above. NOTE: phys_line_number
// would not need to be decremented+incremented even if the below resulted in a recursive
// call to us (though it doesn't currently) because line_number's only purpose is to
// remember where this layer left off when the recursion collapses back to us.
// Fix for v1.0.31.05: It's not enough just to decrement mCombinedLineNumber because there
// might be some blank lines or commented-out lines between this function call/definition
// and the line that follows it, each of which will have previously incremented mCombinedLineNumber.
saved_line_number = mCombinedLineNumber;
mCombinedLineNumber = pending_buf_line_number; // Done so that any syntax errors that occur during the calls below will report the correct line number.
// Open brace means this is a function definition. NOTE: buf was already ltrimmed by GetLine().
// Could use *g_act[ACT_BLOCK_BEGIN].Name instead of '{', but it seems too elaborate to be worth it.
if (*buf == '{' || pending_buf_has_brace) // v1.0.41: Support one-true-brace, e.g. fn(...) {
{
switch (pending_buf_type)
{
case Pending_Class:
if (!DefineClass(pending_buf))
- return FAIL;
+ goto FAIL;
break;
case Pending_Property:
if (!DefineClassProperty(pending_buf))
- return FAIL;
+ goto FAIL;
break;
case Pending_Func:
// Note that two consecutive function definitions aren't possible:
// fn1()
// fn2()
// {
// ...
// }
// In the above, the first would automatically be deemed a function call by means of
// the check higher above (by virtue of the fact that the line after it isn't an open-brace).
if (g->CurrentFunc)
{
// Though it might be allowed in the future -- perhaps to have nested functions have
// access to their parent functions' local variables, or perhaps just to improve
// script readability and maintainability -- it's currently not allowed because of
// the practice of maintaining the func_global_var list on our stack:
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(_T("Functions cannot contain functions."), pending_buf);
}
if (!DefineFunc(pending_buf, func_global_var))
- return FAIL;
+ goto FAIL;
if (pending_buf_has_brace) // v1.0.41: Support one-true-brace for function def, e.g. fn() {
{
if (!AddLine(ACT_BLOCK_BEGIN))
- return FAIL;
+ goto FAIL;
mCurrLine = NULL; // L30: Prevents showing misleading vicinity lines if the line after a OTB function def is a syntax error.
}
break;
#ifdef _DEBUG
default:
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(_T("DEBUG: pending_buf_type has an unexpected value."));
#endif
}
}
else // It's a function call on a line by itself, such as fn(x). It can't be if(..) because another section checked that.
{
if (pending_buf_type != Pending_Func) // Missing open-brace for class definition.
+ {
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(ERR_MISSING_OPEN_BRACE, pending_buf);
+ }
if (mClassObjectCount && !g->CurrentFunc) // Unexpected function call in class definition.
+ {
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(mClassProperty ? ERR_MISSING_OPEN_BRACE : ERR_INVALID_LINE_IN_CLASS_DEF, pending_buf);
+ }
if (!ParseAndAddLine(pending_buf, ACT_EXPRESSION))
- return FAIL;
+ goto FAIL;
mCurrLine = NULL; // Prevents showing misleading vicinity lines if the line after a function call is a syntax error.
}
*pending_buf = '\0'; // Reset now that it's been fully handled, as an indicator for subsequent iterations.
if (pending_buf_type != Pending_Func) // Class or property.
{
if (!pending_buf_has_brace)
{
// This is the open-brace of a class definition, so requires no further processing.
if ( !*(cp = omit_leading_whitespace(buf + 1)) )
{
mCombinedLineNumber = saved_line_number;
goto continue_main_loop;
}
// Otherwise, there's something following the "{", possibly "}" or a function definition.
tmemmove(buf, cp, (buf_length = _tcslen(cp)) + 1);
}
}
mCombinedLineNumber = saved_line_number;
// Now fall through to the below so that *this* line (the one after it) will be processed.
// Note that this line might be a pre-processor directive, label, etc. that won't actually
// become a runtime line per se.
} // if (*pending_function)
if (*buf == '}' && mClassObjectCount && !g->CurrentFunc)
{
cp = buf;
if (mClassProperty)
{
// Close this property definition.
mClassProperty = NULL;
if (mClassPropertyDef)
{
free(mClassPropertyDef);
mClassPropertyDef = NULL;
}
cp = omit_leading_whitespace(cp + 1);
}
// Handling this before the two sections below allows a function or class definition
// to begin immediately after the close-brace of a previous class definition.
// This loop allows something like }}} to terminate multiple nested classes:
for ( ; *cp == '}' && mClassObjectCount; cp = omit_leading_whitespace(cp + 1))
{
// End of class definition.
--mClassObjectCount;
mClassObject[mClassObjectCount]->EndClassDefinition(); // Remove instance variables from the class object.
mClassObject[mClassObjectCount]->Release();
// Revert to the name of the class this class is nested inside, or "" if none.
if (cp1 = _tcsrchr(mClassName, '.'))
*cp1 = '\0';
else
*mClassName = '\0';
}
// cp now points at the next non-whitespace char after the brace.
if (!*cp)
goto continue_main_loop;
// Otherwise, there is something following this close-brace, so continue on below to process it.
tmemmove(buf, cp, buf_length = _tcslen(cp));
}
if (mClassProperty && !g->CurrentFunc) // This is checked before IsFunction() to prevent method definitions inside a property.
{
if (!_tcsnicmp(buf, _T("Get"), 3) || !_tcsnicmp(buf, _T("Set"), 3))
{
LPTSTR cp = omit_leading_whitespace(buf + 3);
if ( !*cp || (*cp == '{' && !cp[1]) )
{
// Defer this line until the next line comes in to simplify handling of '{' and OTB.
// For simplicity, pass the property definition to DefineFunc instead of the actual
// line text, even though it makes some error messages a bit inaccurate. (That would
// happen anyway when DefineFunc() finds a syntax error in the parameter list.)
_tcscpy(pending_buf, mClassPropertyDef);
LPTSTR dot = _tcschr(pending_buf, '.');
dot[1] = *buf; // Replace the x in property.xet(params).
pending_buf_line_number = mCombinedLineNumber;
pending_buf_has_brace = *cp == '{';
pending_buf_type = Pending_Func;
goto continue_main_loop;
}
}
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(ERR_INVALID_LINE_IN_PROPERTY_DEF, buf);
}
// By doing the following section prior to checking for hotkey and hotstring labels, double colons do
// not need to be escaped inside naked function calls and function definitions such as the following:
// fn("::") ; Function call.
// fn(Str="::") ; Function definition with default value for its parameter.
if (IsFunction(buf, &pending_buf_has_brace)) // If true, it's either a function definition or a function call (to be distinguished later).
{
// Defer this line until the next line comes in, which helps determine whether this line is
// a function call vs. definition:
_tcscpy(pending_buf, buf);
pending_buf_line_number = mCombinedLineNumber;
pending_buf_type = Pending_Func;
goto continue_main_loop; // In lieu of "continue", for performance.
}
if (!g->CurrentFunc)
{
if (LPTSTR class_name = IsClassDefinition(buf, pending_buf_has_brace))
{
// Defer this line until the next line comes in to simplify handling of '{' and OTB:
_tcscpy(pending_buf, class_name);
pending_buf_line_number = mCombinedLineNumber;
pending_buf_type = Pending_Class;
goto continue_main_loop; // In lieu of "continue", for performance.
}
if (mClassObjectCount)
{
// Check for assignment first, in case of something like "Static := 123".
for (cp = buf; cisalnum(*cp) || *cp == '_' || *cp == '.'; ++cp);
if (cp > buf) // i.e. buf begins with an identifier.
{
cp = omit_leading_whitespace(cp);
if (*cp == ':' && cp[1] == '=') // This is an assignment.
{
if (!DefineClassVars(buf, false)) // See above for comments.
- return FAIL;
+ goto FAIL;
goto continue_main_loop;
}
if ( !*cp || *cp == '[' || (*cp == '{' && !cp[1]) ) // Property
{
size_t length = _tcslen(buf);
if (pending_buf_has_brace = (buf[length - 1] == '{'))
{
// Omit '{' and trailing whitespace from further consideration.
rtrim(buf, length - 1);
}
// Defer this line until the next line comes in to simplify handling of '{' and OTB:
_tcscpy(pending_buf, buf);
pending_buf_line_number = mCombinedLineNumber;
pending_buf_type = Pending_Property;
goto continue_main_loop; // In lieu of "continue", for performance.
}
}
if (!_tcsnicmp(buf, _T("Static"), 6) && IS_SPACE_OR_TAB(buf[6]))
{
if (!DefineClassVars(buf + 7, true))
- return FAIL; // Above already displayed the error.
+ goto FAIL; // Above already displayed the error.
goto continue_main_loop; // In lieu of "continue", for performance.
}
if (*buf == '#') // See the identical section further below for comments.
{
saved_line_number = mCombinedLineNumber;
switch(IsDirective(buf))
{
case CONDITION_TRUE:
mCurrFileIndex = source_file_index;
mCombinedLineNumber = saved_line_number;
goto continue_main_loop;
case FAIL:
- return FAIL;
+ goto FAIL;
}
}
// Anything not already handled above is not valid directly inside a class definition.
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(ERR_INVALID_LINE_IN_CLASS_DEF, buf);
}
}
// The following "examine_line" label skips the following parts above:
// 1) IsFunction() because that's only for a function call or definition alone on a line
// e.g. not "if fn()" or x := fn(). Those who goto this label don't need that processing.
// 2) The "if (*pending_function)" block: Doesn't seem applicable for the callers of this label.
// 3) The inner loop that handles continuation sections: Not needed by the callers of this label.
// 4) Things like the following should be skipped because callers of this label don't want the
// physical line number changed (which would throw off the count of lines that lie beneath a remap):
// mCombinedLineNumber = phys_line_number + 1;
// ++phys_line_number;
// 5) "mCurrLine = NULL": Probably not necessary since it's only for error reporting. Worst thing
// that could happen is that syntax errors would be thrown off, which testing shows isn't the case.
examine_line:
#ifndef MINIDLL
// "::" alone isn't a hotstring, it's a label whose name is colon.
// Below relies on the fact that no valid hotkey can start with a colon, since
// ": & somekey" is not valid (since colon is a shifted key) and colon itself
// should instead be defined as "+;::". It also relies on short-circuit boolean:
hotstring_start = NULL;
hotstring_options = NULL; // Set default as "no options were specified for this hotstring".
hotkey_flag = NULL;
if (buf[0] == ':' && buf[1])
{
if (buf[1] != ':')
{
hotstring_options = buf + 1; // Point it to the hotstring's option letters.
// The following relies on the fact that options should never contain a literal colon.
// ALSO, the following doesn't use IS_HOTSTRING_OPTION() for backward compatibility,
// performance, and because it seems seldom if ever necessary at this late a stage.
if ( !(hotstring_start = _tcschr(hotstring_options, ':')) )
hotstring_start = NULL; // Indicate that this isn't a hotstring after all.
else
++hotstring_start; // Points to the hotstring itself.
}
else // Double-colon, so it's a hotstring if there's more after this (but this means no options are present).
if (buf[2])
hotstring_start = buf + 2; // And leave hotstring_options at its default of NULL to indicate no options.
//else it's just a naked "::", which is considered to be an ordinary label whose name is colon.
}
if (hotstring_start)
{
// Find the hotstring's final double-colon by considering escape sequences from left to right.
// This is necessary for to handles cases such as the following:
// ::abc```::::Replacement String
// The above hotstring translates literally into "abc`::".
LPTSTR escaped_double_colon = NULL;
for (cp = hotstring_start; ; ++cp) // Increment to skip over the symbol just found by the inner for().
{
for (; *cp && *cp != g_EscapeChar && *cp != ':'; ++cp); // Find the next escape char or colon.
if (!*cp) // end of string.
break;
cp1 = cp + 1;
if (*cp == ':')
{
if (*cp1 == ':') // Found a non-escaped double-colon, so this is the right one.
{
hotkey_flag = cp++; // Increment to have loop skip over both colons.
// and the continue with the loop so that escape sequences in the replacement
// text (if there is replacement text) are also translated.
}
// else just a single colon, or the second colon of an escaped pair (`::), so continue.
continue;
}
switch (*cp1)
{
// Only lowercase is recognized for these:
case 'a': *cp1 = '\a'; break; // alert (bell) character
case 'b': *cp1 = '\b'; break; // backspace
case 'f': *cp1 = '\f'; break; // formfeed
case 'n': *cp1 = '\n'; break; // newline
case 'r': *cp1 = '\r'; break; // carriage return
case 't': *cp1 = '\t'; break; // horizontal tab
case 'v': *cp1 = '\v'; break; // vertical tab
// Otherwise, if it's not one of the above, the escape-char is considered to
// mark the next character as literal, regardless of what it is. Examples:
// `` -> `
// `:: -> :: (effectively)
// `; -> ;
// `c -> c (i.e. unknown escape sequences resolve to the char after the `)
}
// Below has a final +1 to include the terminator:
tmemmove(cp, cp1, _tcslen(cp1) + 1);
// Since single colons normally do not need to be escaped, this increments one extra
// for double-colons to skip over the entire pair so that its second colon
// is not seen as part of the hotstring's final double-colon. Example:
// ::ahc```::::Replacement String
if (*cp == ':' && *cp1 == ':')
++cp;
} // for()
if (!hotkey_flag)
hotstring_start = NULL; // Indicate that this isn't a hotstring after all.
}
if (!hotstring_start) // Not a hotstring (hotstring_start is checked *again* in case above block changed it; otherwise hotkeys like ": & x" aren't recognized).
{
// Note that there may be an action following the HOTKEY_FLAG (on the same line).
if (hotkey_flag = _tcsstr(buf, HOTKEY_FLAG)) // Find the first one from the left, in case there's more than 1.
{
if (hotkey_flag == buf && hotkey_flag[2] == ':') // v1.0.46: Support ":::" to mean "colon is a hotkey".
++hotkey_flag;
// v1.0.40: It appears to be a hotkey, but validate it as such before committing to processing
// it as a hotkey. If it fails validation as a hotkey, treat it as a command that just happens
// to contain a double-colon somewhere. This avoids the need to escape double colons in scripts.
// Note: Hotstrings can't suffer from this type of ambiguity because a leading colon or pair of
// colons makes them easier to detect.
cp = omit_trailing_whitespace(buf, hotkey_flag); // For maintainability.
orig_char = *cp;
*cp = '\0'; // Temporarily terminate.
if (!Hotkey::TextInterpret(omit_leading_whitespace(buf), NULL, false)) // Passing NULL calls it in validate-only mode.
hotkey_flag = NULL; // It's not a valid hotkey, so indicate that it's a command (i.e. one that contains a literal double-colon, which avoids the need to escape the double-colon).
*cp = orig_char; // Undo the temp. termination above.
}
}
// Treat a naked "::" as a normal label whose label name is colon:
if (is_label = (hotkey_flag && hotkey_flag > buf)) // It's a hotkey/hotstring label.
{
if (g->CurrentFunc)
{
// Even if it weren't for the reasons below, the first hotkey/hotstring label in a script
// will end the auto-execute section with a "return". Therefore, if this restriction here
// is ever removed, be sure that that extra return doesn't get put inside the function.
//
// The reason for not allowing hotkeys and hotstrings inside a function's body is that
// when the subroutine is launched, the hotstring/hotkey would be using the function's
// local variables. But that is not appropriate and it's likely to cause problems even
// if it were. It doesn't seem useful in any case. By contrast, normal labels can
// safely exist inside a function body and since the body is a block, other validation
// ensures that a Gosub or Goto can't jump to it from outside the function.
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(_T("Hotkeys/hotstrings are not allowed inside functions."), buf);
}
if (mLastLine && mLastLine->mActionType == ACT_IFWINACTIVE)
{
mCurrLine = mLastLine; // To show vicinity lines.
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(_T("IfWin should be #IfWin."), buf);
}
*hotkey_flag = '\0'; // Terminate so that buf is now the label itself.
hotkey_flag += HOTKEY_FLAG_LENGTH; // Now hotkey_flag is the hotkey's action, if any.
if (!hotstring_start)
{
ltrim(hotkey_flag); // Has already been rtrimmed by GetLine().
rtrim(buf); // Trim the new substring inside of buf (due to temp termination). It has already been ltrimmed.
cp = hotkey_flag; // Set default, conditionally overridden below (v1.0.44.07).
// v1.0.40: Check if this is a remap rather than hotkey:
if ( *hotkey_flag // This hotkey's action is on the same line as its label.
&& (remap_source_vk = TextToVK(cp1 = Hotkey::TextToModifiers(buf, NULL)))
&& (remap_dest_vk = hotkey_flag[1] ? TextToVK(cp = Hotkey::TextToModifiers(hotkey_flag, NULL)) : 0xFF) ) // And the action appears to be a remap destination rather than a command.
// For above:
// Fix for v1.0.44.07: Set remap_dest_vk to 0xFF if hotkey_flag's length is only 1 because:
// 1) It allows a destination key that doesn't exist in the keyboard layout (such as 6::ð in
// English).
// 2) It improves performance a little by not calling TextToVK except when the destination key
// might be a mouse button or some longer key name whose actual/correct VK value is relied
// upon by other places below.
// Fix for v1.0.40.01: Since remap_dest_vk is also used as the flag to indicate whether
// this line qualifies as a remap, must do it last in the statement above. Otherwise,
// the statement might short-circuit and leave remap_dest_vk as non-zero even though
// the line shouldn't be a remap. For example, I think a hotkey such as "x & y::return"
// would trigger such a bug.
{
// These will be ignored in other stages if it turns out not to be a remap later below:
remap_source_is_mouse = IsMouseVK(remap_source_vk);
remap_dest_is_mouse = IsMouseVK(remap_dest_vk);
remap_keybd_to_mouse = !remap_source_is_mouse && remap_dest_is_mouse;
sntprintf(remap_source, _countof(remap_source), _T("%s%s")
, _tcslen(cp1) == 1 && IsCharUpper(*cp1) ? _T("+") : _T("") // Allow A::b to be different than a::b.
, buf); // Include any modifiers too, e.g. ^b::c.
tcslcpy(remap_dest, cp, _countof(remap_dest)); // But exclude modifiers here; they're wanted separately.
tcslcpy(remap_dest_modifiers, hotkey_flag, _countof(remap_dest_modifiers));
if (cp - hotkey_flag < _countof(remap_dest_modifiers)) // Avoid reading beyond the end.
remap_dest_modifiers[cp - hotkey_flag] = '\0'; // Terminate at the proper end of the modifier string.
remap_stage = 0; // Init for use in the next stage.
// In the unlikely event that the dest key has the same name as a command, disqualify it
// from being a remap (as documented). v1.0.40.05: If the destination key has any modifiers,
// it is unambiguously a key name rather than a command, so the switch() isn't necessary.
if (*remap_dest_modifiers)
goto continue_main_loop; // It will see that remap_dest_vk is non-zero and act accordingly.
switch (remap_dest_vk)
{
case VK_CONTROL: // Checked in case it was specified as "Control" rather than "Ctrl".
case VK_SLEEP:
if (StrChrAny(hotkey_flag, _T(" \t,"))) // Not using g_delimiter (reduces code size/complexity).
break; // Any space, tab, or enter means this is a command rather than a remap destination.
goto continue_main_loop; // It will see that remap_dest_vk is non-zero and act accordingly.
// "Return" and "Pause" as destination keys are always considered commands instead.
// This is documented and is done to preserve backward compatibility.
case VK_RETURN:
// v1.0.40.05: Although "Return" can't be a destination, "Enter" can be. Must compare
// to "Return" not "Enter" so that things like "vk0d" (the VK of "Enter") can also be a
// destination key:
if (!_tcsicmp(remap_dest, _T("Return")))
break;
goto continue_main_loop; // It will see that remap_dest_vk is non-zero and act accordingly.
case VK_PAUSE: // Used for both "Pause" and "Break"
break;
default: // All other VKs are valid destinations and thus the remap is valid.
goto continue_main_loop; // It will see that remap_dest_vk is non-zero and act accordingly.
}
// Since above didn't goto, indicate that this is not a remap after all:
remap_dest_vk = 0;
}
}
// else don't trim hotstrings since literal spaces in both substrings are significant.
// If this is the first hotkey label encountered, Add a return before
// adding the label, so that the auto-execute section is terminated.
// Only do this if the label is a hotkey because, for example,
// the user may want to fully execute a normal script that contains
// no hotkeys but does contain normal labels to which the execution
// should fall through, if specified, rather than returning.
// But this might result in weirdness? Example:
//testlabel:
// Sleep, 1
// return
// ^a::
// return
// It would put the hard return in between, which is wrong. But in the case above,
// the first sub shouldn't have a return unless there's a part up top that ends in Exit.
// So if Exit is encountered before the first hotkey, don't add the return?
// Even though wrong, the return is harmless because it's never executed? Except when
// falling through from above into a hotkey (which probably isn't very valid anyway)?
// Update: Below must check if there are any true hotkey labels, not just regular labels.
// Otherwise, a normal (non-hotkey) label in the autoexecute section would count and
// thus the RETURN would never be added here, even though it should be:
// Notes about the below macro:
// Fix for v1.0.34: Don't point labels to this particular RETURN so that labels
// can point to the very first hotkey or hotstring in a script. For example:
// Goto Test
// Test:
// ^!z::ToolTip Without the fix`, this is never displayed by "Goto Test".
// UCHAR_MAX signals it not to point any pending labels to this RETURN.
// mCurrLine = NULL -> signifies that we're in transition, trying to load a new one.
#define CHECK_mNoHotkeyLabels \
if (mNoHotkeyLabels)\
{\
mNoHotkeyLabels = false;\
if (!AddLine(ACT_RETURN, NULL, UCHAR_MAX))\
- return FAIL;\
+ goto FAIL;\
mCurrLine = NULL;\
}
CHECK_mNoHotkeyLabels
// For hotstrings, the below makes the label include leading colon(s) and the full option
// string (if any) so that the uniqueness of labels is preserved. For example, we want
// the following two hotstring labels to be unique rather than considered duplicates:
// ::abc::
// :c:abc::
if (!AddLabel(buf, true)) // Always add a label before adding the first line of its section.
- return FAIL;
+ goto FAIL;
hook_action = 0; // Set default.
if (*hotkey_flag) // This hotkey's action is on the same line as its label.
{
if (!hotstring_start)
// Don't add the alt-tabs as a line, since it has no meaning as a script command.
// But do put in the Return regardless, in case this label is ever jumped to
// via Goto/Gosub:
if ( !(hook_action = Hotkey::ConvertAltTab(hotkey_flag, false)) )
if (!ParseAndAddLine(hotkey_flag))
- return FAIL;
+ goto FAIL;
// Also add a Return that's implicit for a single-line hotkey. This is also
// done for auto-replace hotstrings in case gosub/goto is ever used to jump
// to their labels:
if (!AddLine(ACT_RETURN))
- return FAIL;
+ goto FAIL;
}
if (hotstring_start)
{
if (!*hotstring_start)
{
// The following error message won't indicate the correct line number because
// the hotstring (as a label) does not actually exist as a line. But it seems
// best to report it this way in case the hotstring is inside a #Include file,
// so that the correct file name and approximate line number are shown:
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(_T("This hotstring is missing its abbreviation."), buf); // Display buf vs. hotkey_flag in case the line is simply "::::".
}
// In the case of hotstrings, hotstring_start is the beginning of the hotstring itself,
// i.e. the character after the second colon. hotstring_options is NULL if no options,
// otherwise it's the first character in the options list (option string is not terminated,
// but instead ends in a colon). hotkey_flag is blank if it's not an auto-replace
// hotstring, otherwise it contains the auto-replace text.
// v1.0.42: Unlike hotkeys, duplicate hotstrings are not detected. This is because
// hotstrings are less commonly used and also because it requires more code to find
// hotstring duplicates (and performs a lot worse if a script has thousands of
// hotstrings) because of all the hotstring options.
if (!Hotstring::AddHotstring(mLastLabel, hotstring_options ? hotstring_options : _T("")
, hotstring_start, hotkey_flag, has_continuation_section))
- return FAIL;
+ goto FAIL;
}
else // It's a hotkey vs. hotstring.
{
if (hk = Hotkey::FindHotkeyByTrueNature(buf, suffix_has_tilde, hook_is_mandatory)) // Parent hotkey found. Add a child/variant hotkey for it.
{
if (hook_action) // suffix_has_tilde has always been ignored for these types (alt-tab hotkeys).
{
// Hotkey::Dynamic() contains logic and comments similar to this, so maintain them together.
// An attempt to add an alt-tab variant to an existing hotkey. This might have
// merit if the intention is to make it alt-tab now but to later disable that alt-tab
// aspect via the Hotkey cmd to let the context-sensitive variants shine through
// (take effect).
hk->mHookAction = hook_action;
}
else
{
// Detect duplicate hotkey variants to help spot bugs in scripts.
if (hk->FindVariant()) // See if there's already a variant matching the current criteria (suffix_has_tilde does not make variants distinct form each other because it would require firing two hotkey IDs in response to pressing one hotkey, which currently isn't in the design).
{
mCurrLine = NULL; // Prevents showing unhelpful vicinity lines.
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(_T("Duplicate hotkey."), buf);
}
if (!hk->AddVariant(mLastLabel, suffix_has_tilde))
+ {
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(ERR_OUTOFMEM, buf);
+ }
if (hook_is_mandatory || (!g_os.IsWin9x() && g_ForceKeybdHook))
{
// Require the hook for all variants of this hotkey if any variant requires it.
// This seems more intuitive than the old behaviour, which required $ or #UseHook
// to be used on the *first* variant, even though it affected all variants.
#ifdef CONFIG_WIN9X
if (g_os.IsWin9x())
hk->mUnregisterDuringThread = true;
else
#endif
hk->mKeybdHookMandatory = true;
}
}
}
else // No parent hotkey yet, so create it.
- if ( !(hk = Hotkey::AddHotkey(mLastLabel, hook_action, NULL, suffix_has_tilde, false)) )
- return FAIL; // It already displayed the error.
+ if (!(hk = Hotkey::AddHotkey(mLastLabel, hook_action, NULL, suffix_has_tilde, false)))
+ goto FAIL; // It already displayed the error.
}
goto continue_main_loop; // In lieu of "continue", for performance.
} // if (is_label = ...)
#endif
// Otherwise, not a hotkey or hotstring. Check if it's a generic, non-hotkey label:
if (buf[buf_length - 1] == ':') // Labels must end in a colon (buf was previously rtrimmed).
{
if (buf_length == 1) // v1.0.41.01: Properly handle the fact that this line consists of only a colon.
+ {
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(ERR_UNRECOGNIZED_ACTION, buf);
+ }
// Labels (except hotkeys) must contain no whitespace, delimiters, or escape-chars.
// This is to avoid problems where a legitimate action-line ends in a colon,
// such as "WinActivate SomeTitle" and "#Include c:".
// We allow hotkeys to violate this since they may contain commas, and since a normal
// script line (i.e. just a plain command) is unlikely to ever end in a double-colon:
for (cp = buf, is_label = true; *cp; ++cp)
if (IS_SPACE_OR_TAB(*cp) || *cp == g_delimiter || *cp == g_EscapeChar)
{
is_label = false;
break;
}
if (is_label) // It's a generic, non-hotkey/non-hotstring label.
{
// v1.0.44.04: Fixed this check by moving it after the above loop.
// Above has ensured buf_length>1, so it's safe to check for double-colon:
// v1.0.44.03: Don't allow anything that ends in "::" (other than a line consisting only
// of "::") to be a normal label. Assume it's a command instead (if it actually isn't, a
// later stage will report it as "invalid hotkey"). This change avoids the situation in
// which a hotkey like ^!ä:: is seen as invalid because the current keyboard layout doesn't
// have a "ä" key. Without this change, if such a hotkey appears at the top of the script,
// its subroutine would execute immediately as a normal label, which would be especially
// bad if the hotkey were something like the "Shutdown" command.
if (buf[buf_length - 2] == ':' && buf_length > 2) // i.e. allow "::" as a normal label, but consider anything else with double-colon to be a failed-hotkey label that terminates the auto-exec section.
{
//CHECK_mNoHotkeyLabels // Terminate the auto-execute section since this is a failed hotkey vs. a mere normal label.
sntprintf(msg_text, _countof(msg_text), _T("Note: The hotkey %s will not be active because it does not exist in the current keyboard layout."), buf);
MsgBox(msg_text);
}
buf[--buf_length] = '\0'; // Remove the trailing colon.
rtrim(buf, buf_length); // Has already been ltrimmed.
if (!AddLabel(buf, false))
- return FAIL;
+ goto FAIL;
goto continue_main_loop; // In lieu of "continue", for performance.
}
}
// Since above didn't "goto", it's not a label.
if (*buf == '#')
{
saved_line_number = mCombinedLineNumber; // Backup in case IsDirective() processes an include file, which would change mCombinedLineNumber's value.
switch(IsDirective(buf)) // Note that it may alter the contents of buf, at least in the case of #IfWin.
{
case CONDITION_TRUE:
// Since the directive may have been a #include which called us recursively,
// restore the class's values for these two, which are maintained separately
// like this to avoid having to specify them in various calls, especially the
// hundreds of calls to ScriptError() and LineError():
mCurrFileIndex = source_file_index;
mCombinedLineNumber = saved_line_number;
goto continue_main_loop; // In lieu of "continue", for performance.
case FAIL: // IsDirective() already displayed the error.
- return FAIL;
+ goto FAIL;
//case CONDITION_FALSE: Do nothing; let processing below handle it.
}
}
// Otherwise, treat it as a normal script line.
if (*buf == '{' || *buf == '}')
{
if (!AddLine(*buf == '{' ? ACT_BLOCK_BEGIN : ACT_BLOCK_END))
- return FAIL;
+ goto FAIL;
// Allow any command/action, directive or label to the right of "{" or "}":
if ( *(buf = omit_leading_whitespace(buf + 1)) )
{
buf_length = _tcslen(buf); // Update.
mCurrLine = NULL; // To signify that we're in transition, trying to load a new line.
goto process_completed_line; // Have the main loop process the contents of "buf" as though it came in from the script.
}
goto continue_main_loop; // It's just a naked "{" or "}", so no more processing needed for this line.
}
// First do a little special handling to support actions on the same line as their
// ELSE or TRY, e.g.:
// else if x = 1
// try someFunction()
// This is done here rather than in ParseAndAddLine() because it's fairly
// complicated to do there (already tried it) mostly due to the fact that
// literal_map has to be properly passed in a recursive call to itself, as well
// as properly detecting special commands that don't have keywords such as
// IF comparisons, ACT_ASSIGN, +=, -=, etc.
// v1.0.41: '{' was added to the line below to support no spaces inside "}else{".
if (!(action_end = StrChrAny(buf, _T("\t ,{")))) // Position of first tab/space/comma/open-brace. For simplicity, a non-standard g_delimiter is not supported.
action_end = buf + buf_length; // It's done this way so that ELSE can be fully handled here; i.e. that ELSE does not have to be in the list of commands recognizable by ParseAndAddLine().
// The following method ensures that words or variables that start with "Else", e.g. ElseAction, are not
// incorrectly detected as an Else command:
int try_cmp = 1, finally_cmp = 1;
if (tcslicmp(buf, _T("Else"), action_end - buf) // It's not an ELSE, a TRY or a FINALLY. ("Else"/"Try"/"Finally" is used vs. g_act[ACT_ELSE/TRY/FINALLY].Name for performance).
&& (try_cmp = tcslicmp(buf, _T("Try"), action_end - buf))
&& (finally_cmp = tcslicmp(buf, _T("Finally"), action_end - buf)))
{
if (!ParseAndAddLine(buf))
- return FAIL;
+ goto FAIL;
}
else // This line is an ELSE, a TRY or a FINALLY, possibly with another command immediately after it (on the same line).
{
// Add the ELSE, TRY or FINALLY directly rather than calling ParseAndAddLine() because that function
// would resolve escape sequences throughout the entire length of <buf>, which we
// don't want because we wouldn't have access to the corresponding literal-map to
// figure out the proper use of escaped characters:
if (!AddLine(try_cmp ? (finally_cmp ? ACT_ELSE : ACT_FINALLY) : ACT_TRY))
- return FAIL;
+ goto FAIL;
mCurrLine = NULL; // To signify that we're in transition, trying to load a new one.
buf = omit_leading_whitespace(action_end); // Now buf is the word after the ELSE or TRY.
if (*buf == g_delimiter) // Allow "else, action", "try, action" and "finally, action"
buf = omit_leading_whitespace(buf + 1);
// Allow any command/action to the right of "else", "try" or "finally", including "{":
if (*buf)
{
// This is done rather than calling ParseAndAddLine() as it handles "{" in a way that
// anything to the right of it is considered an arg of that line and is basically ignored.
buf_length = _tcslen(buf); // Update.
mCurrLine = NULL; // To signify that we're in transition, trying to load a new line.
goto examine_line; // Have the main loop process the contents of "buf" as though it came in from the script.
}
// Otherwise, there was either no same-line action, so do nothing.
}
continue_main_loop: // This method is used in lieu of "continue" for performance and code size reduction.
#ifndef MINIDLL
if (remap_dest_vk)
{
// For remapping, decided to use a "macro expansion" approach because I think it's considerably
// smaller in code size and complexity than other approaches would be. I originally wanted to
// do it with the hook by changing the incoming event prior to passing it back out again (for
// example, a::b would transform an incoming 'a' keystroke into 'b' directly without having
// to suppress the original keystroke and simulate a new one). Unfortunately, the low-level
// hooks apparently do not allow this. Here is the test that confirmed it:
// if (event.vkCode == 'A')
// {
// event.vkCode = 'B';
// event.scanCode = 0x30; // Or use vk_to_sc(event.vkCode).
// return CallNextHookEx(g_KeybdHook, aCode, wParam, lParam);
// }
switch (++remap_stage)
{
case 1: // Stage 1: Add key-down hotkey label, e.g. *LButton::
buf_length = _stprintf(buf, _T("*%s::"), remap_source); // Should be no risk of buffer overflow due to prior validation.
goto examine_line; // Have the main loop process the contents of "buf" as though it came in from the script.
case 2: // Stage 2.
// Copied into a writable buffer for maintainability: AddLine() might rely on this.
// Also, it seems unnecessary to set press-duration to -1 even though the auto-exec section might
// have set it to something higher than -1 because:
// 1) Press-duration doesn't apply to normal remappings since they use down-only and up-only events.
// 2) Although it does apply to remappings such as a::B and a::^b (due to press-duration being
// applied after a change to modifier state), those remappings are fairly rare and supporting
// a non-negative-one press-duration (almost always 0) probably adds a degree of flexibility
// that may be desirable to keep.
// 3) SendInput may become the predominant SendMode, so press-duration won't often be in effect anyway.
// 4) It has been documented that remappings use the auto-execute section's press-duration.
_tcscpy(buf, _T("-1")); // Does NOT need to be "-1, -1" for SetKeyDelay (see above).
// The primary reason for adding Key/MouseDelay -1 is to minimize the chance that a one of
// these hotkey threads will get buried under some other thread such as a timer, which
// would disrupt the remapping if #MaxThreadsPerHotkey is at its default of 1.
AddLine(remap_dest_is_mouse ? ACT_SETMOUSEDELAY : ACT_SETKEYDELAY, &buf, 1, NULL); // PressDuration doesn't need to be specified because it doesn't affect down-only and up-only events.
if (remap_keybd_to_mouse)
{
// Since source is keybd and dest is mouse, prevent keyboard auto-repeat from auto-repeating
// the mouse button (since that would be undesirable 90% of the time). This is done
// by inserting a single extra IF-statement above the Send that produces the down-event:
buf_length = _stprintf(buf, _T("if not GetKeyState(\"%s\")"), remap_dest); // Should be no risk of buffer overflow due to prior validation.
remap_stage = 9; // Have it hit special stage 9+1 next time for code reduction purposes.
goto examine_line; // Have the main loop process the contents of "buf" as though it came in from the script.
}
// Otherwise, remap_keybd_to_mouse==false, so fall through to next case.
case 10:
extra_event = _T(""); // Set default.
switch (remap_dest_vk)
{
case VK_LMENU:
case VK_RMENU:
case VK_MENU:
switch (remap_source_vk)
{
case VK_LCONTROL:
case VK_CONTROL:
extra_event = _T("{LCtrl up}"); // Somewhat surprisingly, this is enough to make "Ctrl::Alt" properly remap both right and left control.
break;
case VK_RCONTROL:
extra_event = _T("{RCtrl up}");
break;
// Below is commented out because its only purpose was to allow a shift key remapped to alt
// to be able to alt-tab. But that wouldn't work correctly due to the need for the following
// hotkey, which does more harm than good by impacting the normal Alt key's ability to alt-tab
// (if the normal Alt key isn't remapped): *Tab::Send {Blind}{Tab}
//case VK_LSHIFT:
//case VK_SHIFT:
// extra_event = "{LShift up}";
// break;
//case VK_RSHIFT:
// extra_event = "{RShift up}";
// break;
}
break;
}
mCurrLine = NULL; // v1.0.40.04: Prevents showing misleading vicinity lines for a syntax-error such as %::%
_stprintf(buf, _T("{Blind}%s%s{%s DownTemp}"), extra_event, remap_dest_modifiers, remap_dest); // v1.0.44.05: DownTemp vs. Down. See Send's DownTemp handler for details.
if (!AddLine(ACT_SEND, &buf, 1, NULL)) // v1.0.40.04: Check for failure due to bad remaps such as %::%.
- return FAIL;
+ goto FAIL;
AddLine(ACT_RETURN);
// Add key-up hotkey label, e.g. *LButton up::
buf_length = _stprintf(buf, _T("*%s up::"), remap_source); // Should be no risk of buffer overflow due to prior validation.
remap_stage = 2; // Adjust to hit stage 3 next time (in case this is stage 10).
goto examine_line; // Have the main loop process the contents of "buf" as though it came in from the script.
case 3: // Stage 3.
_tcscpy(buf, _T("-1"));
AddLine(remap_dest_is_mouse ? ACT_SETMOUSEDELAY : ACT_SETKEYDELAY, &buf, 1, NULL);
_stprintf(buf, _T("{Blind}{%s Up}"), remap_dest); // Unlike the down-event above, remap_dest_modifiers is not included for the up-event; e.g. ^{b up} is inappropriate.
AddLine(ACT_SEND, &buf, 1, NULL);
AddLine(ACT_RETURN);
remap_dest_vk = 0; // Reset to signal that the remapping expansion is now complete.
break; // Fall through to the next section so that script loading can resume at the next line.
}
} // if (remap_dest_vk)
#endif
// Since above didn't "continue", resume loading script line by line:
buf = next_buf;
buf_length = next_buf_length;
next_buf = (buf == buf1) ? buf2 : buf1;
// The line above alternates buffers (toggles next_buf to be the unused buffer), which helps
// performance because it avoids memcpy from buf2 to buf1.
} // for each whole/constructed line.
if (*pending_buf) // Since this is the last non-comment line, the pending function must be a function call, not a function definition.
{
// Somewhat messy to decrement then increment later, but it's probably easier than the
// alternatives due to the use of "continue" in some places above.
saved_line_number = mCombinedLineNumber;
mCombinedLineNumber = pending_buf_line_number; // Done so that any syntax errors that occur during the calls below will report the correct line number.
if (pending_buf_type != Pending_Func)
+ {
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
return ScriptError(pending_buf_has_brace ? ERR_MISSING_CLOSE_BRACE : ERR_MISSING_OPEN_BRACE, pending_buf);
+ }
if (!ParseAndAddLine(pending_buf, ACT_EXPRESSION)) // Must be function call vs. definition since otherwise the above would have detected the opening brace beneath it and already cleared pending_function.
- return FAIL;
+ goto FAIL;
mCombinedLineNumber = saved_line_number;
}
+
+ if (aSizeDeCompressed) // clear memory of protected script since it is not required anymore
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
if (mClassObjectCount && !source_file_index) // or mClassProperty, which implies mClassObjectCount != 0.
{
// A class definition has not been closed with "}". Previously this was detected by adding
// the open and close braces as lines, but this way is simpler and has less overhead.
// The downside is that the line number won't be shown; however, the class name will.
// Seems okay not to show mClassProperty->mName since the class is missing "}" as well.
return ScriptError(ERR_MISSING_CLOSE_BRACE, mClassName);
}
++mCombinedLineNumber; // L40: Put the implicit ACT_EXIT on the line after the last physical line (for the debugger).
// This is not required, it is called by the destructor.
// fp->Close();
return OK;
+FAIL:
+ if (aSizeDeCompressed) // clear memory of protected script since it is not required anymore
+ SecureZeroMemory(textbuf.mBuffer, aSizeDeCompressed);
+ return FAIL;
}
size_t Script::GetLine(LPTSTR aBuf, int aMaxCharsToRead, int aInContinuationSection, TextStream *ts)
{
size_t aBuf_length = 0;
if (!aBuf || !ts) return -1;
if (aMaxCharsToRead < 1) return 0;
if ( !(aBuf_length = ts->ReadLine(aBuf, aMaxCharsToRead)) ) // end-of-file or error
{
*aBuf = '\0'; // Reset since on error, contents added by fgets() are indeterminate.
return -1;
}
if (aBuf[aBuf_length-1] == '\n')
--aBuf_length;
aBuf[aBuf_length] = '\0';
if (aInContinuationSection)
{
LPTSTR cp = omit_leading_whitespace(aBuf);
if (aInContinuationSection == CONTINUATION_SECTION_WITHOUT_COMMENTS) // By default, continuation sections don't allow comments (lines beginning with a semicolon are treated as literal text).
{
// Caller relies on us to detect the end of the continuation section so that trimming
// will be done on the final line of the section and so that a comment can immediately
// follow the closing parenthesis (on the same line). Example:
// (
// Text
// ) ; Same line comment.
if (*cp != ')') // This isn't the last line of the continuation section, so leave the line untrimmed (caller will apply the ltrim setting on its own).
return aBuf_length; // Earlier sections are responsible for keeping aBufLength up-to-date with any changes to aBuf.
//else this line starts with ')', so continue on to later section that checks for a same-line comment on its right side.
}
else // aInContinuationSection == CONTINUATION_SECTION_WITH_COMMENTS (i.e. comments are allowed in this continuation section).
{
// Fix for v1.0.46.09+: The "com" option shouldn't put "ltrim" into effect.
if (!_tcsncmp(cp, g_CommentFlag, g_CommentFlagLength)) // Case sensitive.
{
*aBuf = '\0'; // Since this line is a comment, have the caller ignore it.
return -2; // Callers tolerate -2 only when in a continuation section. -2 indicates, "don't include this line at all, not even as a blank line to which the JOIN string (default "\n") will apply.
}
if (*cp == ')') // This isn't the last line of the continuation section, so leave the line untrimmed (caller will apply the ltrim setting on its own).
{
ltrim(aBuf); // Ltrim this line unconditionally so that caller will see that it starts with ')' without having to do extra steps.
aBuf_length = _tcslen(aBuf); // ltrim() doesn't always return an accurate length, so do it this way.
}
}
}
// Since above didn't return, either:
// 1) We're not in a continuation section at all, so apply ltrim() to support semicolons after tabs or
// other whitespace. Seems best to rtrim also.
// 2) CONTINUATION_SECTION_WITHOUT_COMMENTS but this line is the final line of the section. Apply
// trim() and other logic further below because caller might rely on it.
// 3) CONTINUATION_SECTION_WITH_COMMENTS (i.e. comments allowed), but this line isn't a comment (though
// it may start with ')' and thus be the final line of this section). In either case, need to check
// for same-line comments further below.
if (aInContinuationSection != CONTINUATION_SECTION_WITH_COMMENTS) // Case #1 & #2 above.
{
aBuf_length = trim(aBuf);
if (!_tcsncmp(aBuf, g_CommentFlag, g_CommentFlagLength)) // Case sensitive.
{
// Due to other checks, aInContinuationSection==false whenever the above condition is true.
*aBuf = '\0';
return 0;
}
}
//else CONTINUATION_SECTION_WITH_COMMENTS (case #3 above), which due to other checking also means that
// this line isn't a comment (though it might have a comment on its right side, which is checked below).
// CONTINUATION_SECTION_WITHOUT_COMMENTS would already have returned higher above if this line isn't
// the last line of the continuation section.
// Handle comment-flags that appear to the right of a valid line.
LPTSTR cp, prevp;
for (cp = _tcsstr(aBuf, g_CommentFlag); cp; cp = _tcsstr(cp + g_CommentFlagLength, g_CommentFlag))
{
// If no whitespace to its left, it's not a valid comment.
// We insist on this so that a semi-colon (for example) immediately after
// a word (as semi-colons are often used) will not be considered a comment.
prevp = cp - 1;
if (prevp < aBuf) // should never happen because we already checked above.
{
*aBuf = '\0';
return 0;
}
if (IS_SPACE_OR_TAB_OR_NBSP(*prevp)) // consider it to be a valid comment flag
{
*prevp = '\0';
aBuf_length = rtrim_with_nbsp(aBuf, prevp - aBuf); // Since it's our responsibility to return a fully trimmed string.
break; // Once the first valid comment-flag is found, nothing after it can matter.
}
else // No whitespace to the left.
if (*prevp == g_EscapeChar) // Remove the escape char.
{
// The following isn't exactly correct because it prevents an include filename from ever
// containing the literal string "`;". This is because attempts to escape the accent via
// "``;" are not supported. This is documented here as a known limitation because fixing
// it would probably break existing scripts that rely on the fact that accents do not need
// to be escaped inside #Include. Also, the likelihood of "`;" appearing literally in a
// legitimate #Include file seems vanishingly small.
tmemmove(prevp, prevp + 1, _tcslen(prevp + 1) + 1); // +1 for the terminator.
--aBuf_length;
// Then continue looking for others.
}
// else there wasn't any whitespace to its left, so keep looking in case there's
// another further on in the line.
} // for()
return aBuf_length; // The above is responsible for keeping aBufLength up-to-date with any changes to aBuf.
}
inline ResultType Script::IsDirective(LPTSTR aBuf)
// aBuf must be a modifiable string since this function modifies it in the case of "#Include %A_ScriptDir%"
// changes it. It must also be large enough to accept the replacement of %A_ScriptDir% with a larger string.
// Returns CONDITION_TRUE, CONDITION_FALSE, or FAIL.
// Note: Don't assume that every line in the script that starts with '#' is a directive
// because hotkeys can legitimately start with that as well. i.e., the following line should
// not be unconditionally ignored, just because it starts with '#', since it is a valid hotkey:
// #y::run, notepad
{
TCHAR end_flags[] = {' ', '\t', g_delimiter, '\0'}; // '\0' must be last.
LPTSTR directive_end, parameter_raw;
if ( !(directive_end = StrChrAny(aBuf, end_flags)) )
{
directive_end = aBuf + _tcslen(aBuf); // Point it to the zero terminator.
parameter_raw = NULL;
}
else
if (!*(parameter_raw = omit_leading_whitespace(directive_end)))
parameter_raw = NULL;
// The raw parameter retains any leading comma for those directives that need that (none currently).
// But the following omits that comma:
LPTSTR parameter;
if (!parameter_raw)
parameter = NULL;
else // Since parameter_raw is non-NULL, it's also non-blank and non-whitespace due to the above checking.
if (*parameter_raw != g_delimiter)
parameter = parameter_raw;
else // It's a delimiter, so "parameter" will be whatever non-whitespace character follows it, if any.
if (!*(parameter = omit_leading_whitespace(parameter_raw + 1)))
parameter = NULL;
//else leave it set to the value returned by omit_leading_whitespace().
int value; // Helps detect values that are too large, since some of the target globals are UCHAR.
// Use _tcsnicmp() so that a match is found as long as aBuf starts with the string in question.
// e.g. so that "#SingleInstance, on" will still work too, but
// "#a::run, something, "#SingleInstance" (i.e. a hotkey) will not be falsely detected
// due to using a more lenient function such as tcscasestr().
// UPDATE: Using strlicmp() now so that overlapping names, such as #MaxThreads and #MaxThreadsPerHotkey,
// won't get mixed up:
#define IS_DIRECTIVE_MATCH(directive) (!tcslicmp(aBuf, directive, directive_name_length))
size_t directive_name_length = directive_end - aBuf; // To avoid calculating it every time in the macro above.
bool is_include_again = false; // Set default in case of short-circuit boolean.
if (IS_DIRECTIVE_MATCH(_T("#Include")) || (is_include_again = IS_DIRECTIVE_MATCH(_T("#IncludeAgain"))))
{
// Standalone EXEs ignore this directive since the included files were already merged in
// with the main file when the script was compiled. These should have been removed
// or commented out by Ahk2Exe, but just in case, it's safest to ignore them:
#ifdef AUTOHOTKEYSC
return CONDITION_TRUE;
#else
// If the below decision is ever changed, be sure to update ahk2exe with the same change:
// "parameter" is checked rather than parameter_raw for backward compatibility with earlier versions,
// in which a leading comma is not considered part of the filename. Although this behavior is incorrect
// because it prevents files whose names start with a comma from being included without the first
// delim-comma being there too, it is kept because filenames that start with a comma seem
// exceedingly rare. As a workaround, the script can do #Include ,,FilenameWithLeadingComma.ahk
if (!parameter)
return ScriptError(ERR_PARAM1_REQUIRED, aBuf);
// v1.0.32:
bool ignore_load_failure = (parameter[0] == '*' && ctoupper(parameter[1]) == 'I'); // Relies on short-circuit boolean order.
if (ignore_load_failure)
{
parameter += 2;
if (IS_SPACE_OR_TAB(*parameter)) // Skip over at most one space or tab, since others might be a literal part of the filename.
++parameter;
}
if (*parameter == '<') // Support explicitly-specified <standard_lib_name>.
{
LPTSTR parameter_end = _tcschr(parameter, '>');
if (parameter_end && !parameter_end[1])
{
++parameter; // Remove '<'.
*parameter_end = '\0'; // Remove '>'.
bool error_was_shown, file_was_found;
// Save the working directory.
TCHAR buf[MAX_PATH];
if (!GetCurrentDirectory(_countof(buf) - 1, buf))
*buf = '\0';
// Attempt to include a script file based on the same rules as func() auto-include:
FindFuncInLibrary(parameter, parameter_end - parameter, error_was_shown, file_was_found, false);
// Restore the working directory so that any ordinary #includes will work correctly.
SetCurrentDirectory(buf);
// If any file was included, consider it a success; i.e. allow #include <lib> and #include <lib_func>.
if (!error_was_shown && file_was_found || ignore_load_failure)
return CONDITION_TRUE;
*parameter_end = '>'; // Restore '>' for display to the user.
return error_was_shown ? FAIL : ScriptError(_T("Function library not found."), aBuf);
}
//else invalid syntax; treat it as a regular #include which will almost certainly fail.
}
size_t space_remaining = LINE_SIZE - (parameter-aBuf);
TCHAR buf[MAX_PATH];
StrReplace(parameter, _T("%A_ScriptDir%"), mFileDir, SCS_INSENSITIVE, 1, space_remaining); // v1.0.35.11. Caller has ensured string is writable.
StrReplace(parameter, _T("%A_LineFile%"), Line::sSourceFile[mCurrFileIndex], SCS_INSENSITIVE, 1, space_remaining); // v1.1.11: Support A_LineFile to allow paths relative to current file regardless of working dir; e.g. %A_LineFile%\..\fileinsamedir.ahk.
if (tcscasestr(parameter, _T("%A_AppData%"))) // v1.0.45.04: This and the next were requested by Tekl to make it easier to customize scripts on a per-user basis.
{
BIV_SpecialFolderPath(buf, _T("A_AppData"));
StrReplace(parameter, _T("%A_AppData%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_AppDataCommon%"))) // v1.0.45.04.
{
BIV_SpecialFolderPath(buf, _T("A_AppDataCommon"));
StrReplace(parameter, _T("%A_AppDataCommon%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
DWORD attr = GetFileAttributes(parameter);
if (attr != 0xFFFFFFFF && (attr & FILE_ATTRIBUTE_DIRECTORY)) // File exists and its a directory (possibly A_ScriptDir or A_AppData set above).
{
// v1.0.35.11 allow changing of load-time directory to increase flexibility. This feature has
// been asked for directly or indirectly several times.
// If a script ever wants to use a string like "%A_ScriptDir%" literally in an include's filename,
// that would not work. But that seems too rare to worry about.
// v1.0.45.01: Call SetWorkingDir() vs. SetCurrentDirectory() so that it succeeds even for a root
// drive like C: that lacks a backslash (see SetWorkingDir() for details).
SetWorkingDir(parameter);
return CONDITION_TRUE;
}
// Since above didn't return, it's a file (or non-existent file, in which case the below will display
// the error). This will also display any other errors that occur:
return LoadIncludedFile(parameter, is_include_again, ignore_load_failure) ? CONDITION_TRUE : FAIL;
#endif
}
if (IS_DIRECTIVE_MATCH(_T("#NoEnv")))
{
g_NoEnv = TRUE;
return CONDITION_TRUE;
}
if (IS_DIRECTIVE_MATCH(_T("#NoTrayIcon")))
{
#ifndef MINIDLL
g_NoTrayIcon = true;
#endif
return CONDITION_TRUE;
}
if (IS_DIRECTIVE_MATCH(_T("#Persistent")))
{
g_persistent = true;
return CONDITION_TRUE;
}
if (IS_DIRECTIVE_MATCH(_T("#SingleInstance")))
{
#ifndef _USRDLL
g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; // Set default.
if (parameter)
{
if (!_tcsicmp(parameter, _T("Force")))
g_AllowOnlyOneInstance = SINGLE_INSTANCE_REPLACE;
else if (!_tcsicmp(parameter, _T("Ignore")))
g_AllowOnlyOneInstance = SINGLE_INSTANCE_IGNORE;
else if (!_tcsicmp(parameter, _T("Off")))
g_AllowOnlyOneInstance = SINGLE_INSTANCE_OFF;
}
#endif
return CONDITION_TRUE;
}
#ifndef MINIDLL
if (IS_DIRECTIVE_MATCH(_T("#InstallKeybdHook")))
{
// It seems best not to report this warning because a user may want to use partial functionality
// of a script on Win9x:
//MsgBox("#InstallKeybdHook is not supported on Windows 95/98/Me. This line will be ignored.");
if (!g_os.IsWin9x())
Hotkey::RequireHook(HOOK_KEYBD);
return CONDITION_TRUE;
}
if (IS_DIRECTIVE_MATCH(_T("#InstallMouseHook")))
{
// It seems best not to report this warning because a user may want to use partial functionality
// of a script on Win9x:
//MsgBox("#InstallMouseHook is not supported on Windows 95/98/Me. This line will be ignored.");
if (!g_os.IsWin9x())
Hotkey::RequireHook(HOOK_MOUSE);
return CONDITION_TRUE;
}
if (IS_DIRECTIVE_MATCH(_T("#UseHook")))
{
g_ForceKeybdHook = !parameter || Line::ConvertOnOff(parameter) != TOGGLED_OFF;
return CONDITION_TRUE;
}
// L4: Handle #if (expression) directive.
if (IS_DIRECTIVE_MATCH(_T("#If")))
{
if (!parameter) // The omission of the parameter indicates that any existing criteria should be turned off.
{
g_HotCriterion = HOT_NO_CRITERION; // Indicate that no criteria are in effect for subsequent hotkeys.
g_HotWinTitle = _T(""); // Helps maintainability and some things might rely on it.
g_HotWinText = _T(""); //
g_HotExprIndex = -1;
return CONDITION_TRUE;
}
Func *currentFunc = g->CurrentFunc;
// Ensure variable references are global:
g->CurrentFunc = NULL;
ConvertEscapeSequences(parameter, g_EscapeChar, false); // Normally done in ParseAndAddLine().
// ACT_EXPRESSION will be changed to ACT_IFEXPR after PreparseBlocks() is called so that EvaluateCondition()
// can be used and because ACT_EXPRESSION is designed to discard its result (since it normally would not be
// used). This can't be done before PreparseBlocks() is called since this isn't really an IF (it has no body).
if (!AddLine(ACT_EXPRESSION, ¶meter, UCHAR_MAX + 1)) // UCHAR_MAX signals AddLine to avoid pointing any pending labels or functions at the new line.
return FAIL; // Above already displayed the error message.
Line *hot_expr_line = mLastLine;
// Remove the newly added line from the actual script.
if (mFirstLine == mLastLine)
mFirstLine = NULL;
mLastLine = mLastLine->mPrevLine;
if (mLastLine) // Will be NULL if no actual code precedes the #if.
mLastLine->mNextLine = NULL;
mCurrLine = mLastLine;
// Restore to previous value:
g->CurrentFunc = currentFunc;
// Set the new criterion.
g_HotCriterion = HOT_IF_EXPR;
// Use the expression text to identify hotkey variants.
g_HotWinTitle = hot_expr_line->mArg[0].text;
g_HotWinText = _T("");
if (g_HotExprLineCount + 1 > g_HotExprLineCountMax)
{ // Allocate or reallocate g_HotExprLines.
g_HotExprLineCountMax += 100;
g_HotExprLines = (Line**)realloc(g_HotExprLines, g_HotExprLineCountMax * sizeof(Line**));
}
g_HotExprIndex = g_HotExprLineCount++;
g_HotExprLines[g_HotExprIndex] = hot_expr_line;
// VicinityToText() assumes lines are linked both ways, so clear mPrevLine in case an error occurs when this line is validated.
hot_expr_line->mPrevLine = NULL;
// The lines could be linked to simplify function resolution (i.e. allow calling PreparseBlocks() for all lines instead of once for each line) -- However, this would cause confusing/irrelevant vicinity lines to be shown if an error occurs.
return CONDITION_TRUE;
}
// L4: Allow #if timeout to be adjusted.
if (IS_DIRECTIVE_MATCH(_T("#IfTimeout")))
{
if (parameter)
g_HotExprTimeout = ATOU(parameter);
return CONDITION_TRUE;
}
if (!_tcsnicmp(aBuf, _T("#IfWin"), 6))
{
bool invert = !_tcsnicmp(aBuf + 6, _T("Not"), 3);
if (!_tcsnicmp(aBuf + (invert ? 9 : 6), _T("Active"), 6)) // It matches #IfWin[Not]Active.
g_HotCriterion = invert ? HOT_IF_NOT_ACTIVE : HOT_IF_ACTIVE;
else if (!_tcsnicmp(aBuf + (invert ? 9 : 6), _T("Exist"), 5))
g_HotCriterion = invert ? HOT_IF_NOT_EXIST : HOT_IF_EXIST;
else // It starts with #IfWin but isn't Active or Exist: Don't alter g_HotCriterion.
return CONDITION_FALSE; // Indicate unknown directive since there are currently no other possibilities.
g_HotExprIndex = -1; // L4: For consistency, don't allow mixing of #if and other #ifWin criterion.
if (!parameter) // The omission of the parameter indicates that any existing criteria should be turned off.
{
g_HotCriterion = HOT_NO_CRITERION; // Indicate that no criteria are in effect for subsequent hotkeys.
g_HotWinTitle = _T(""); // Helps maintainability and some things might rely on it.
g_HotWinText = _T(""); //
return CONDITION_TRUE;
}
LPTSTR hot_win_title = parameter, hot_win_text; // Set default for title; text is determined later.
// Scan for the first non-escaped comma. If there is one, it marks the second parameter: WinText.
LPTSTR cp, first_non_escaped_comma;
for (first_non_escaped_comma = NULL, cp = hot_win_title; ; ++cp) // Increment to skip over the symbol just found by the inner for().
{
for (; *cp && !(*cp == g_EscapeChar || *cp == g_delimiter || *cp == g_DerefChar); ++cp); // Find the next escape char, comma, or %.
if (!*cp) // End of string was found.
break;
#define ERR_ESCAPED_COMMA_PERCENT _T("Literal commas and percent signs must be escaped (e.g. `%)")
if (*cp == g_DerefChar)
return ScriptError(ERR_ESCAPED_COMMA_PERCENT, aBuf);
if (*cp == g_delimiter) // non-escaped delimiter was found.
{
// Preserve the ability to add future-use parameters such as section of window
// over which the mouse is hovering, e.g. #IfWinActive, Untitled - Notepad,, TitleBar
if (first_non_escaped_comma) // A second non-escaped comma was found.
return ScriptError(ERR_ESCAPED_COMMA_PERCENT, aBuf);
// Otherwise:
first_non_escaped_comma = cp;
continue; // Check if there are any more non-escaped commas.
}
// Otherwise, an escape character was found, so skip over the next character (if any).
if (!*(++cp)) // The string unexpectedly ends in an escape character, so avoid out-of-bounds.
break;
// Otherwise, the ++cp above has skipped over the escape-char itself, and the loop's ++cp will now
// skip over the char-to-be-escaped, which is not the one we want (even if it is a comma).
}
if (first_non_escaped_comma) // Above found a non-escaped comma, so there is a second parameter (WinText).
{
// Omit whitespace to (seems best to conform to convention/expectations rather than give
// strange whitespace flexibility that would likely cause unwanted bugs due to inadvertently
// have two spaces instead of one). The user may use `s and `t to put literal leading/trailing
// spaces/tabs into these parameters.
hot_win_text = omit_leading_whitespace(first_non_escaped_comma + 1);
*first_non_escaped_comma = '\0'; // Terminate at the comma to split off hot_win_title on its own.
rtrim(hot_win_title, first_non_escaped_comma - hot_win_title); // Omit whitespace (see similar comment above).
// The following must be done only after trimming and omitting whitespace above, so that
// `s and `t can be used to insert leading/trailing spaces/tabs. ConvertEscapeSequences()
// also supports insertion of literal commas via escaped sequences.
ConvertEscapeSequences(hot_win_text, g_EscapeChar, true);
}
else
hot_win_text = _T(""); // And leave hot_win_title set to the entire string because there's only one parameter.
// The following must be done only after trimming and omitting whitespace above (see similar comment above).
ConvertEscapeSequences(hot_win_title, g_EscapeChar, true);
// The following also handles the case where both title and text are blank, which could happen
// due to something weird but legit like: #IfWinActive, ,
if (!SetGlobalHotTitleText(hot_win_title, hot_win_text))
return ScriptError(ERR_OUTOFMEM); // So rare that no second param is provided (since its contents may have been temp-terminated or altered above).
return CONDITION_TRUE;
} // Above completely handles all directives and non-directives that start with "#IfWin".
if (IS_DIRECTIVE_MATCH(_T("#Hotstring")))
{
if (parameter)
{
LPTSTR suboption = tcscasestr(parameter, _T("EndChars"));
if (suboption)
{
// Since it's not realistic to have only a couple, spaces and literal tabs
// must be included in between other chars, e.g. `n `t has a space in between.
// Also, EndChar \t will have a space and a tab since there are two spaces
// after the word EndChar.
if ( !(parameter = StrChrAny(suboption, _T("\t "))) )
return CONDITION_TRUE;
tcslcpy(g_EndChars, ++parameter, _countof(g_EndChars));
ConvertEscapeSequences(g_EndChars, g_EscapeChar, false);
return CONDITION_TRUE;
}
if (!_tcsnicmp(parameter, _T("NoMouse"), 7)) // v1.0.42.03
{
g_HSResetUponMouseClick = false;
return CONDITION_TRUE;
}
// Otherwise assume it's a list of options. Note that for compatibility with its
// other caller, it will stop at end-of-string or ':', whichever comes first.
Hotstring::ParseOptions(parameter, g_HSPriority, g_HSKeyDelay, g_HSSendMode, g_HSCaseSensitive
, g_HSConformToCase, g_HSDoBackspace, g_HSOmitEndChar, g_HSSendRaw, g_HSEndCharRequired
, g_HSDetectWhenInsideWord, g_HSDoReset);
}
return CONDITION_TRUE;
}
if (IS_DIRECTIVE_MATCH(_T("#HotkeyModifierTimeout")))
{
if (parameter)
g_HotkeyModifierTimeout = ATOI(parameter); // parameter was set to the right position by the above macro
return CONDITION_TRUE;
}
if (IS_DIRECTIVE_MATCH(_T("#HotkeyInterval")))
{
if (parameter)
{
g_HotkeyThrottleInterval = ATOI(parameter); // parameter was set to the right position by the above macro
if (g_HotkeyThrottleInterval < 10) // values under 10 wouldn't be useful due to timer granularity.
g_HotkeyThrottleInterval = 10;
}
return CONDITION_TRUE;
}
if (IS_DIRECTIVE_MATCH(_T("#MaxHotkeysPerInterval")))
{
if (parameter)
{
g_MaxHotkeysPerInterval = ATOI(parameter); // parameter was set to the right position by the above macro
if (g_MaxHotkeysPerInterval < 1) // sanity check
g_MaxHotkeysPerInterval = 1;
}
return CONDITION_TRUE;
}
if (IS_DIRECTIVE_MATCH(_T("#MaxThreadsPerHotkey")))
{
if (parameter)
{
// Use value as a temp holder since it's int vs. UCHAR and can thus detect very large or negative values:
value = ATOI(parameter); // parameter was set to the right position by the above macro
if (value > MAX_THREADS_LIMIT) // For now, keep this limited to prevent stack overflow due to too many pseudo-threads.
value = MAX_THREADS_LIMIT; // UPDATE: To avoid array overflow, this limit must by obeyed except where otherwise documented.
else if (value < 1)
value = 1;
g_MaxThreadsPerHotkey = value; // Note: g_MaxThreadsPerHotkey is UCHAR.
}
return CONDITION_TRUE;
}
#endif
if (IS_DIRECTIVE_MATCH(_T("#MaxThreadsBuffer")))
{
g_MaxThreadsBuffer = !parameter || Line::ConvertOnOff(parameter) != TOGGLED_OFF;
return CONDITION_TRUE;
}
if (IS_DIRECTIVE_MATCH(_T("#MaxThreads")))
{
if (parameter)
{
@@ -9679,1027 +9727,1027 @@ ResultType Script::DefineClassVars(LPTSTR aBuf, bool aStatic)
break;
case ':':
if (item_end[1] == '=')
{
item_end += 2; // Point to the character after the ":=".
break;
}
// Otherwise, fall through to below:
default:
return ScriptError(ERR_INVALID_CLASS_VAR, item);
}
// Since above didn't "continue", this declared variable also has an initializer.
// Append the class name, ":=" and initializer to pending_buf, to be turned into
// an expression below, and executed at script start-up.
item_end = omit_leading_whitespace(item_end);
LPTSTR right_side_of_operator = item_end; // Save for use below.
item_end += FindNextDelimiter(item_end); // Find the next comma which is not part of the initializer (or find end of string).
// Append "ClassNameOrThis.VarName := Initializer, " to the buffer.
int chars_written = _sntprintf(buf + buf_used, _countof(buf) - buf_used, _T("%s.%.*s := %.*s, ")
, aStatic ? mClassName : _T("this"), name_length, item, item_end - right_side_of_operator, right_side_of_operator);
if (chars_written < 0)
return ScriptError(_T("Declaration too long.")); // Short message since should be rare.
buf_used += chars_written;
// Set "item" for use by the next iteration:
item = (*item_end == ',') // i.e. it's not the terminator and thus not the final item in the list.
? omit_leading_whitespace(item_end + 1)
: item_end; // It's the terminator, so let the loop detect that to finish.
}
if (buf_used)
{
// Above wrote at least one initializer expression into buf.
buf[buf_used -= 2] = '\0'; // Remove the final ", "
// The following section temporarily replaces mLastLine in order to insert script lines
// either at the end of the list of static initializers (separate from the main script)
// or at the end of the __Init method belonging to this class. Save the current values:
Line *script_first_line = mFirstLine, *script_last_line = mLastLine;
Line *block_end;
Func *init_func = NULL;
if (aStatic)
{
mLastLine = mLastStaticLine;
mFirstLine = mFirstStaticLine;
}
else
{
ExprTokenType token;
if (class_object->GetItem(token, _T("__Init")) && token.symbol == SYM_OBJECT
&& (init_func = dynamic_cast<Func *>(token.object))) // This cast SHOULD always succeed; done for maintainability.
{
// __Init method already exists, so find the end of its body.
for (block_end = init_func->mJumpToLine;
block_end->mActionType != ACT_BLOCK_END || !block_end->mAttribute;
block_end = block_end->mNextLine);
}
else
{
// Create an __Init method for this class.
TCHAR def[] = _T("__Init()");
if (!DefineFunc(def, NULL) || !AddLine(ACT_BLOCK_BEGIN)
|| (class_object->Base() && !ParseAndAddLine(_T("base.__Init()"), ACT_EXPRESSION))) // Initialize base-class variables first. Relies on short-circuit evaluation.
return FAIL;
mLastLine->mLineNumber = 0; // Signal the debugger to skip this line while stepping in/over/out.
init_func = g->CurrentFunc;
init_func->mDefaultVarType = VAR_DECLARE_GLOBAL; // Allow global variables/class names in initializer expressions.
if (!AddLine(ACT_BLOCK_END)) // This also resets g->CurrentFunc to NULL.
return FAIL;
block_end = mLastLine;
block_end->mLineNumber = 0; // See above.
// These must be updated as one or both have changed:
script_first_line = mFirstLine;
script_last_line = mLastLine;
}
g->CurrentFunc = init_func; // g->CurrentFunc should be NULL prior to this.
mLastLine = block_end->mPrevLine; // i.e. insert before block_end.
mLastLine->mNextLine = NULL; // For maintainability; AddLine() should overwrite it regardless.
mCurrLine = NULL; // Fix for v1.1.09.02: Leaving this non-NULL at best causes error messages to show irrelevant vicinity lines, and at worst causes a crash because the linked list is in an inconsistent state.
}
LPTSTR arg[] = { ConvertEscapeSequences(buf, g_EscapeChar, false) };
if (!AddLine(ACT_EXPRESSION, arg, UCHAR_MAX + 1)) // v1.1.17: Avoid pointing labels at this line by passing UCHAR_MAX+ for aArgc.
return FAIL; // Above already displayed the error.
if (aStatic)
{
if (!mFirstStaticLine)
mFirstStaticLine = mLastLine;
mLastStaticLine = mLastLine;
// The following is necessary if there weren't any executable lines above this static
// initializer (i.e. mFirstLine was NULL and has been set to the newly created line):
mFirstLine = script_first_line;
}
else
{
if (init_func->mJumpToLine == block_end) // This can be true only for the first initializer of a class with no base-class.
init_func->mJumpToLine = mLastLine;
// Rejoin the function's block-end (and any lines following it) to the main script.
mLastLine->mNextLine = block_end;
block_end->mPrevLine = mLastLine;
// mFirstLine should be left as it is: if it was NULL, it now contains a pointer to our
// __init function's block-begin, which is now the very first executable line in the script.
g->CurrentFunc = NULL;
}
// Restore mLastLine so that any subsequent script lines are added at the correct point.
mLastLine = script_last_line;
}
return OK;
}
Object *Script::FindClass(LPCTSTR aClassName, size_t aClassNameLength)
{
if (!aClassNameLength)
aClassNameLength = _tcslen(aClassName);
if (!aClassNameLength || aClassNameLength > MAX_CLASS_NAME_LENGTH)
return NULL;
LPTSTR cp, key;
ExprTokenType token;
Object *base_object = NULL;
TCHAR class_name[MAX_CLASS_NAME_LENGTH + 2]; // Extra +1 for '.' to simplify parsing.
// Make temporary copy which we can modify.
tmemcpy(class_name, aClassName, aClassNameLength);
class_name[aClassNameLength] = '.'; // To simplify parsing.
class_name[aClassNameLength + 1] = '\0';
// Get base variable; e.g. "MyClass" in "MyClass.MySubClass".
cp = _tcschr(class_name + 1, '.');
Var *base_var = FindVar(class_name, cp - class_name, NULL, FINDVAR_GLOBAL);
if (!base_var)
return NULL;
// Although at load time only the "Object" type can exist, dynamic_cast is used in case we're called at run-time:
if ( !(base_var->IsObject() && (base_object = dynamic_cast<Object *>(base_var->Object()))) )
return NULL;
// Even if the loop below has no iterations, it initializes 'key' to the appropriate value:
for (key = cp + 1; cp = _tcschr(key, '.'); key = cp + 1) // For each key in something like TypeVar.Key1.Key2.
{
if (cp == key)
return NULL; // ScriptError(_T("Missing name."), cp);
*cp = '\0'; // Terminate at the delimiting dot.
if (!base_object->GetItem(token, key))
return NULL;
base_object = (Object *)token.object; // See comment about Object() above.
}
return base_object;
}
Object *Object::GetUnresolvedClass(LPTSTR &aName)
// This method is only valid for mUnresolvedClass.
{
if (!mFieldCount)
return NULL;
aName = mFields[0].key.s;
return (Object *)mFields[0].object;
}
ResultType Script::ResolveClasses()
{
LPTSTR name;
Object *base = mUnresolvedClasses->GetUnresolvedClass(name);
if (!base)
return OK;
// There is at least one unresolved class.
ExprTokenType token;
if (base->GetItem(token, _T("__Class")))
{
// In this case (an object in the mUnresolvedClasses list), it is always an integer
// containing the file index and line number:
mCurrFileIndex = int(token.value_int64 >> 32);
mCombinedLineNumber = LineNumberType(token.value_int64);
}
mCurrLine = NULL;
return ScriptError(_T("Unknown class."), name);
}
#ifndef AUTOHOTKEYSC
struct FuncLibrary
{
LPTSTR path;
DWORD_PTR length;
};
Func *Script::FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool &aErrorWasShown, bool &aFileWasFound, bool aIsAutoInclude)
// Caller must ensure that aFuncName doesn't already exist as a defined function.
// If aFuncNameLength is 0, the entire length of aFuncName is used.
{
aErrorWasShown = false; // Set default for this output parameter.
aFileWasFound = false;
int i;
LPTSTR char_after_last_backslash, terminate_here;
TCHAR buf[MAX_PATH+1];
DWORD attr;
TextMem tmem;
TextMem::Buffer textbuf(NULL, 0, false);
#define FUNC_LIB_EXT _T(".ahk")
#define FUNC_LIB_EXT_LENGTH (_countof(FUNC_LIB_EXT) - 1)
#define FUNC_LOCAL_LIB _T("\\Lib\\") // Needs leading and trailing backslash.
#define FUNC_LOCAL_LIB_LENGTH (_countof(FUNC_LOCAL_LIB) - 1)
#define FUNC_USER_LIB _T("\\AutoHotkey\\Lib\\") // Needs leading and trailing backslash.
#define FUNC_USER_LIB_LENGTH (_countof(FUNC_USER_LIB) - 1)
#define FUNC_STD_LIB _T("Lib\\") // Needs trailing but not leading backslash.
#define FUNC_STD_LIB_LENGTH (_countof(FUNC_STD_LIB) - 1)
#define FUNC_LIB_COUNT 4
static FuncLibrary sLib[FUNC_LIB_COUNT] = {0};
static LPTSTR winapi;
if (!sLib[0].path) // Allocate & discover paths only upon first use because many scripts won't use anything from the library. This saves a bit of memory and performance.
{
LPVOID aDataBuf;
HRSRC hResInfo = FindResource(g_hInstance, _T("WINAPI"), MAKEINTRESOURCE(10));
DecompressBuffer(LockResource(LoadResource(g_hInstance, hResInfo)), aDataBuf, g_default_pwd);
#ifdef _UNICODE
winapi = UTF8ToWide((LPCSTR)aDataBuf);
#else
winapi = (LPTSTR)aDataBuf;
#endif
for (i = 0; i < FUNC_LIB_COUNT; ++i)
#ifdef _USRDLL
if ( !(sLib[i].path = tmalloc(MAX_PATH)) ) // When dll script is restarted, SimpleHeap is deleted and we don't want to delete static memberst
#else
if ( !(sLib[i].path = (LPTSTR) SimpleHeap::Malloc(MAX_PATH * sizeof(TCHAR))) ) // Need MAX_PATH for to allow room for appending each candidate file/function name.
#endif
return NULL; // Due to rarity, simply pass the failure back to caller.
FuncLibrary *this_lib;
// DETERMINE PATH TO "LOCAL" LIBRARY:
this_lib = sLib; // For convenience and maintainability.
this_lib->length = BIV_ScriptDir(NULL, _T(""));
if (this_lib->length < MAX_PATH-FUNC_LOCAL_LIB_LENGTH)
{
this_lib->length = BIV_ScriptDir(this_lib->path, _T(""));
_tcscpy(this_lib->path + this_lib->length, FUNC_LOCAL_LIB);
this_lib->length += FUNC_LOCAL_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "USER" LIBRARY:
this_lib++; // For convenience and maintainability.
this_lib->length = BIV_MyDocuments(this_lib->path, _T(""));
if (this_lib->length < MAX_PATH-FUNC_USER_LIB_LENGTH)
{
_tcscpy(this_lib->path + this_lib->length, FUNC_USER_LIB);
this_lib->length += FUNC_USER_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "STANDARD" LIBRARY:
this_lib++; // For convenience and maintainability.
GetModuleFileName(NULL, this_lib->path, MAX_PATH); // The full path to the currently-running AutoHotkey.exe.
char_after_last_backslash = 1 + _tcsrchr(this_lib->path, '\\'); // Should always be found, so failure isn't checked.
this_lib->length = (DWORD)(char_after_last_backslash - this_lib->path); // The length up to and including the last backslash.
if (this_lib->length < MAX_PATH-FUNC_STD_LIB_LENGTH)
{
_tcscpy(this_lib->path + this_lib->length, FUNC_STD_LIB);
this_lib->length += FUNC_STD_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "AHKPATH\Lib.lnk" LIBRARY:
this_lib++; // For convenience and maintainability.
BIV_AhkPath(this_lib->path, _T(""));
_tcscpy(_tcsrchr(this_lib->path,'\\')+1,_T("Lib.lnk"));
*(_tcsrchr(this_lib->path,'\\')+8) = '\0';
CoInitialize(NULL);
IShellLink *psl;
if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *)&psl)))
{
IPersistFile *ppf;
if (SUCCEEDED(psl->QueryInterface(IID_IPersistFile, (LPVOID *)&ppf)))
{
#ifdef UNICODE
if (SUCCEEDED(ppf->Load(this_lib->path, 0)))
#else
WCHAR wsz[MAX_PATH+1]; // +1 hasn't been explained, but is retained in case it's needed.
ToWideChar(this_lib->path, wsz, MAX_PATH+1); // Dest. size is in wchars, not bytes.
if (SUCCEEDED(ppf->Load((const WCHAR*)wsz, 0)))
#endif
{
TCHAR buf[MAX_PATH+1];
psl->GetPath(buf, MAX_PATH, NULL, SLGP_UNCPRIORITY);
_tcscpy(this_lib->path,buf);
_tcscpy(this_lib->path + _tcslen(buf),_T("\\\0"));
}
ppf->Release();
}
psl->Release();
}
CoUninitialize();
if ( !_tcsrchr(FileAttribToStr(buf, GetFileAttributes(this_lib->path)),'D') )
{
this_lib->length = 0;
*this_lib->path = '\0';
}
else
this_lib->length = _tcslen(this_lib->path);
for (i = 0; i < FUNC_LIB_COUNT; ++i)
{
attr = GetFileAttributes(sLib[i].path); // Seems to accept directories that have a trailing backslash, which is good because it simplifies the code.
if (attr == 0xFFFFFFFF || !(attr & FILE_ATTRIBUTE_DIRECTORY)) // Directory doesn't exist or it's a file vs. directory. Relies on short-circuit boolean order.
{
*sLib[i].path = '\0'; // Mark this library as disabled.
sLib[i].length = 0; //
}
}
}
// Above must ensure that all sLib[].path elements are non-NULL (but they can be "" to indicate "no library").
if (!aFuncNameLength) // Caller didn't specify, so use the entire string.
aFuncNameLength = _tcslen(aFuncName);
TCHAR *dest, *first_underscore, class_name_buf[MAX_VAR_NAME_LENGTH + 1];
LPTSTR naked_filename = aFuncName; // Set up for the first iteration.
size_t naked_filename_length = aFuncNameLength; //
for (int second_iteration = 0; second_iteration < 2; ++second_iteration)
{
for (i = 0; i < FUNC_LIB_COUNT; ++i)
{
if (!*sLib[i].path) // Library is marked disabled, so skip it.
continue;
if (sLib[i].length + naked_filename_length >= MAX_PATH-FUNC_LIB_EXT_LENGTH)
continue; // Path too long to match in this library, but try others.
dest = (LPTSTR) tmemcpy(sLib[i].path + sLib[i].length, naked_filename, naked_filename_length); // Append the filename to the library path.
_tcscpy(dest + naked_filename_length, FUNC_LIB_EXT); // Append the file extension.
attr = GetFileAttributes(sLib[i].path); // Testing confirms that GetFileAttributes() doesn't support wildcards; which is good because we want filenames containing question marks to be "not found" rather than being treated as a match-pattern.
if (attr == 0xFFFFFFFF || (attr & FILE_ATTRIBUTE_DIRECTORY)) // File doesn't exist or it's a directory. Relies on short-circuit boolean order.
continue;
aFileWasFound = true; // Indicate success for #include <lib>, which doesn't necessarily expect a function to be found.
// Since above didn't "continue", a file exists whose name matches that of the requested function.
// Before loading/including that file, set the working directory to its folder so that if it uses
// #Include, it will be able to use more convenient/intuitive relative paths. This is similar to
// the "#Include DirName" feature.
// Call SetWorkingDir() vs. SetCurrentDirectory() so that it succeeds even for a root drive like
// C: that lacks a backslash (see SetWorkingDir() for details).
terminate_here = sLib[i].path + sLib[i].length - 1; // The trailing backslash in the full-path-name to this library.
*terminate_here = '\0'; // Temporarily terminate it for use with SetWorkingDir().
SetWorkingDir(sLib[i].path); // See similar section in the #Include directive.
*terminate_here = '\\'; // Undo the termination.
if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude)
{
// For each auto-included library-file, write out two #Include lines:
// 1) Use #Include in its "change working directory" mode so that any explicit #include directives
// or FileInstalls inside the library file itself will work consistently and properly.
// 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include
// the library file itself.
// We don't directly append library files onto the main script here because:
// 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files
// might contain #Include even though it's rare).
// 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or
// subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they
// wouldn't be properly interleaved/asynchronous, but instead brought out of their library file
// and deposited separately/synchronously into the temp-include file by some new logic at the
// AutoHotkey.exe's code for the #Include directive.
// 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts.
mIncludeLibraryFunctionsThenExit->Format(_T("#Include %-0.*s\n#IncludeAgain %s\n")
, sLib[i].length, sLib[i].path, sLib[i].path);
// Now continue on normally so that our caller can continue looking for syntax errors.
}
// g->CurrentFunc is non-NULL when the function-call being resolved is inside
// a function. Save and reset it for correct behaviour in the include file:
Func *current_func = g->CurrentFunc;
g->CurrentFunc = NULL;
// Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the
// above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written.
if (!LoadIncludedFile(sLib[i].path, false, false)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included).
{
g->CurrentFunc = current_func; // Restore.
aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier.
return NULL;
}
g->CurrentFunc = current_func; // Restore.
// Now that a matching filename has been found, it seems best to stop searching here even if that
// file doesn't actually contain the requested function. This helps library authors catch bugs/typos.
// HotKeyIt, override so resource can be tried too
if (current_func = FindFunc(aFuncName, aFuncNameLength))
return current_func;
continue;
} // for() each library directory.
// Now that the first iteration is done, set up for the second one that searches by class/prefix.
// Notes about ambiguity and naming collisions:
// By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a
// match in a filename that isn't really a class, it seems inconsequential because at worst it will
// still not find the function and will then say "call to nonexistent function". In addition, the
// ability to customize which libraries are searched is planned. This would allow a publicly
// distributed script to turn off all libraries except stdlib.
if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed.
break; // All loops are done because second iteration is the last possible attempt.
naked_filename_length = first_underscore - aFuncName;
if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently).
break; // All loops are done because second iteration is the last possible attempt.
naked_filename = class_name_buf; // Point it to a buffer for use below.
tmemcpy(naked_filename, aFuncName, naked_filename_length);
naked_filename[naked_filename_length] = '\0';
} // 2-iteration for().
// HotKeyIt find library in Resource
// Since above didn't return, no match found in any library.
// Search in Resource for a library
//
// If using dll, first try find function in dll resource, then function + underscore (function_) in dll resource
// If nothing in dll resource is found, search again in main executable.
tmemcpy(class_name_buf, aFuncName, aFuncNameLength);
tmemcpy(class_name_buf + aFuncNameLength,_T(".ahk"),4);
class_name_buf[aFuncNameLength + 4] = '\0';
HRSRC lib_hResource;
BOOL aUseHinstance = true;
if (!(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB"))))
{
// Now that the resource is not found, set up for the second one that searches by class/prefix.
// Notes about ambiguity and naming collisions:
// By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a
// match in a filename that isn't really a class, it seems inconsequential because at worst it will
// still not find the function and will then say "call to nonexistent function". In addition, the
// ability to customize which libraries are searched is planned. This would allow a publicly
// distributed script to turn off all libraries except stdlib.
aUseHinstance = false;
if ( !(lib_hResource = FindResource(NULL, class_name_buf, _T("LIB"))) )
{
if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed.
goto winapi;
else
{
naked_filename_length = first_underscore - aFuncName;
if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently).
goto winapi;
tmemcpy(class_name_buf, aFuncName, naked_filename_length);
tmemcpy(class_name_buf + naked_filename_length,_T(".ahk"),4);
class_name_buf[naked_filename_length + 4] = '\0';
if ( !(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB"))) )
{
if ( !(lib_hResource = FindResource(NULL, class_name_buf, _T("LIB"))) )
goto winapi;
}
else
aUseHinstance = true;
}
}
}
// Now a resouce was found and it can be loaded
HGLOBAL hResData;
HINSTANCE ahInstance = aUseHinstance ? g_hInstance : NULL;
if ( !( (textbuf.mLength = SizeofResource(ahInstance, lib_hResource))
&& (hResData = LoadResource(ahInstance, lib_hResource))
&& (textbuf.mBuffer = LockResource(hResData)) ) )
{ // aErrorWasShown = true; // Do not display errors here
goto winapi;
}
DWORD aSizeDeCompressed = 0;
if (*(unsigned int*)textbuf.mBuffer == 0x04034b50)
{
LPVOID aDataBuf;
aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf);
if (aSizeDeCompressed)
{
LPVOID buff = _alloca(aSizeDeCompressed); // will be freed when function returns
memmove(buff,aDataBuf,aSizeDeCompressed);
SecureZeroMemory(aDataBuf, aSizeDeCompressed);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
textbuf.mLength = aSizeDeCompressed;
textbuf.mBuffer = buff;
}
}
aFileWasFound = true;
// NOTE: Ahk2Exe strips off the UTF-8 BOM.
LPTSTR resource_script = (LPTSTR)_alloca(textbuf.mLength);
tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF8);
+ tmem.Read(resource_script, textbuf.mLength);
if (aSizeDeCompressed)
SecureZeroMemory(textbuf.mBuffer, textbuf.mLength);
- tmem.Read(resource_script, textbuf.mLength);
if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude)
{
// For each auto-included library-file, write out two #Include lines:
// 1) Use #Include in its "change working directory" mode so that any explicit #include directives
// or FileInstalls inside the library file itself will work consistently and properly.
// 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include
// the library file itself.
// We don't directly append library files onto the main script here because:
// 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files
// might contain #Include even though it's rare).
// 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or
// subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they
// wouldn't be properly interleaved/asynchronous, but instead brought out of their library file
// and deposited separately/synchronously into the temp-include file by some new logic at the
// AutoHotkey.exe's code for the #Include directive.
// 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts.
mIncludeLibraryFunctionsThenExit->Format(_T("%*s\n")
, (DWORD_PTR)_tcslen(resource_script), resource_script);
// Now continue on normally so that our caller can continue looking for syntax errors.
}
// g->CurrentFunc is non-NULL when the function-call being resolved is inside
// a function. Save and reset it for correct behaviour in the include file:
Func *current_func = g->CurrentFunc;
g->CurrentFunc = NULL;
// Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the
// above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written.
if (!LoadIncludedText(resource_script, class_name_buf)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included).
{
SecureZeroMemory(resource_script, textbuf.mLength);
g->CurrentFunc = current_func; // Restore.
aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier.
return NULL;
}
SecureZeroMemory(resource_script, textbuf.mLength);
g->CurrentFunc = current_func; // Restore.
return FindFunc(aFuncName, aFuncNameLength);
winapi:
TCHAR parameter[1024] = { L'#', L'D', L'l', L'l', L'I', L'm', L'p', L'o', L'r', L't', L'\\' };
memmove(¶meter[11], aFuncName, aFuncNameLength*sizeof(TCHAR));
parameter[aFuncNameLength + 11] = L',';
parameter[aFuncNameLength + 12] = '\0';
LPTSTR found;
if (found = _tcsstr(winapi, (LPTSTR)¶meter[10]))
{
parameter[10] = L',';
LPTSTR aDest = (LPTSTR)¶meter[aFuncNameLength + 12];
LPTSTR aDllName = _tcsstr(found, _T("\t")) + 1;
size_t aNameLen = _tcsstr(aDllName, _T("\\")) - aDllName + 1;
_tcsncpy(aDest, aDllName, aNameLen);
aDest = aDest + aNameLen;
_tcsncpy(aDest, found + 1, aFuncNameLength + 1);
// Override _ in the end of definition (ahk function like SendMessage, Sleep, Send, SendInput ...
if (*(aFuncName + aFuncNameLength - 1) == '_')
{
*(aDest + aFuncNameLength - 1) = ',';
*(aDest + aFuncNameLength) = '\0';
aDest = aDest + aFuncNameLength;
}
else
{
aDest = aDest + aFuncNameLength + 1;
}
for (found = _tcsstr(found, _T(",")) + 1; *found != L'\\'; found++)
{
if (*found == L'U' || *found == L'u')
{
*aDest = L'U';
aDest++;
continue;
}
else if (*found == L'z' || *found == L'Z')
{
#ifdef _UNICODE
_tcscpy(aDest, _T("USHORT"));
aDest = aDest + 6;
#else
_tcscpy(aDest, _T("UCHAR"));
aDest = aDest + 5;
#endif
}
else if (*found == L's' || *found == L'S')
{
_tcscpy(aDest, _T("STR"));
aDest = aDest + 3;
}
else if (*found == L't' || *found == L't')
{
_tcscpy(aDest, _T("PTR"));
aDest = aDest + 3;
}
else if (*found == L'a' || *found == L'A')
{
_tcscpy(aDest, _T("ASTR"));
aDest = aDest + 4;
}
else if (*found == L'w' || *found == L'W')
{
_tcscpy(aDest, _T("WSTR"));
aDest = aDest + 4;
}
else if (*found == L'x' || *found == L'X') //TCHAR
{
#ifdef _UNICODE
_tcscpy(aDest, _T("USHORT"));
aDest = aDest + 6;
#else
_tcscpy(aDest, _T("UCHAR"));
aDest = aDest + 5;
#endif
}
else if ((*found == L'i' || *found == L'I') && *(found + 1) == L'6')
{
_tcscpy(aDest, _T("INT64"));
aDest = aDest + 5;
found++;
}
else if (*found == L'i' || *found == L'I')
{
if (*(found + 1) != L'\\' || *(aDest - 1) == 'u' || *(aDest - 1) == 'U')
{ // Not default return type int, no need to define
_tcscpy(aDest, _T("INT"));
aDest = aDest + 3;
}
else // remove last , since no return type is given
{
aDest--;
}
}
else if (*found == L'h' || *found == L'H')
{
_tcscpy(aDest, _T("SHORT"));
aDest = aDest + 5;
}
else if (*found == L'c' || *found == L'C')
{
_tcscpy(aDest, _T("CHAR"));
aDest = aDest + 4;
}
else if (*found == L'f' || *found == L'F')
{
_tcscpy(aDest, _T("FLOAT"));
aDest = aDest + 5;
}
else if (*found == L'd' || *found == L'D')
{
_tcscpy(aDest, _T("DOUBLE"));
aDest = aDest + 6;
}
if (*(found + 1) == L'*' || *(found + 1) == L'p' || *(found + 1) == L'P')
{
*aDest = *found;
aDest++;
}
_tcscpy(aDest, _T(",,"));
aDest = aDest + 2;
}
*(aDest - 2) = L'\0';
if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude)
{
// For each auto-included library-file, write out two #Include lines:
// 1) Use #Include in its "change working directory" mode so that any explicit #include directives
// or FileInstalls inside the library file itself will work consistently and properly.
// 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include
// the library file itself.
// We don't directly append library files onto the main script here because:
// 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files
// might contain #Include even though it's rare).
// 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or
// subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they
// wouldn't be properly interleaved/asynchronous, but instead brought out of their library file
// and deposited separately/synchronously into the temp-include file by some new logic at the
// AutoHotkey.exe's code for the #Include directive.
// 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts.
mIncludeLibraryFunctionsThenExit->Format(_T("%*s\n")
, _tcslen(parameter), parameter);
// Now continue on normally so that our caller can continue looking for syntax errors.
}
LoadDllFunction(_tcschr(parameter, L',') + 1, parameter);
return FindFunc(aFuncName, aFuncNameLength);
}
return NULL;
}
#endif
Func *Script::FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength, int *apInsertPos) // L27: Added apInsertPos for binary-search.
// Returns the Function whose name matches aFuncName (which caller has ensured isn't NULL).
// If it doesn't exist, NULL is returned.
{
if (!aFuncNameLength) // Caller didn't specify, so use the entire string.
aFuncNameLength = _tcslen(aFuncName);
if (apInsertPos) // L27: Set default for maintainability.
*apInsertPos = -1;
// For the below, no error is reported because callers don't want that. Instead, simply return
// NULL to indicate that names that are illegal or too long are not found. If the caller later
// tries to add the function, it will get an error then:
if (aFuncNameLength > MAX_VAR_NAME_LENGTH)
return NULL;
// The following copy is made because it allows the name searching to use _tcsicmp() instead of
// strlicmp(), which close to doubles the performance. The copy includes only the first aVarNameLength
// characters from aVarName:
TCHAR func_name[MAX_VAR_NAME_LENGTH + 1];
tcslcpy(func_name, aFuncName, aFuncNameLength + 1); // +1 to convert length to size.
Func *pfunc;
// Using a binary searchable array vs a linked list speeds up dynamic function calls, on average.
int left, right, mid, result;
for (left = 0, right = mFuncCount - 1; left <= right;)
{
mid = (left + right) / 2;
result = _tcsicmp(func_name, mFunc[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance.
if (result > 0)
left = mid + 1;
else if (result < 0)
right = mid - 1;
else // Match found.
return mFunc[mid];
}
if (apInsertPos)
*apInsertPos = left;
// Since above didn't return, there is no match. See if it's a built-in function that hasn't yet
// been added to the function list.
// Set defaults to be possibly overridden below:
int min_params = 1;
int max_params = 1;
BuiltInFunctionType bif;
LPTSTR suffix = func_name + 3;
#ifndef MINIDLL
if (!_tcsnicmp(func_name, _T("LV_"), 3)) // As a built-in function, LV_* can only be a ListView function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("GetNext")))
{
bif = BIF_LV_GetNextOrCount;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("GetCount")))
{
bif = BIF_LV_GetNextOrCount;
min_params = 0; // But leave max at its default of 1.
}
else if (!_tcsicmp(suffix, _T("GetText")))
{
bif = BIF_LV_GetText;
min_params = 2;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_LV_AddInsertModify;
min_params = 0; // 0 params means append a blank row.
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Insert")))
{
bif = BIF_LV_AddInsertModify;
// Leave min_params at 1. Passing only 1 param to it means "insert a blank row".
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Modify")))
{
bif = BIF_LV_AddInsertModify; // Although it shares the same function with "Insert", it can still have its own min/max params.
min_params = 2;
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Delete")))
{
bif = BIF_LV_Delete;
min_params = 0; // Leave max at its default of 1.
}
else if (!_tcsicmp(suffix, _T("InsertCol")))
{
bif = BIF_LV_InsertModifyDeleteCol;
// Leave min_params at 1 because inserting a blank column ahead of the first column
// does not seem useful enough to sacrifice the no-parameter mode, which might have
// potential future uses.
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("ModifyCol")))
{
bif = BIF_LV_InsertModifyDeleteCol;
min_params = 0;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("DeleteCol")))
bif = BIF_LV_InsertModifyDeleteCol; // Leave min/max set to 1.
else if (!_tcsicmp(suffix, _T("SetImageList")))
{
bif = BIF_LV_SetImageList;
max_params = 2; // Leave min at 1.
}
else
return NULL;
}
else if (!_tcsnicmp(func_name, _T("TV_"), 3)) // As a built-in function, TV_* can only be a TreeView function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_TV_AddModifyDelete;
max_params = 3; // Leave min at its default of 1.
}
else if (!_tcsicmp(suffix, _T("Modify")))
{
bif = BIF_TV_AddModifyDelete;
max_params = 3; // One-parameter mode is "select specified item".
}
else if (!_tcsicmp(suffix, _T("Delete")))
{
bif = BIF_TV_AddModifyDelete;
min_params = 0;
}
else if (!_tcsicmp(suffix, _T("GetParent")) || !_tcsicmp(suffix, _T("GetChild")) || !_tcsicmp(suffix, _T("GetPrev")))
bif = BIF_TV_GetRelatedItem;
else if (!_tcsicmp(suffix, _T("GetCount")) || !_tcsicmp(suffix, _T("GetSelection")))
{
bif = BIF_TV_GetRelatedItem;
min_params = 0;
max_params = 0;
}
else if (!_tcsicmp(suffix, _T("GetNext"))) // Unlike "Prev", Next also supports 0 or 2 parameters.
{
bif = BIF_TV_GetRelatedItem;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("Get")) || !_tcsicmp(suffix, _T("GetText")))
{
bif = BIF_TV_Get;
min_params = 2;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("SetImageList")))
{
bif = BIF_TV_SetImageList;
max_params = 2; // Leave min at 1.
}
else
return NULL;
}
else if (!_tcsnicmp(func_name, _T("IL_"), 3)) // It's an ImageList function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("Create")))
{
bif = BIF_IL_Create;
min_params = 0;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("Destroy")))
{
bif = BIF_IL_Destroy; // Leave Min/Max set to 1.
}
else if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_IL_Add;
min_params = 2;
max_params = 4;
}
else
return NULL;
}
else if (!_tcsicmp(func_name, _T("SB_SetText")))
{
bif = BIF_StatusBar;
max_params = 3; // Leave min_params at its default of 1.
}
else if (!_tcsicmp(func_name, _T("SB_SetParts")))
{
bif = BIF_StatusBar;
min_params = 0;
max_params = 255; // 255 params allows for up to 256 parts, which is SB's max.
}
else if (!_tcsicmp(func_name, _T("SB_SetIcon")))
{
bif = BIF_StatusBar;
max_params = 3; // Leave min_params at its default of 1.
}
else if (!_tcsicmp(func_name, _T("StrLen")))
#else
if (!_tcsicmp(func_name, _T("StrLen")))
#endif
bif = BIF_StrLen;
else if (!_tcsicmp(func_name, _T("SubStr")))
{
bif = BIF_SubStr;
min_params = 2;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("Struct")))
{
bif = BIF_Struct;
min_params = 1;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("Sizeof")))
{
bif = BIF_sizeof;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("CriticalObject")))
{
bif = BIF_CriticalObject;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("Lock")))
{
bif = BIF_Lock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("TryLock")))
{
bif = BIF_TryLock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("UnLock")))
{
bif = BIF_UnLock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("FindFunc"))) // addFile() Naveen v8.
{
bif = BIF_FindFunc;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("FindLabel"))) // HotKeyIt v1.1.02.00
{
bif = BIF_FindLabel;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("Alias"))) // lowlevel() Naveen v9.
{
bif = BIF_Alias;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("UnZipRawMemory"))) // lowlevel() Naveen v9.
{
bif = BIF_UnZipRawMemory;
min_params = 1;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("getTokenValue"))) // lowlevel() Naveen v9.
{
bif = BIF_getTokenValue;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("CacheEnable"))) // lowlevel() Naveen v9.
{
bif = BIF_CacheEnable;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("Getvar"))) // lowlevel() Naveen v9.
{
bif = BIF_Getvar;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("Trim")) || !_tcsicmp(func_name, _T("LTrim")) || !_tcsicmp(func_name, _T("RTrim"))) // L31
{
bif = BIF_Trim;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("InStr")))
{
bif = BIF_InStr;
min_params = 2;
max_params = 5;
}
else if (!_tcsicmp(func_name, _T("RegExMatch")))
{
bif = BIF_RegEx;
min_params = 2;
max_params = 4;
}
else if (!_tcsicmp(func_name, _T("RegExReplace")))
{
bif = BIF_RegEx;
min_params = 2;
max_params = 6;
}
else if (!_tcsicmp(func_name, _T("StrSplit")))
{
bif = BIF_StrSplit;
min_params = 1;
max_params = 3;
}
else if (!_tcsnicmp(func_name, _T("GetKey"), 6))
{
suffix = func_name + 6;
|
tinku99/ahkdll
|
7c3ba7df325717ae88d113b42aea98347174ba2b
|
Protect compiled sources
|
diff --git a/source/script.cpp b/source/script.cpp
index b1845f2..9a1a382 100644
--- a/source/script.cpp
+++ b/source/script.cpp
@@ -2981,1082 +2981,1090 @@ examine_line:
if (!_tcsicmp(remap_dest, _T("Return")))
break;
goto continue_main_loop; // It will see that remap_dest_vk is non-zero and act accordingly.
case VK_PAUSE: // Used for both "Pause" and "Break"
break;
default: // All other VKs are valid destinations and thus the remap is valid.
goto continue_main_loop; // It will see that remap_dest_vk is non-zero and act accordingly.
}
// Since above didn't goto, indicate that this is not a remap after all:
remap_dest_vk = 0;
}
}
// else don't trim hotstrings since literal spaces in both substrings are significant.
// If this is the first hotkey label encountered, Add a return before
// adding the label, so that the auto-execute section is terminated.
// Only do this if the label is a hotkey because, for example,
// the user may want to fully execute a normal script that contains
// no hotkeys but does contain normal labels to which the execution
// should fall through, if specified, rather than returning.
// But this might result in weirdness? Example:
//testlabel:
// Sleep, 1
// return
// ^a::
// return
// It would put the hard return in between, which is wrong. But in the case above,
// the first sub shouldn't have a return unless there's a part up top that ends in Exit.
// So if Exit is encountered before the first hotkey, don't add the return?
// Even though wrong, the return is harmless because it's never executed? Except when
// falling through from above into a hotkey (which probably isn't very valid anyway)?
// Update: Below must check if there are any true hotkey labels, not just regular labels.
// Otherwise, a normal (non-hotkey) label in the autoexecute section would count and
// thus the RETURN would never be added here, even though it should be:
// Notes about the below macro:
// Fix for v1.0.34: Don't point labels to this particular RETURN so that labels
// can point to the very first hotkey or hotstring in a script. For example:
// Goto Test
// Test:
// ^!z::ToolTip Without the fix`, this is never displayed by "Goto Test".
// UCHAR_MAX signals it not to point any pending labels to this RETURN.
// mCurrLine = NULL -> signifies that we're in transition, trying to load a new one.
#define CHECK_mNoHotkeyLabels \
if (mNoHotkeyLabels)\
{\
mNoHotkeyLabels = false;\
if (!AddLine(ACT_RETURN, NULL, UCHAR_MAX))\
return FAIL;\
mCurrLine = NULL;\
}
CHECK_mNoHotkeyLabels
// For hotstrings, the below makes the label include leading colon(s) and the full option
// string (if any) so that the uniqueness of labels is preserved. For example, we want
// the following two hotstring labels to be unique rather than considered duplicates:
// ::abc::
// :c:abc::
if (!AddLabel(buf, true)) // Always add a label before adding the first line of its section.
return FAIL;
hook_action = 0; // Set default.
if (*hotkey_flag) // This hotkey's action is on the same line as its label.
{
if (!hotstring_start)
// Don't add the alt-tabs as a line, since it has no meaning as a script command.
// But do put in the Return regardless, in case this label is ever jumped to
// via Goto/Gosub:
if ( !(hook_action = Hotkey::ConvertAltTab(hotkey_flag, false)) )
if (!ParseAndAddLine(hotkey_flag))
return FAIL;
// Also add a Return that's implicit for a single-line hotkey. This is also
// done for auto-replace hotstrings in case gosub/goto is ever used to jump
// to their labels:
if (!AddLine(ACT_RETURN))
return FAIL;
}
if (hotstring_start)
{
if (!*hotstring_start)
{
// The following error message won't indicate the correct line number because
// the hotstring (as a label) does not actually exist as a line. But it seems
// best to report it this way in case the hotstring is inside a #Include file,
// so that the correct file name and approximate line number are shown:
return ScriptError(_T("This hotstring is missing its abbreviation."), buf); // Display buf vs. hotkey_flag in case the line is simply "::::".
}
// In the case of hotstrings, hotstring_start is the beginning of the hotstring itself,
// i.e. the character after the second colon. hotstring_options is NULL if no options,
// otherwise it's the first character in the options list (option string is not terminated,
// but instead ends in a colon). hotkey_flag is blank if it's not an auto-replace
// hotstring, otherwise it contains the auto-replace text.
// v1.0.42: Unlike hotkeys, duplicate hotstrings are not detected. This is because
// hotstrings are less commonly used and also because it requires more code to find
// hotstring duplicates (and performs a lot worse if a script has thousands of
// hotstrings) because of all the hotstring options.
if (!Hotstring::AddHotstring(mLastLabel, hotstring_options ? hotstring_options : _T("")
, hotstring_start, hotkey_flag, has_continuation_section))
return FAIL;
}
else // It's a hotkey vs. hotstring.
{
if (hk = Hotkey::FindHotkeyByTrueNature(buf, suffix_has_tilde, hook_is_mandatory)) // Parent hotkey found. Add a child/variant hotkey for it.
{
if (hook_action) // suffix_has_tilde has always been ignored for these types (alt-tab hotkeys).
{
// Hotkey::Dynamic() contains logic and comments similar to this, so maintain them together.
// An attempt to add an alt-tab variant to an existing hotkey. This might have
// merit if the intention is to make it alt-tab now but to later disable that alt-tab
// aspect via the Hotkey cmd to let the context-sensitive variants shine through
// (take effect).
hk->mHookAction = hook_action;
}
else
{
// Detect duplicate hotkey variants to help spot bugs in scripts.
if (hk->FindVariant()) // See if there's already a variant matching the current criteria (suffix_has_tilde does not make variants distinct form each other because it would require firing two hotkey IDs in response to pressing one hotkey, which currently isn't in the design).
{
mCurrLine = NULL; // Prevents showing unhelpful vicinity lines.
return ScriptError(_T("Duplicate hotkey."), buf);
}
if (!hk->AddVariant(mLastLabel, suffix_has_tilde))
return ScriptError(ERR_OUTOFMEM, buf);
if (hook_is_mandatory || (!g_os.IsWin9x() && g_ForceKeybdHook))
{
// Require the hook for all variants of this hotkey if any variant requires it.
// This seems more intuitive than the old behaviour, which required $ or #UseHook
// to be used on the *first* variant, even though it affected all variants.
#ifdef CONFIG_WIN9X
if (g_os.IsWin9x())
hk->mUnregisterDuringThread = true;
else
#endif
hk->mKeybdHookMandatory = true;
}
}
}
else // No parent hotkey yet, so create it.
if ( !(hk = Hotkey::AddHotkey(mLastLabel, hook_action, NULL, suffix_has_tilde, false)) )
return FAIL; // It already displayed the error.
}
goto continue_main_loop; // In lieu of "continue", for performance.
} // if (is_label = ...)
#endif
// Otherwise, not a hotkey or hotstring. Check if it's a generic, non-hotkey label:
if (buf[buf_length - 1] == ':') // Labels must end in a colon (buf was previously rtrimmed).
{
if (buf_length == 1) // v1.0.41.01: Properly handle the fact that this line consists of only a colon.
return ScriptError(ERR_UNRECOGNIZED_ACTION, buf);
// Labels (except hotkeys) must contain no whitespace, delimiters, or escape-chars.
// This is to avoid problems where a legitimate action-line ends in a colon,
// such as "WinActivate SomeTitle" and "#Include c:".
// We allow hotkeys to violate this since they may contain commas, and since a normal
// script line (i.e. just a plain command) is unlikely to ever end in a double-colon:
for (cp = buf, is_label = true; *cp; ++cp)
if (IS_SPACE_OR_TAB(*cp) || *cp == g_delimiter || *cp == g_EscapeChar)
{
is_label = false;
break;
}
if (is_label) // It's a generic, non-hotkey/non-hotstring label.
{
// v1.0.44.04: Fixed this check by moving it after the above loop.
// Above has ensured buf_length>1, so it's safe to check for double-colon:
// v1.0.44.03: Don't allow anything that ends in "::" (other than a line consisting only
// of "::") to be a normal label. Assume it's a command instead (if it actually isn't, a
// later stage will report it as "invalid hotkey"). This change avoids the situation in
// which a hotkey like ^!ä:: is seen as invalid because the current keyboard layout doesn't
// have a "ä" key. Without this change, if such a hotkey appears at the top of the script,
// its subroutine would execute immediately as a normal label, which would be especially
// bad if the hotkey were something like the "Shutdown" command.
if (buf[buf_length - 2] == ':' && buf_length > 2) // i.e. allow "::" as a normal label, but consider anything else with double-colon to be a failed-hotkey label that terminates the auto-exec section.
{
//CHECK_mNoHotkeyLabels // Terminate the auto-execute section since this is a failed hotkey vs. a mere normal label.
sntprintf(msg_text, _countof(msg_text), _T("Note: The hotkey %s will not be active because it does not exist in the current keyboard layout."), buf);
MsgBox(msg_text);
}
buf[--buf_length] = '\0'; // Remove the trailing colon.
rtrim(buf, buf_length); // Has already been ltrimmed.
if (!AddLabel(buf, false))
return FAIL;
goto continue_main_loop; // In lieu of "continue", for performance.
}
}
// Since above didn't "goto", it's not a label.
if (*buf == '#')
{
saved_line_number = mCombinedLineNumber; // Backup in case IsDirective() processes an include file, which would change mCombinedLineNumber's value.
switch(IsDirective(buf)) // Note that it may alter the contents of buf, at least in the case of #IfWin.
{
case CONDITION_TRUE:
// Since the directive may have been a #include which called us recursively,
// restore the class's values for these two, which are maintained separately
// like this to avoid having to specify them in various calls, especially the
// hundreds of calls to ScriptError() and LineError():
mCurrFileIndex = source_file_index;
mCombinedLineNumber = saved_line_number;
goto continue_main_loop; // In lieu of "continue", for performance.
case FAIL: // IsDirective() already displayed the error.
return FAIL;
//case CONDITION_FALSE: Do nothing; let processing below handle it.
}
}
// Otherwise, treat it as a normal script line.
if (*buf == '{' || *buf == '}')
{
if (!AddLine(*buf == '{' ? ACT_BLOCK_BEGIN : ACT_BLOCK_END))
return FAIL;
// Allow any command/action, directive or label to the right of "{" or "}":
if ( *(buf = omit_leading_whitespace(buf + 1)) )
{
buf_length = _tcslen(buf); // Update.
mCurrLine = NULL; // To signify that we're in transition, trying to load a new line.
goto process_completed_line; // Have the main loop process the contents of "buf" as though it came in from the script.
}
goto continue_main_loop; // It's just a naked "{" or "}", so no more processing needed for this line.
}
// First do a little special handling to support actions on the same line as their
// ELSE or TRY, e.g.:
// else if x = 1
// try someFunction()
// This is done here rather than in ParseAndAddLine() because it's fairly
// complicated to do there (already tried it) mostly due to the fact that
// literal_map has to be properly passed in a recursive call to itself, as well
// as properly detecting special commands that don't have keywords such as
// IF comparisons, ACT_ASSIGN, +=, -=, etc.
// v1.0.41: '{' was added to the line below to support no spaces inside "}else{".
if (!(action_end = StrChrAny(buf, _T("\t ,{")))) // Position of first tab/space/comma/open-brace. For simplicity, a non-standard g_delimiter is not supported.
action_end = buf + buf_length; // It's done this way so that ELSE can be fully handled here; i.e. that ELSE does not have to be in the list of commands recognizable by ParseAndAddLine().
// The following method ensures that words or variables that start with "Else", e.g. ElseAction, are not
// incorrectly detected as an Else command:
int try_cmp = 1, finally_cmp = 1;
if (tcslicmp(buf, _T("Else"), action_end - buf) // It's not an ELSE, a TRY or a FINALLY. ("Else"/"Try"/"Finally" is used vs. g_act[ACT_ELSE/TRY/FINALLY].Name for performance).
&& (try_cmp = tcslicmp(buf, _T("Try"), action_end - buf))
&& (finally_cmp = tcslicmp(buf, _T("Finally"), action_end - buf)))
{
if (!ParseAndAddLine(buf))
return FAIL;
}
else // This line is an ELSE, a TRY or a FINALLY, possibly with another command immediately after it (on the same line).
{
// Add the ELSE, TRY or FINALLY directly rather than calling ParseAndAddLine() because that function
// would resolve escape sequences throughout the entire length of <buf>, which we
// don't want because we wouldn't have access to the corresponding literal-map to
// figure out the proper use of escaped characters:
if (!AddLine(try_cmp ? (finally_cmp ? ACT_ELSE : ACT_FINALLY) : ACT_TRY))
return FAIL;
mCurrLine = NULL; // To signify that we're in transition, trying to load a new one.
buf = omit_leading_whitespace(action_end); // Now buf is the word after the ELSE or TRY.
if (*buf == g_delimiter) // Allow "else, action", "try, action" and "finally, action"
buf = omit_leading_whitespace(buf + 1);
// Allow any command/action to the right of "else", "try" or "finally", including "{":
if (*buf)
{
// This is done rather than calling ParseAndAddLine() as it handles "{" in a way that
// anything to the right of it is considered an arg of that line and is basically ignored.
buf_length = _tcslen(buf); // Update.
mCurrLine = NULL; // To signify that we're in transition, trying to load a new line.
goto examine_line; // Have the main loop process the contents of "buf" as though it came in from the script.
}
// Otherwise, there was either no same-line action, so do nothing.
}
continue_main_loop: // This method is used in lieu of "continue" for performance and code size reduction.
#ifndef MINIDLL
if (remap_dest_vk)
{
// For remapping, decided to use a "macro expansion" approach because I think it's considerably
// smaller in code size and complexity than other approaches would be. I originally wanted to
// do it with the hook by changing the incoming event prior to passing it back out again (for
// example, a::b would transform an incoming 'a' keystroke into 'b' directly without having
// to suppress the original keystroke and simulate a new one). Unfortunately, the low-level
// hooks apparently do not allow this. Here is the test that confirmed it:
// if (event.vkCode == 'A')
// {
// event.vkCode = 'B';
// event.scanCode = 0x30; // Or use vk_to_sc(event.vkCode).
// return CallNextHookEx(g_KeybdHook, aCode, wParam, lParam);
// }
switch (++remap_stage)
{
case 1: // Stage 1: Add key-down hotkey label, e.g. *LButton::
buf_length = _stprintf(buf, _T("*%s::"), remap_source); // Should be no risk of buffer overflow due to prior validation.
goto examine_line; // Have the main loop process the contents of "buf" as though it came in from the script.
case 2: // Stage 2.
// Copied into a writable buffer for maintainability: AddLine() might rely on this.
// Also, it seems unnecessary to set press-duration to -1 even though the auto-exec section might
// have set it to something higher than -1 because:
// 1) Press-duration doesn't apply to normal remappings since they use down-only and up-only events.
// 2) Although it does apply to remappings such as a::B and a::^b (due to press-duration being
// applied after a change to modifier state), those remappings are fairly rare and supporting
// a non-negative-one press-duration (almost always 0) probably adds a degree of flexibility
// that may be desirable to keep.
// 3) SendInput may become the predominant SendMode, so press-duration won't often be in effect anyway.
// 4) It has been documented that remappings use the auto-execute section's press-duration.
_tcscpy(buf, _T("-1")); // Does NOT need to be "-1, -1" for SetKeyDelay (see above).
// The primary reason for adding Key/MouseDelay -1 is to minimize the chance that a one of
// these hotkey threads will get buried under some other thread such as a timer, which
// would disrupt the remapping if #MaxThreadsPerHotkey is at its default of 1.
AddLine(remap_dest_is_mouse ? ACT_SETMOUSEDELAY : ACT_SETKEYDELAY, &buf, 1, NULL); // PressDuration doesn't need to be specified because it doesn't affect down-only and up-only events.
if (remap_keybd_to_mouse)
{
// Since source is keybd and dest is mouse, prevent keyboard auto-repeat from auto-repeating
// the mouse button (since that would be undesirable 90% of the time). This is done
// by inserting a single extra IF-statement above the Send that produces the down-event:
buf_length = _stprintf(buf, _T("if not GetKeyState(\"%s\")"), remap_dest); // Should be no risk of buffer overflow due to prior validation.
remap_stage = 9; // Have it hit special stage 9+1 next time for code reduction purposes.
goto examine_line; // Have the main loop process the contents of "buf" as though it came in from the script.
}
// Otherwise, remap_keybd_to_mouse==false, so fall through to next case.
case 10:
extra_event = _T(""); // Set default.
switch (remap_dest_vk)
{
case VK_LMENU:
case VK_RMENU:
case VK_MENU:
switch (remap_source_vk)
{
case VK_LCONTROL:
case VK_CONTROL:
extra_event = _T("{LCtrl up}"); // Somewhat surprisingly, this is enough to make "Ctrl::Alt" properly remap both right and left control.
break;
case VK_RCONTROL:
extra_event = _T("{RCtrl up}");
break;
// Below is commented out because its only purpose was to allow a shift key remapped to alt
// to be able to alt-tab. But that wouldn't work correctly due to the need for the following
// hotkey, which does more harm than good by impacting the normal Alt key's ability to alt-tab
// (if the normal Alt key isn't remapped): *Tab::Send {Blind}{Tab}
//case VK_LSHIFT:
//case VK_SHIFT:
// extra_event = "{LShift up}";
// break;
//case VK_RSHIFT:
// extra_event = "{RShift up}";
// break;
}
break;
}
mCurrLine = NULL; // v1.0.40.04: Prevents showing misleading vicinity lines for a syntax-error such as %::%
_stprintf(buf, _T("{Blind}%s%s{%s DownTemp}"), extra_event, remap_dest_modifiers, remap_dest); // v1.0.44.05: DownTemp vs. Down. See Send's DownTemp handler for details.
if (!AddLine(ACT_SEND, &buf, 1, NULL)) // v1.0.40.04: Check for failure due to bad remaps such as %::%.
return FAIL;
AddLine(ACT_RETURN);
// Add key-up hotkey label, e.g. *LButton up::
buf_length = _stprintf(buf, _T("*%s up::"), remap_source); // Should be no risk of buffer overflow due to prior validation.
remap_stage = 2; // Adjust to hit stage 3 next time (in case this is stage 10).
goto examine_line; // Have the main loop process the contents of "buf" as though it came in from the script.
case 3: // Stage 3.
_tcscpy(buf, _T("-1"));
AddLine(remap_dest_is_mouse ? ACT_SETMOUSEDELAY : ACT_SETKEYDELAY, &buf, 1, NULL);
_stprintf(buf, _T("{Blind}{%s Up}"), remap_dest); // Unlike the down-event above, remap_dest_modifiers is not included for the up-event; e.g. ^{b up} is inappropriate.
AddLine(ACT_SEND, &buf, 1, NULL);
AddLine(ACT_RETURN);
remap_dest_vk = 0; // Reset to signal that the remapping expansion is now complete.
break; // Fall through to the next section so that script loading can resume at the next line.
}
} // if (remap_dest_vk)
#endif
// Since above didn't "continue", resume loading script line by line:
buf = next_buf;
buf_length = next_buf_length;
next_buf = (buf == buf1) ? buf2 : buf1;
// The line above alternates buffers (toggles next_buf to be the unused buffer), which helps
// performance because it avoids memcpy from buf2 to buf1.
} // for each whole/constructed line.
if (*pending_buf) // Since this is the last non-comment line, the pending function must be a function call, not a function definition.
{
// Somewhat messy to decrement then increment later, but it's probably easier than the
// alternatives due to the use of "continue" in some places above.
saved_line_number = mCombinedLineNumber;
mCombinedLineNumber = pending_buf_line_number; // Done so that any syntax errors that occur during the calls below will report the correct line number.
if (pending_buf_type != Pending_Func)
return ScriptError(pending_buf_has_brace ? ERR_MISSING_CLOSE_BRACE : ERR_MISSING_OPEN_BRACE, pending_buf);
if (!ParseAndAddLine(pending_buf, ACT_EXPRESSION)) // Must be function call vs. definition since otherwise the above would have detected the opening brace beneath it and already cleared pending_function.
return FAIL;
mCombinedLineNumber = saved_line_number;
}
if (mClassObjectCount && !source_file_index) // or mClassProperty, which implies mClassObjectCount != 0.
{
// A class definition has not been closed with "}". Previously this was detected by adding
// the open and close braces as lines, but this way is simpler and has less overhead.
// The downside is that the line number won't be shown; however, the class name will.
// Seems okay not to show mClassProperty->mName since the class is missing "}" as well.
return ScriptError(ERR_MISSING_CLOSE_BRACE, mClassName);
}
++mCombinedLineNumber; // L40: Put the implicit ACT_EXIT on the line after the last physical line (for the debugger).
// This is not required, it is called by the destructor.
// fp->Close();
return OK;
}
#endif
ResultType Script::LoadIncludedFile(LPTSTR aFileSpec, bool aAllowDuplicateInclude, bool aIgnoreLoadFailure)
// Returns OK or FAIL.
// Below: Use double-colon as delimiter to set these apart from normal labels.
// The main reason for this is that otherwise the user would have to worry
// about a normal label being unintentionally valid as a hotkey, e.g.
// "Shift:" might be a legitimate label that the user forgot is also
// a valid hotkey:
#define HOTKEY_FLAG _T("::")
#define HOTKEY_FLAG_LENGTH 2
{
if (!aFileSpec || !*aFileSpec) return FAIL;
#ifndef AUTOHOTKEYSC
if (Line::sSourceFileCount >= Line::sMaxSourceFiles)
{
if (Line::sSourceFileCount >= ABSOLUTE_MAX_SOURCE_FILES)
return ScriptError(_T("Too many includes.")); // Short msg since so rare.
int new_max;
if (Line::sMaxSourceFiles)
{
new_max = 2*Line::sMaxSourceFiles;
if (new_max > ABSOLUTE_MAX_SOURCE_FILES)
new_max = ABSOLUTE_MAX_SOURCE_FILES;
}
else
new_max = 100;
// For simplicity and due to rarity of every needing to, expand by reallocating the array.
// Use a temp var. because realloc() returns NULL on failure but leaves original block allocated.
LPTSTR *realloc_temp = (LPTSTR *)realloc(Line::sSourceFile, new_max * sizeof(LPTSTR)); // If passed NULL, realloc() will do a malloc().
if (!realloc_temp)
return ScriptError(ERR_OUTOFMEM); // Short msg since so rare.
Line::sSourceFile = realloc_temp;
Line::sMaxSourceFiles = new_max;
}
TCHAR full_path[MAX_PATH];
#endif
// Keep this var on the stack due to recursion, which allows newly created lines to be given the
// correct file number even when some #include's have been encountered in the middle of the script:
int source_file_index = Line::sSourceFileCount;
if (!source_file_index)
// Since this is the first source file, it must be the main script file. Just point it to the
// location of the filespec already dynamically allocated:
Line::sSourceFile[source_file_index] = mFileSpec;
#ifndef AUTOHOTKEYSC // The "else" part below should never execute for compiled scripts since they never include anything (other than the main/combined script).
else
{
// Get the full path in case aFileSpec has a relative path. This is done so that duplicates
// can be reliably detected (we only want to avoid including a given file more than once):
LPTSTR filename_marker;
GetFullPathName(aFileSpec, _countof(full_path), full_path, &filename_marker);
// Check if this file was already included. If so, it's not an error because we want
// to support automatic "include once" behavior. So just ignore repeats:
if (!aAllowDuplicateInclude)
for (int f = 0; f < source_file_index; ++f) // Here, source_file_index==Line::sSourceFileCount
if (!lstrcmpi(Line::sSourceFile[f], full_path)) // Case insensitive like the file system (testing shows that "Ä" == "ä" in the NTFS, which is hopefully how lstrcmpi works regardless of locale).
return OK;
// The file is added to the list further below, after the file has been opened, in case the
// opening fails and aIgnoreLoadFailure==true.
}
#endif
// <buf> should be no larger than LINE_SIZE because some later functions rely upon that:
TCHAR msg_text[MAX_PATH + 256], buf1[LINE_SIZE], buf2[LINE_SIZE], suffix[16], pending_buf[LINE_SIZE] = _T("");
LPTSTR buf = buf1, next_buf = buf2; // Oscillate between bufs to improve performance (avoids memcpy from buf2 to buf1).
size_t buf_length, next_buf_length, suffix_length;
bool pending_buf_has_brace;
TextStream *fp;
TextFile tfile;
TextMem tmem;
enum {
Pending_Func,
Pending_Class,
Pending_Property
} pending_buf_type;
#ifndef AUTOHOTKEYSC
if (!g_hResource || Line::sSourceFileCount) // It is not a compiled exe or main script was already loaded
{
if (!tfile.Open(aFileSpec, DEFAULT_READ_FLAGS, g_DefaultScriptCodepage))
{
if (aIgnoreLoadFailure)
return OK;
sntprintf(msg_text, _countof(msg_text), _T("%s file \"%s\" cannot be opened.")
, Line::sSourceFileCount > 0 ? _T("#Include") : _T("Script"), aFileSpec);
return ScriptError(msg_text);
}
fp = &tfile;
// This is done only after the file has been successfully opened in case aIgnoreLoadFailure==true:
if (source_file_index > 0)
{
Line::sSourceFile[source_file_index] = tmalloc(_tcslen(full_path)+1); //SimpleHeap::Malloc(full_path);
if (Line::sSourceFile[source_file_index] == 0)
{
ScriptError(ERR_OUTOFMEM);
return FAIL;
}
_tcscpy(Line::sSourceFile[source_file_index],full_path);
}
}
else
{
HGLOBAL hResData;
TextMem::Buffer textbuf(NULL, 0, false);
if ( !( (textbuf.mLength = SizeofResource(g_hInstance, g_hResource))
&& (hResData = LoadResource(g_hInstance, g_hResource))
&& (textbuf.mBuffer = LockResource(hResData)) ) )
{
MsgBox(_T("Could not extract script from EXE."), 0, aFileSpec);
return FAIL;
}
+ DWORD aSizeDeCompressed = 0;
if (*(unsigned int*)textbuf.mBuffer == 0x04034b50)
{
LPVOID aDataBuf;
- DWORD aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf,g_default_pwd);
+ aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf,g_default_pwd);
if (aSizeDeCompressed)
{
LPVOID buff = _alloca(aSizeDeCompressed); // will be freed when function returns
memmove(buff,aDataBuf,aSizeDeCompressed);
+ SecureZeroMemory(aDataBuf, aSizeDeCompressed);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
textbuf.mLength = aSizeDeCompressed;
textbuf.mBuffer = buff;
}
}
fp = &tmem;
// NOTE: Ahk2Exe strips off the UTF-8 BOM.
tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF8);
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, textbuf.mLength);
}
//else the first file was already taken care of by another means.
#else // Stand-alone mode (there are no include files in this mode since all of them were merged into the main script at the time of compiling).
TextMem::Buffer textbuf(NULL, 0, false);
HRSRC hRes;
HGLOBAL hResData;
#ifdef _DEBUG
if (hRes = FindResource(NULL, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA)))
#else
if (hRes = FindResource(NULL, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA)))
#endif
mCompiledHasCustomIcon = false;
else if (hRes = FindResource(NULL, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA)))
mCompiledHasCustomIcon = true;
if ( !( hRes
&& (textbuf.mLength = SizeofResource(NULL, hRes))
&& (hResData = LoadResource(NULL, hRes))
&& (textbuf.mBuffer = LockResource(hResData)) ) )
{
MsgBox(_T("Could not extract script from EXE."), 0, aFileSpec);
return FAIL;
}
+ DWORD aSizeDeCompressed = 0;
if (*(unsigned int*)textbuf.mBuffer == 0x04034b50)
{
LPVOID aDataBuf;
- DWORD aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf,g_default_pwd);
+ aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf,g_default_pwd);
if (aSizeDeCompressed)
{
LPVOID buff = _alloca(aSizeDeCompressed); // will be freed when function returns
memmove(buff,aDataBuf,aSizeDeCompressed);
+ SecureZeroMemory(aDataBuf, aSizeDeCompressed);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
textbuf.mLength = aSizeDeCompressed;
textbuf.mBuffer = buff;
}
}
fp = &tmem;
// NOTE: Ahk2Exe strips off the UTF-8 BOM.
tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF8);
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, textbuf.mLength);
#endif
++Line::sSourceFileCount;
// File is now open, read lines from it.
#ifndef MINIDLL
LPTSTR hotkey_flag, cp, cp1, action_end, hotstring_start, hotstring_options;
Hotkey *hk;
#else
LPTSTR hotkey_flag, cp, cp1, action_end;
#endif
LineNumberType pending_buf_line_number, saved_line_number;
#ifndef MINIDLL
HookActionType hook_action;
bool is_label, suffix_has_tilde, hook_is_mandatory, in_comment_section, hotstring_options_all_valid;
#else
bool is_label, in_comment_section;
#endif
#ifndef MINIDLL
// For the remap mechanism, e.g. a::b
int remap_stage;
vk_type remap_source_vk, remap_dest_vk = 0; // Only dest is initialized to enforce the fact that it is the flag/signal to indicate whether remapping is in progress.
TCHAR remap_source[32], remap_dest[32], remap_dest_modifiers[8]; // Must fit the longest key name (currently Browser_Favorites [17]), but buffer overflow is checked just in case.
LPTSTR extra_event;
bool remap_source_is_mouse, remap_dest_is_mouse, remap_keybd_to_mouse;
#endif
// For the line continuation mechanism:
bool do_ltrim, do_rtrim, literal_escapes, literal_derefs, literal_delimiters
, has_continuation_section, is_continuation_line;
#define CONTINUATION_SECTION_WITHOUT_COMMENTS 1 // MUST BE 1 because it's the default set by anything that's boolean-true.
#define CONTINUATION_SECTION_WITH_COMMENTS 2 // Zero means "not in a continuation section".
int in_continuation_section;
LPTSTR next_option, option_end;
TCHAR orig_char, one_char_string[2], two_char_string[3]; // Line continuation mechanism's option parsing.
one_char_string[1] = '\0'; // Pre-terminate these to simplify code later below.
two_char_string[2] = '\0'; //
int continuation_line_count;
#define MAX_FUNC_VAR_GLOBALS 2000
Var *func_global_var[MAX_FUNC_VAR_GLOBALS];
// Init both for main file and any included files loaded by this function:
mCurrFileIndex = source_file_index; // source_file_index is kept on the stack due to recursion (from #include).
#ifdef AUTOHOTKEYSC
// -1 (MAX_UINT in this case) to compensate for the fact that there is a comment containing
// the version number added to the top of each compiled script:
LineNumberType phys_line_number = -1;
#else
LineNumberType phys_line_number = 0;
#endif
buf_length = GetLine(buf, LINE_SIZE - 1, 0, fp);
if (in_comment_section = !_tcsncmp(buf, _T("/*"), 2))
{
// Fixed for v1.0.35.08. Must reset buffer to allow a script's first line to be "/*".
*buf = '\0';
buf_length = 0;
}
while (buf_length != -1) // Compare directly to -1 since length is unsigned.
{
// For each whole line (a line with continuation section is counted as only a single line
// for the purpose of this outer loop).
// Keep track of this line's *physical* line number within its file for A_LineNumber and
// error reporting purposes. This must be done only in the outer loop so that it tracks
// the topmost line of any set of lines merged due to continuation section/line(s)..
mCombinedLineNumber = phys_line_number + 1;
// This must be reset for each iteration because a prior iteration may have changed it, even
// indirectly by calling something that changed it:
mCurrLine = NULL; // To signify that we're in transition, trying to load a new one.
// v1.0.44.13: An additional call to IsDirective() is now made up here so that #CommentFlag affects
// the line beneath it the same way as other lines (#EscapeChar et. al. didn't have this bug).
// It's best not to process ALL directives up here because then they would no longer support a
// continuation section beneath them (and possibly other drawbacks because it was never thoroughly
// tested).
if (!_tcsnicmp(buf, _T("#CommentFlag"), 12)) // Have IsDirective() process this now (it will also process it again later, which is harmless).
if (IsDirective(buf) == FAIL) // IsDirective() already displayed the error.
return FAIL;
// Read in the next line (if that next line is the start of a continuation section, append
// it to the line currently being processed:
for (has_continuation_section = false, in_continuation_section = 0;;)
{
// This increment relies on the fact that this loop always has at least one iteration:
++phys_line_number; // Tracks phys. line number in *this* file (independent of any recursion caused by #Include).
next_buf_length = GetLine(next_buf, LINE_SIZE - 1, in_continuation_section, fp);
if (next_buf_length && next_buf_length != -1 // Prevents infinite loop when file ends with an unclosed "/*" section. Compare directly to -1 since length is unsigned.
&& !in_continuation_section) // Multi-line comments can't be used in continuation sections. This line fixes '*/' being discarded in continuation sections (broken by L54).
{
if (!_tcsncmp(next_buf, _T("*/"), 2) // Check this even if !in_comment_section so it can be ignored (for convenience) and not treated as a line-continuation operator.
&& (in_comment_section || next_buf[2] != ':' || next_buf[3] != ':')) // ...but support */:: as a hotkey.
{
in_comment_section = false;
next_buf_length -= 2; // Adjust for removal of /* from the beginning of the string.
tmemmove(next_buf, next_buf + 2, next_buf_length + 1); // +1 to include the string terminator.
next_buf_length = ltrim(next_buf, next_buf_length); // Get rid of any whitespace that was between the comment-end and remaining text.
if (!*next_buf) // The rest of the line is empty, so it was just a naked comment-end.
continue;
}
else if (in_comment_section)
continue;
if (!_tcsncmp(next_buf, _T("/*"), 2))
{
in_comment_section = true;
continue; // It's now commented out, so the rest of this line is ignored.
}
}
if (in_comment_section) // Above has incremented and read the next line, which is everything needed while inside /* .. */
{
if (next_buf_length == -1) // Compare directly to -1 since length is unsigned.
break; // By design, it's not an error. This allows "/*" to be used to comment out the bottommost portion of the script without needing a matching "*/".
// Otherwise, continue reading lines so that they can be merged with the line above them
// if they qualify as continuation lines.
continue;
}
if (!in_continuation_section) // This is either the first iteration or the line after the end of a previous continuation section.
{
// v1.0.38.06: The following has been fixed to exclude "(:" and "(::". These should be
// labels/hotkeys, not the start of a continuation section. In addition, a line that starts
// with '(' but that ends with ':' should be treated as a label because labels such as
// "(label):" are far more common than something obscure like a continuation section whose
// join character is colon, namely "(Join:".
if ( !(in_continuation_section = (next_buf_length != -1 && *next_buf == '(' // Compare directly to -1 since length is unsigned.
&& next_buf[1] != ':' && next_buf[next_buf_length - 1] != ':')) ) // Relies on short-circuit boolean order.
{
if (next_buf_length == -1) // Compare directly to -1 since length is unsigned.
break;
if (!next_buf_length)
// It is permitted to have blank lines and comment lines in between the line above
// and any continuation section/line that might come after the end of the
// comment/blank lines:
continue;
// SINCE ABOVE DIDN'T BREAK/CONTINUE, NEXT_BUF IS NON-BLANK.
if (next_buf[next_buf_length - 1] == ':' && *next_buf != ',')
// With the exception of lines starting with a comma, the last character of any
// legitimate continuation line can't be a colon because expressions can't end
// in a colon. The only exception is the ternary operator's colon, but that is
// very rare because it requires the line after it also be a continuation line
// or section, which is unusual to say the least -- so much so that it might be
// too obscure to even document as a known limitation. Anyway, by excluding lines
// that end with a colon from consideration ambiguity with normal labels
// and non-single-line hotkeys and hotstrings is eliminated.
break;
is_continuation_line = false; // Set default.
switch(ctoupper(*next_buf)) // Above has ensured *next_buf != '\0' (toupper might have problems with '\0').
{
case 'A': // "AND".
// See comments in the default section further below.
if (!_tcsnicmp(next_buf, _T("and"), 3) && IS_SPACE_OR_TAB_OR_NBSP(next_buf[3])) // Relies on short-circuit boolean order.
{
cp = omit_leading_whitespace(next_buf + 3);
// v1.0.38.06: The following was fixed to use EXPR_CORE vs. EXPR_OPERAND_TERMINATORS
// to properly detect a continuation line whose first char after AND/OR is "!~*&-+()":
if (!_tcschr(EXPR_CORE, *cp))
// This check recognizes the following examples as NON-continuation lines by checking
// that AND/OR aren't followed immediately by something that's obviously an operator:
// and := x, and = 2 (but not and += 2 since the an operand can have a unary plus/minus).
// This is done for backward compatibility. Also, it's documented that
// AND/OR/NOT aren't supported as variable names inside expressions.
is_continuation_line = true; // Override the default set earlier.
}
break;
case 'O': // "OR".
// See comments in the default section further below.
if (ctoupper(next_buf[1]) == 'R' && IS_SPACE_OR_TAB_OR_NBSP(next_buf[2])) // Relies on short-circuit boolean order.
{
cp = omit_leading_whitespace(next_buf + 2);
// v1.0.38.06: The following was fixed to use EXPR_CORE vs. EXPR_OPERAND_TERMINATORS
// to properly detect a continuation line whose first char after AND/OR is "!~*&-+()":
if (!_tcschr(EXPR_CORE, *cp)) // See comment in the "AND" case above.
is_continuation_line = true; // Override the default set earlier.
}
break;
default:
// Desired line continuation operators:
// Pretty much everything, namely:
// +, -, *, /, //, **, <<, >>, &, |, ^, <, >, <=, >=, =, ==, <>, !=, :=, +=, -=, /=, *=, ?, :
// And also the following remaining unaries (i.e. those that aren't also binaries): !, ~
// The first line below checks for ::, ++, and --. Those can't be continuation lines because:
// "::" isn't a valid operator (this also helps performance if there are many hotstrings).
// ++ and -- are ambiguous with an isolated line containing ++Var or --Var (and besides,
// wanting to use ++ to continue an expression seems extremely rare, though if there's ever
// demand for it, might be able to look at what lies to the right of the operator's operand
// -- though that would produce inconsistent continuation behavior since ++Var itself still
// could never be a continuation line due to ambiguity).
//
// The logic here isn't smart enough to differentiate between a leading ! or - that's
// meant as a continuation character and one that isn't. Even if it were, it would
// still be ambiguous in some cases because the author's intent isn't known; for example,
// the leading minus sign on the second line below is ambiguous, so will probably remain
// a continuation character in both v1 and v2:
// x := y
// -z ? a:=1 : func()
if ((*next_buf == ':' || *next_buf == '+' || *next_buf == '-') && next_buf[1] == *next_buf // See above.
// L31: '.' and '?' no longer require spaces; '.' without space is member-access (object) operator.
//|| (*next_buf == '.' || *next_buf == '?') && !IS_SPACE_OR_TAB_OR_NBSP(next_buf[1]) // The "." and "?" operators require a space or tab after them to be legitimate. For ".", this is done in case period is ever a legal character in var names, such as struct support. For "?", it's done for backward compatibility since variable names can contain question marks (though "?" by itself is not considered a variable in v1.0.46).
//&& next_buf[1] != '=' // But allow ".=" (and "?=" too for code simplicity), since ".=" is the concat-assign operator.
|| !_tcschr(CONTINUATION_LINE_SYMBOLS, *next_buf)) // Line doesn't start with a continuation char.
break; // Leave is_continuation_line set to its default of false.
// Some of the above checks must be done before the next ones.
if ( !(hotkey_flag = _tcsstr(next_buf, HOTKEY_FLAG)) ) // Without any "::", it can't be a hotkey or hotstring.
{
is_continuation_line = true; // Override the default set earlier.
break;
}
#ifndef MINIDLL
if (*next_buf == ':') // First char is ':', so it's more likely a hotstring than a hotkey.
{
// Remember that hotstrings can contain what *appear* to be quoted literal strings,
// so detecting whether a "::" is in a quoted/literal string in this case would
// be more complicated. That's one reason this other method is used.
for (hotstring_options_all_valid = true, cp = next_buf + 1; *cp && *cp != ':'; ++cp)
if (!IS_HOTSTRING_OPTION(*cp)) // Not a perfect test, but eliminates most of what little remaining ambiguity exists between ':' as a continuation character vs. ':' as the start of a hotstring. It especially eliminates the ":=" operator.
{
hotstring_options_all_valid = false;
break;
}
if (hotstring_options_all_valid && *cp == ':') // It's almost certainly a hotstring.
break; // So don't treat it as a continuation line.
//else it's not a hotstring but it might still be a hotkey such as ": & x::".
// So continue checking below.
}
#endif
// Since above didn't "break", this line isn't a hotstring but it is probably a hotkey
// because above already discovered that it contains "::" somewhere. So try to find out
// if there's anything that disqualifies this from being a hotkey, such as some
// expression line that contains a quoted/literal "::" (or a line starting with
// a comma that contains an unquoted-but-literal "::" such as for FileAppend).
if (*next_buf == ',')
{
cp = omit_leading_whitespace(next_buf + 1);
// The above has set cp to the position of the non-whitespace item to the right of
// this comma. Normal (single-colon) labels can't contain commas, so only hotkey
// labels are sources of ambiguity. In addition, normal labels and hotstrings have
// already been checked for, higher above.
#ifndef MINIDLL
if ( _tcsncmp(cp, HOTKEY_FLAG, HOTKEY_FLAG_LENGTH) // It's not a hotkey such as ",::action".
&& _tcsncmp(cp - 1, COMPOSITE_DELIMITER, COMPOSITE_DELIMITER_LENGTH) ) // ...and it's not a hotkey such as ", & y::action".
#endif
is_continuation_line = true; // Override the default set earlier.
}
else // First symbol in line isn't a comma but some other operator symbol.
{
// Check if the "::" found earlier appears to be inside a quoted/literal string.
// This check is NOT done for a line beginning with a comma since such lines
// can contain an unquoted-but-literal "::". In addition, this check is done this
// way to detect hotkeys such as the following:
// +keyname:: (and other hotkey modifier symbols such as ! and ^)
// +keyname1 & keyname2::
// +^:: (i.e. a modifier symbol followed by something that is a hotkey modifier and/or a hotkey suffix and/or an expression operator).
// <:: and &:: (i.e. hotkeys that are also expression-continuation symbols)
// By contrast, expressions that qualify as continuation lines can look like:
// . "xxx::yyy"
// + x . "xxx::yyy"
// In addition, hotkeys like the following should continue to be supported regardless
// of how things are done here:
// ^"::
// . & "::
// Finally, keep in mind that an expression-continuation line can start with two
// consecutive unary operators like !! or !*. It can also start with a double-symbol
// operator such as <=, <>, !=, &&, ||, //, **.
for (cp = next_buf; cp < hotkey_flag && *cp != '"'; ++cp);
if (cp == hotkey_flag) // No '"' found to left of "::", so this "::" appears to be a real hotkey flag rather than part of a literal string.
break; // Treat this line as a normal line vs. continuation line.
for (cp = hotkey_flag + HOTKEY_FLAG_LENGTH; *cp && *cp != '"'; ++cp);
if (*cp)
{
// Closing quote was found so "::" is probably inside a literal string of an
// expression (further checking seems unnecessary given the fairly extreme
// rarity of using '"' as a key in a hotkey definition).
is_continuation_line = true; // Override the default set earlier.
}
//else no closing '"' found, so this "::" probably belongs to something like +":: or
// . & "::. Treat this line as a normal line vs. continuation line.
}
} // switch(toupper(*next_buf))
if (is_continuation_line)
{
if (buf_length + next_buf_length >= LINE_SIZE - 1) // -1 to account for the extra space added below.
return ScriptError(ERR_CONTINUATION_SECTION_TOO_LONG, next_buf);
if (*next_buf != ',') // Insert space before expression operators so that built/combined expression works correctly (some operators like 'and', 'or', '.', and '?' currently require spaces on either side) and also for readability of ListLines.
buf[buf_length++] = ' ';
tmemcpy(buf + buf_length, next_buf, next_buf_length + 1); // Append this line to prev. and include the zero terminator.
buf_length += next_buf_length;
continue; // Check for yet more continuation lines after this one.
}
// Since above didn't continue, there is no continuation line or section. In addition,
// since this line isn't blank, no further searching is needed.
break;
} // if (!in_continuation_section)
// OTHERWISE in_continuation_section != 0, so the above has found the first line of a new
// continuation section.
continuation_line_count = 0; // Reset for this new section.
// Otherwise, parse options. First set the defaults, which can be individually overridden
// by any options actually present. RTrim defaults to ON for two reasons:
// 1) Whitespace often winds up at the end of a lines in a text editor by accident. In addition,
// whitespace at the end of any consolidated/merged line will be rtrim'd anyway, since that's
// how command parsing works.
// 2) Copy & paste from the forum and perhaps other web sites leaves a space at the end of each
// line. Although this behavior is probably site/browser-specific, it's a consideration.
do_ltrim = g_ContinuationLTrim; // Start off at global default.
do_rtrim = true; // Seems best to rtrim even if this line is a hotstring, since it is very rare that trailing spaces and tabs would ever be desirable.
// For hotstrings (which could be detected via *buf==':'), it seems best not to default the
// escape character (`) to be literal because the ability to have `t `r and `n inside the
// hotstring continuation section seems more useful/common than the ability to use the
// accent character by itself literally (which seems quite rare in most languages).
literal_escapes = false;
literal_derefs = false;
literal_delimiters = true; // This is the default even for hotstrings because although using (*buf != ':') would improve loading performance, it's not a 100% reliable way to detect hotstrings.
// The default is linefeed because:
// 1) It's the best choice for hotstrings, for which the line continuation mechanism is well suited.
// 2) It's good for FileAppend.
// 3) Minor: Saves memory in large sections by being only one character instead of two.
suffix[0] = '\n';
suffix[1] = '\0';
suffix_length = 1;
for (next_option = omit_leading_whitespace(next_buf + 1); *next_option; next_option = omit_leading_whitespace(option_end))
{
// Find the end of this option item:
if ( !(option_end = StrChrAny(next_option, _T(" \t"))) ) // Space or tab.
option_end = next_option + _tcslen(next_option); // Set to position of zero terminator instead.
// Temporarily terminate to help eliminate ambiguity for words contained inside other words,
// such as hypothetical "Checked" inside of "CheckedGray":
orig_char = *option_end;
*option_end = '\0';
if (!_tcsnicmp(next_option, _T("Join"), 4))
{
next_option += 4;
tcslcpy(suffix, next_option, _countof(suffix)); // The word "Join" by itself will product an empty string, as documented.
// Passing true for the last parameter supports `s as the special escape character,
// which allows space to be used by itself and also at the beginning or end of a string
// containing other chars.
ConvertEscapeSequences(suffix, g_EscapeChar, true);
suffix_length = _tcslen(suffix);
}
else if (!_tcsnicmp(next_option, _T("LTrim"), 5))
do_ltrim = (next_option[5] != '0'); // i.e. Only an explicit zero will turn it off.
else if (!_tcsnicmp(next_option, _T("RTrim"), 5))
do_rtrim = (next_option[5] != '0');
else
{
// Fix for v1.0.36.01: Missing "else" above, because otherwise, the option Join`r`n
// would be processed above but also be processed again below, this time seeing the
// accent and thinking it's the signal to treat accents literally for the entire
// continuation section rather than as escape characters.
// Within this terminated option substring, allow the characters to be adjacent to
// improve usability:
for (; *next_option; ++next_option)
{
switch (*next_option)
{
case '`': // Although not using g_EscapeChar (reduces code size/complexity), #EscapeChar is still supported by continuation sections; it's just that enabling the option uses '`' rather than the custom escape-char (one reason is that that custom escape-char might be ambiguous with future/past options if it's something weird like an alphabetic character).
literal_escapes = true;
break;
case '%': // Same comment as above.
literal_derefs = true;
break;
case ',': // Same comment as above.
literal_delimiters = false;
break;
case 'C': // v1.0.45.03: For simplicity, anything that begins with "C" is enough to
case 'c': // identify it as the option to allow comments in the section.
in_continuation_section = CONTINUATION_SECTION_WITH_COMMENTS; // Override the default, which is boolean true (i.e. 1).
break;
case ')':
// Probably something like (x.y)[z](), which is not intended as the beginning of
// a continuation section. Doing this only when ")" is found should remove the
// need to escape "(" in most real-world expressions while still allowing new
// options to be added later with minimal risk of breaking scripts.
in_continuation_section = 0;
*option_end = orig_char; // Undo the temporary termination.
goto process_completed_line;
}
}
}
// If the item was not handled by the above, ignore it because it is unknown.
*option_end = orig_char; // Undo the temporary termination.
} // for() each item in option list
// "has_continuation_section" indicates whether the line we're about to construct is partially
// composed of continuation lines beneath it. It's separate from continuation_line_count
// in case there is another continuation section immediately after/adjacent to the first one,
// but the second one doesn't have any lines in it:
has_continuation_section = true;
continue; // Now that the open-parenthesis of this continuation section has been processed, proceed to the next line.
} // if (!in_continuation_section)
// Since above didn't "continue", we're in the continuation section and thus next_buf contains
// either a line to be appended onto buf or the closing parenthesis of this continuation section.
if (next_buf_length == -1) // Compare directly to -1 since length is unsigned.
return ScriptError(ERR_MISSING_CLOSE_PAREN, buf);
if (next_buf_length == -2) // v1.0.45.03: Special flag that means "this is a commented-out line to be
continue; // entirely omitted from the continuation section." Compare directly to -2 since length is unsigned.
if (*next_buf == ')')
{
in_continuation_section = 0; // Facilitates back-to-back continuation sections and proper incrementing of phys_line_number.
next_buf_length = rtrim(next_buf); // Done because GetLine() wouldn't have done it due to have told it we're in a continuation section.
// Anything that lies to the right of the close-parenthesis gets appended verbatim, with
// no trimming (for flexibility) and no options-driven translation:
cp = next_buf + 1; // Use temp var cp to avoid altering next_buf (for maintainability).
--next_buf_length; // This is now the length of cp, not next_buf.
}
else
{
cp = next_buf;
// The following are done in this block only because anything that comes after the closing
// parenthesis (i.e. the block above) is exempt from translations and custom trimming.
// This means that commas are always delimiters and percent signs are always deref symbols
// in the previous block.
if (do_rtrim)
next_buf_length = rtrim(next_buf, next_buf_length);
if (do_ltrim)
next_buf_length = ltrim(next_buf, next_buf_length);
// Escape each comma and percent sign in the body of the continuation section so that
// the later parsing stages will see them as literals. Although, it's not always
// necessary to do this (e.g. commas in the last parameter of a command don't need to
// be escaped, nor do percent signs in hotstrings' auto-replace text), the settings
// are applied unconditionally because:
// 1) Determining when its safe to omit the translation would add a lot of code size and complexity.
// 2) The translation doesn't affect the functionality of the script since escaped literals
// are always de-escaped at a later stage, at least for everything that's likely to matter
// or that's reasonable to put into a continuation section (e.g. a hotstring's replacement text).
// UPDATE for v1.0.44.11: #EscapeChar, #DerefChar, #Delimiter are now supported by continuation
// sections because there were some requests for that in forum.
int replacement_count = 0;
if (literal_escapes) // literal_escapes must be done FIRST because otherwise it would also replace any accents added for literal_delimiters or literal_derefs.
{
one_char_string[0] = g_EscapeChar; // These strings were terminated earlier, so no need to
two_char_string[0] = g_EscapeChar; // do it here. In addition, these strings must be set by
two_char_string[1] = g_EscapeChar; // each iteration because the #EscapeChar (and similar directives) can occur multiple times, anywhere in the script.
replacement_count += StrReplace(next_buf, one_char_string, two_char_string, SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
}
if (literal_derefs)
{
one_char_string[0] = g_DerefChar;
two_char_string[0] = g_EscapeChar;
two_char_string[1] = g_DerefChar;
replacement_count += StrReplace(next_buf, one_char_string, two_char_string, SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
}
if (literal_delimiters)
{
one_char_string[0] = g_delimiter;
two_char_string[0] = g_EscapeChar;
two_char_string[1] = g_delimiter;
replacement_count += StrReplace(next_buf, one_char_string, two_char_string, SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
}
if (replacement_count) // Update the length if any actual replacements were done.
next_buf_length = _tcslen(next_buf);
} // Handling of a normal line within a continuation section.
// Must check the combined length only after anything that might have expanded the string above.
if (buf_length + next_buf_length + suffix_length >= LINE_SIZE)
return ScriptError(ERR_CONTINUATION_SECTION_TOO_LONG, cp);
++continuation_line_count;
// Append this continuation line onto the primary line.
// The suffix for the previous line gets written immediately prior writing this next line,
// which allows the suffix to be omitted for the final line. But if this is the first line,
// No suffix is written because there is no previous line in the continuation section.
// In addition, cp!=next_buf, this is the special line whose text occurs to the right of the
// continuation section's closing parenthesis. In this case too, the previous line doesn't
// get a suffix.
if (continuation_line_count > 1 && suffix_length && cp == next_buf)
{
tmemcpy(buf + buf_length, suffix, suffix_length + 1); // Append and include the zero terminator.
buf_length += suffix_length; // Must be done only after the old value of buf_length was used above.
}
if (next_buf_length)
{
tmemcpy(buf + buf_length, cp, next_buf_length + 1); // Append this line to prev. and include the zero terminator.
buf_length += next_buf_length; // Must be done only after the old value of buf_length was used above.
}
} // for() each sub-line (continued line) that composes this line.
process_completed_line:
// buf_length can't be -1 (though next_buf_length can) because outer loop's condition prevents it:
if (!buf_length) // Done only after the line number increments above so that the physical line number is properly tracked.
goto continue_main_loop; // In lieu of "continue", for performance.
// Since neither of the above executed, or they did but didn't "continue",
// buf now contains a non-commented line, either by itself or built from
// any continuation sections/lines that might have been present. Also note that
// by design, phys_line_number will be greater than mCombinedLineNumber whenever
// a continuation section/lines were used to build this combined line.
// If there's a previous line waiting to be processed, its fate can now be determined based on the
// nature of *this* line:
if (*pending_buf)
{
// Somewhat messy to decrement then increment later, but it's probably easier than the
// alternatives due to the use of "continue" in some places above. NOTE: phys_line_number
// would not need to be decremented+incremented even if the below resulted in a recursive
// call to us (though it doesn't currently) because line_number's only purpose is to
@@ -9652,1077 +9660,1083 @@ ResultType Script::DefineClassVars(LPTSTR aBuf, bool aStatic)
return ScriptError(ERR_OUTOFMEM);
*item_end = orig_char; // Undo termination.
}
size_t name_length = item_end - item;
// This section is very similar to the one in ParseAndAddLine() which deals with
// variable declarations, so maybe maintain them together:
item_end = omit_leading_whitespace(item_end); // Move up to the next comma, assignment-op, or '\0'.
switch (*item_end)
{
case ',': // No initializer is present for this variable, so move on to the next one.
item = omit_leading_whitespace(item_end + 1); // Set "item" for use by the next iteration.
continue; // No further processing needed below.
case '\0': // No initializer is present for this variable, so move on to the next one.
item = item_end; // Set "item" for use by the loop's condition.
continue;
case '=': // Supported for consistency with v1 syntax; to be removed in v2.
++item_end; // Point to the character after the "=".
break;
case ':':
if (item_end[1] == '=')
{
item_end += 2; // Point to the character after the ":=".
break;
}
// Otherwise, fall through to below:
default:
return ScriptError(ERR_INVALID_CLASS_VAR, item);
}
// Since above didn't "continue", this declared variable also has an initializer.
// Append the class name, ":=" and initializer to pending_buf, to be turned into
// an expression below, and executed at script start-up.
item_end = omit_leading_whitespace(item_end);
LPTSTR right_side_of_operator = item_end; // Save for use below.
item_end += FindNextDelimiter(item_end); // Find the next comma which is not part of the initializer (or find end of string).
// Append "ClassNameOrThis.VarName := Initializer, " to the buffer.
int chars_written = _sntprintf(buf + buf_used, _countof(buf) - buf_used, _T("%s.%.*s := %.*s, ")
, aStatic ? mClassName : _T("this"), name_length, item, item_end - right_side_of_operator, right_side_of_operator);
if (chars_written < 0)
return ScriptError(_T("Declaration too long.")); // Short message since should be rare.
buf_used += chars_written;
// Set "item" for use by the next iteration:
item = (*item_end == ',') // i.e. it's not the terminator and thus not the final item in the list.
? omit_leading_whitespace(item_end + 1)
: item_end; // It's the terminator, so let the loop detect that to finish.
}
if (buf_used)
{
// Above wrote at least one initializer expression into buf.
buf[buf_used -= 2] = '\0'; // Remove the final ", "
// The following section temporarily replaces mLastLine in order to insert script lines
// either at the end of the list of static initializers (separate from the main script)
// or at the end of the __Init method belonging to this class. Save the current values:
Line *script_first_line = mFirstLine, *script_last_line = mLastLine;
Line *block_end;
Func *init_func = NULL;
if (aStatic)
{
mLastLine = mLastStaticLine;
mFirstLine = mFirstStaticLine;
}
else
{
ExprTokenType token;
if (class_object->GetItem(token, _T("__Init")) && token.symbol == SYM_OBJECT
&& (init_func = dynamic_cast<Func *>(token.object))) // This cast SHOULD always succeed; done for maintainability.
{
// __Init method already exists, so find the end of its body.
for (block_end = init_func->mJumpToLine;
block_end->mActionType != ACT_BLOCK_END || !block_end->mAttribute;
block_end = block_end->mNextLine);
}
else
{
// Create an __Init method for this class.
TCHAR def[] = _T("__Init()");
if (!DefineFunc(def, NULL) || !AddLine(ACT_BLOCK_BEGIN)
|| (class_object->Base() && !ParseAndAddLine(_T("base.__Init()"), ACT_EXPRESSION))) // Initialize base-class variables first. Relies on short-circuit evaluation.
return FAIL;
mLastLine->mLineNumber = 0; // Signal the debugger to skip this line while stepping in/over/out.
init_func = g->CurrentFunc;
init_func->mDefaultVarType = VAR_DECLARE_GLOBAL; // Allow global variables/class names in initializer expressions.
if (!AddLine(ACT_BLOCK_END)) // This also resets g->CurrentFunc to NULL.
return FAIL;
block_end = mLastLine;
block_end->mLineNumber = 0; // See above.
// These must be updated as one or both have changed:
script_first_line = mFirstLine;
script_last_line = mLastLine;
}
g->CurrentFunc = init_func; // g->CurrentFunc should be NULL prior to this.
mLastLine = block_end->mPrevLine; // i.e. insert before block_end.
mLastLine->mNextLine = NULL; // For maintainability; AddLine() should overwrite it regardless.
mCurrLine = NULL; // Fix for v1.1.09.02: Leaving this non-NULL at best causes error messages to show irrelevant vicinity lines, and at worst causes a crash because the linked list is in an inconsistent state.
}
LPTSTR arg[] = { ConvertEscapeSequences(buf, g_EscapeChar, false) };
if (!AddLine(ACT_EXPRESSION, arg, UCHAR_MAX + 1)) // v1.1.17: Avoid pointing labels at this line by passing UCHAR_MAX+ for aArgc.
return FAIL; // Above already displayed the error.
if (aStatic)
{
if (!mFirstStaticLine)
mFirstStaticLine = mLastLine;
mLastStaticLine = mLastLine;
// The following is necessary if there weren't any executable lines above this static
// initializer (i.e. mFirstLine was NULL and has been set to the newly created line):
mFirstLine = script_first_line;
}
else
{
if (init_func->mJumpToLine == block_end) // This can be true only for the first initializer of a class with no base-class.
init_func->mJumpToLine = mLastLine;
// Rejoin the function's block-end (and any lines following it) to the main script.
mLastLine->mNextLine = block_end;
block_end->mPrevLine = mLastLine;
// mFirstLine should be left as it is: if it was NULL, it now contains a pointer to our
// __init function's block-begin, which is now the very first executable line in the script.
g->CurrentFunc = NULL;
}
// Restore mLastLine so that any subsequent script lines are added at the correct point.
mLastLine = script_last_line;
}
return OK;
}
Object *Script::FindClass(LPCTSTR aClassName, size_t aClassNameLength)
{
if (!aClassNameLength)
aClassNameLength = _tcslen(aClassName);
if (!aClassNameLength || aClassNameLength > MAX_CLASS_NAME_LENGTH)
return NULL;
LPTSTR cp, key;
ExprTokenType token;
Object *base_object = NULL;
TCHAR class_name[MAX_CLASS_NAME_LENGTH + 2]; // Extra +1 for '.' to simplify parsing.
// Make temporary copy which we can modify.
tmemcpy(class_name, aClassName, aClassNameLength);
class_name[aClassNameLength] = '.'; // To simplify parsing.
class_name[aClassNameLength + 1] = '\0';
// Get base variable; e.g. "MyClass" in "MyClass.MySubClass".
cp = _tcschr(class_name + 1, '.');
Var *base_var = FindVar(class_name, cp - class_name, NULL, FINDVAR_GLOBAL);
if (!base_var)
return NULL;
// Although at load time only the "Object" type can exist, dynamic_cast is used in case we're called at run-time:
if ( !(base_var->IsObject() && (base_object = dynamic_cast<Object *>(base_var->Object()))) )
return NULL;
// Even if the loop below has no iterations, it initializes 'key' to the appropriate value:
for (key = cp + 1; cp = _tcschr(key, '.'); key = cp + 1) // For each key in something like TypeVar.Key1.Key2.
{
if (cp == key)
return NULL; // ScriptError(_T("Missing name."), cp);
*cp = '\0'; // Terminate at the delimiting dot.
if (!base_object->GetItem(token, key))
return NULL;
base_object = (Object *)token.object; // See comment about Object() above.
}
return base_object;
}
Object *Object::GetUnresolvedClass(LPTSTR &aName)
// This method is only valid for mUnresolvedClass.
{
if (!mFieldCount)
return NULL;
aName = mFields[0].key.s;
return (Object *)mFields[0].object;
}
ResultType Script::ResolveClasses()
{
LPTSTR name;
Object *base = mUnresolvedClasses->GetUnresolvedClass(name);
if (!base)
return OK;
// There is at least one unresolved class.
ExprTokenType token;
if (base->GetItem(token, _T("__Class")))
{
// In this case (an object in the mUnresolvedClasses list), it is always an integer
// containing the file index and line number:
mCurrFileIndex = int(token.value_int64 >> 32);
mCombinedLineNumber = LineNumberType(token.value_int64);
}
mCurrLine = NULL;
return ScriptError(_T("Unknown class."), name);
}
#ifndef AUTOHOTKEYSC
struct FuncLibrary
{
LPTSTR path;
DWORD_PTR length;
};
Func *Script::FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool &aErrorWasShown, bool &aFileWasFound, bool aIsAutoInclude)
// Caller must ensure that aFuncName doesn't already exist as a defined function.
// If aFuncNameLength is 0, the entire length of aFuncName is used.
{
aErrorWasShown = false; // Set default for this output parameter.
aFileWasFound = false;
int i;
LPTSTR char_after_last_backslash, terminate_here;
TCHAR buf[MAX_PATH+1];
DWORD attr;
TextMem tmem;
TextMem::Buffer textbuf(NULL, 0, false);
#define FUNC_LIB_EXT _T(".ahk")
#define FUNC_LIB_EXT_LENGTH (_countof(FUNC_LIB_EXT) - 1)
#define FUNC_LOCAL_LIB _T("\\Lib\\") // Needs leading and trailing backslash.
#define FUNC_LOCAL_LIB_LENGTH (_countof(FUNC_LOCAL_LIB) - 1)
#define FUNC_USER_LIB _T("\\AutoHotkey\\Lib\\") // Needs leading and trailing backslash.
#define FUNC_USER_LIB_LENGTH (_countof(FUNC_USER_LIB) - 1)
#define FUNC_STD_LIB _T("Lib\\") // Needs trailing but not leading backslash.
#define FUNC_STD_LIB_LENGTH (_countof(FUNC_STD_LIB) - 1)
#define FUNC_LIB_COUNT 4
static FuncLibrary sLib[FUNC_LIB_COUNT] = {0};
static LPTSTR winapi;
if (!sLib[0].path) // Allocate & discover paths only upon first use because many scripts won't use anything from the library. This saves a bit of memory and performance.
{
LPVOID aDataBuf;
HRSRC hResInfo = FindResource(g_hInstance, _T("WINAPI"), MAKEINTRESOURCE(10));
DecompressBuffer(LockResource(LoadResource(g_hInstance, hResInfo)), aDataBuf, g_default_pwd);
#ifdef _UNICODE
winapi = UTF8ToWide((LPCSTR)aDataBuf);
#else
winapi = (LPTSTR)aDataBuf;
#endif
for (i = 0; i < FUNC_LIB_COUNT; ++i)
#ifdef _USRDLL
if ( !(sLib[i].path = tmalloc(MAX_PATH)) ) // When dll script is restarted, SimpleHeap is deleted and we don't want to delete static memberst
#else
if ( !(sLib[i].path = (LPTSTR) SimpleHeap::Malloc(MAX_PATH * sizeof(TCHAR))) ) // Need MAX_PATH for to allow room for appending each candidate file/function name.
#endif
return NULL; // Due to rarity, simply pass the failure back to caller.
FuncLibrary *this_lib;
// DETERMINE PATH TO "LOCAL" LIBRARY:
this_lib = sLib; // For convenience and maintainability.
this_lib->length = BIV_ScriptDir(NULL, _T(""));
if (this_lib->length < MAX_PATH-FUNC_LOCAL_LIB_LENGTH)
{
this_lib->length = BIV_ScriptDir(this_lib->path, _T(""));
_tcscpy(this_lib->path + this_lib->length, FUNC_LOCAL_LIB);
this_lib->length += FUNC_LOCAL_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "USER" LIBRARY:
this_lib++; // For convenience and maintainability.
this_lib->length = BIV_MyDocuments(this_lib->path, _T(""));
if (this_lib->length < MAX_PATH-FUNC_USER_LIB_LENGTH)
{
_tcscpy(this_lib->path + this_lib->length, FUNC_USER_LIB);
this_lib->length += FUNC_USER_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "STANDARD" LIBRARY:
this_lib++; // For convenience and maintainability.
GetModuleFileName(NULL, this_lib->path, MAX_PATH); // The full path to the currently-running AutoHotkey.exe.
char_after_last_backslash = 1 + _tcsrchr(this_lib->path, '\\'); // Should always be found, so failure isn't checked.
this_lib->length = (DWORD)(char_after_last_backslash - this_lib->path); // The length up to and including the last backslash.
if (this_lib->length < MAX_PATH-FUNC_STD_LIB_LENGTH)
{
_tcscpy(this_lib->path + this_lib->length, FUNC_STD_LIB);
this_lib->length += FUNC_STD_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "AHKPATH\Lib.lnk" LIBRARY:
this_lib++; // For convenience and maintainability.
BIV_AhkPath(this_lib->path, _T(""));
_tcscpy(_tcsrchr(this_lib->path,'\\')+1,_T("Lib.lnk"));
*(_tcsrchr(this_lib->path,'\\')+8) = '\0';
CoInitialize(NULL);
IShellLink *psl;
if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *)&psl)))
{
IPersistFile *ppf;
if (SUCCEEDED(psl->QueryInterface(IID_IPersistFile, (LPVOID *)&ppf)))
{
#ifdef UNICODE
if (SUCCEEDED(ppf->Load(this_lib->path, 0)))
#else
WCHAR wsz[MAX_PATH+1]; // +1 hasn't been explained, but is retained in case it's needed.
ToWideChar(this_lib->path, wsz, MAX_PATH+1); // Dest. size is in wchars, not bytes.
if (SUCCEEDED(ppf->Load((const WCHAR*)wsz, 0)))
#endif
{
TCHAR buf[MAX_PATH+1];
psl->GetPath(buf, MAX_PATH, NULL, SLGP_UNCPRIORITY);
_tcscpy(this_lib->path,buf);
_tcscpy(this_lib->path + _tcslen(buf),_T("\\\0"));
}
ppf->Release();
}
psl->Release();
}
CoUninitialize();
if ( !_tcsrchr(FileAttribToStr(buf, GetFileAttributes(this_lib->path)),'D') )
{
this_lib->length = 0;
*this_lib->path = '\0';
}
else
this_lib->length = _tcslen(this_lib->path);
for (i = 0; i < FUNC_LIB_COUNT; ++i)
{
attr = GetFileAttributes(sLib[i].path); // Seems to accept directories that have a trailing backslash, which is good because it simplifies the code.
if (attr == 0xFFFFFFFF || !(attr & FILE_ATTRIBUTE_DIRECTORY)) // Directory doesn't exist or it's a file vs. directory. Relies on short-circuit boolean order.
{
*sLib[i].path = '\0'; // Mark this library as disabled.
sLib[i].length = 0; //
}
}
}
// Above must ensure that all sLib[].path elements are non-NULL (but they can be "" to indicate "no library").
if (!aFuncNameLength) // Caller didn't specify, so use the entire string.
aFuncNameLength = _tcslen(aFuncName);
TCHAR *dest, *first_underscore, class_name_buf[MAX_VAR_NAME_LENGTH + 1];
LPTSTR naked_filename = aFuncName; // Set up for the first iteration.
size_t naked_filename_length = aFuncNameLength; //
for (int second_iteration = 0; second_iteration < 2; ++second_iteration)
{
for (i = 0; i < FUNC_LIB_COUNT; ++i)
{
if (!*sLib[i].path) // Library is marked disabled, so skip it.
continue;
if (sLib[i].length + naked_filename_length >= MAX_PATH-FUNC_LIB_EXT_LENGTH)
continue; // Path too long to match in this library, but try others.
dest = (LPTSTR) tmemcpy(sLib[i].path + sLib[i].length, naked_filename, naked_filename_length); // Append the filename to the library path.
_tcscpy(dest + naked_filename_length, FUNC_LIB_EXT); // Append the file extension.
attr = GetFileAttributes(sLib[i].path); // Testing confirms that GetFileAttributes() doesn't support wildcards; which is good because we want filenames containing question marks to be "not found" rather than being treated as a match-pattern.
if (attr == 0xFFFFFFFF || (attr & FILE_ATTRIBUTE_DIRECTORY)) // File doesn't exist or it's a directory. Relies on short-circuit boolean order.
continue;
aFileWasFound = true; // Indicate success for #include <lib>, which doesn't necessarily expect a function to be found.
// Since above didn't "continue", a file exists whose name matches that of the requested function.
// Before loading/including that file, set the working directory to its folder so that if it uses
// #Include, it will be able to use more convenient/intuitive relative paths. This is similar to
// the "#Include DirName" feature.
// Call SetWorkingDir() vs. SetCurrentDirectory() so that it succeeds even for a root drive like
// C: that lacks a backslash (see SetWorkingDir() for details).
terminate_here = sLib[i].path + sLib[i].length - 1; // The trailing backslash in the full-path-name to this library.
*terminate_here = '\0'; // Temporarily terminate it for use with SetWorkingDir().
SetWorkingDir(sLib[i].path); // See similar section in the #Include directive.
*terminate_here = '\\'; // Undo the termination.
if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude)
{
// For each auto-included library-file, write out two #Include lines:
// 1) Use #Include in its "change working directory" mode so that any explicit #include directives
// or FileInstalls inside the library file itself will work consistently and properly.
// 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include
// the library file itself.
// We don't directly append library files onto the main script here because:
// 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files
// might contain #Include even though it's rare).
// 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or
// subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they
// wouldn't be properly interleaved/asynchronous, but instead brought out of their library file
// and deposited separately/synchronously into the temp-include file by some new logic at the
// AutoHotkey.exe's code for the #Include directive.
// 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts.
mIncludeLibraryFunctionsThenExit->Format(_T("#Include %-0.*s\n#IncludeAgain %s\n")
, sLib[i].length, sLib[i].path, sLib[i].path);
// Now continue on normally so that our caller can continue looking for syntax errors.
}
// g->CurrentFunc is non-NULL when the function-call being resolved is inside
// a function. Save and reset it for correct behaviour in the include file:
Func *current_func = g->CurrentFunc;
g->CurrentFunc = NULL;
// Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the
// above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written.
if (!LoadIncludedFile(sLib[i].path, false, false)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included).
{
g->CurrentFunc = current_func; // Restore.
aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier.
return NULL;
}
g->CurrentFunc = current_func; // Restore.
// Now that a matching filename has been found, it seems best to stop searching here even if that
// file doesn't actually contain the requested function. This helps library authors catch bugs/typos.
// HotKeyIt, override so resource can be tried too
if (current_func = FindFunc(aFuncName, aFuncNameLength))
return current_func;
continue;
} // for() each library directory.
// Now that the first iteration is done, set up for the second one that searches by class/prefix.
// Notes about ambiguity and naming collisions:
// By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a
// match in a filename that isn't really a class, it seems inconsequential because at worst it will
// still not find the function and will then say "call to nonexistent function". In addition, the
// ability to customize which libraries are searched is planned. This would allow a publicly
// distributed script to turn off all libraries except stdlib.
if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed.
break; // All loops are done because second iteration is the last possible attempt.
naked_filename_length = first_underscore - aFuncName;
if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently).
break; // All loops are done because second iteration is the last possible attempt.
naked_filename = class_name_buf; // Point it to a buffer for use below.
tmemcpy(naked_filename, aFuncName, naked_filename_length);
naked_filename[naked_filename_length] = '\0';
} // 2-iteration for().
// HotKeyIt find library in Resource
// Since above didn't return, no match found in any library.
// Search in Resource for a library
//
// If using dll, first try find function in dll resource, then function + underscore (function_) in dll resource
// If nothing in dll resource is found, search again in main executable.
tmemcpy(class_name_buf, aFuncName, aFuncNameLength);
tmemcpy(class_name_buf + aFuncNameLength,_T(".ahk"),4);
class_name_buf[aFuncNameLength + 4] = '\0';
HRSRC lib_hResource;
BOOL aUseHinstance = true;
if (!(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB"))))
{
// Now that the resource is not found, set up for the second one that searches by class/prefix.
// Notes about ambiguity and naming collisions:
// By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a
// match in a filename that isn't really a class, it seems inconsequential because at worst it will
// still not find the function and will then say "call to nonexistent function". In addition, the
// ability to customize which libraries are searched is planned. This would allow a publicly
// distributed script to turn off all libraries except stdlib.
aUseHinstance = false;
if ( !(lib_hResource = FindResource(NULL, class_name_buf, _T("LIB"))) )
{
if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed.
goto winapi;
else
{
naked_filename_length = first_underscore - aFuncName;
if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently).
goto winapi;
tmemcpy(class_name_buf, aFuncName, naked_filename_length);
tmemcpy(class_name_buf + naked_filename_length,_T(".ahk"),4);
class_name_buf[naked_filename_length + 4] = '\0';
if ( !(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB"))) )
{
if ( !(lib_hResource = FindResource(NULL, class_name_buf, _T("LIB"))) )
goto winapi;
}
else
aUseHinstance = true;
}
}
}
// Now a resouce was found and it can be loaded
HGLOBAL hResData;
HINSTANCE ahInstance = aUseHinstance ? g_hInstance : NULL;
if ( !( (textbuf.mLength = SizeofResource(ahInstance, lib_hResource))
&& (hResData = LoadResource(ahInstance, lib_hResource))
&& (textbuf.mBuffer = LockResource(hResData)) ) )
{ // aErrorWasShown = true; // Do not display errors here
goto winapi;
}
+ DWORD aSizeDeCompressed = 0;
if (*(unsigned int*)textbuf.mBuffer == 0x04034b50)
{
LPVOID aDataBuf;
- DWORD aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf);
+ aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf);
if (aSizeDeCompressed)
{
LPVOID buff = _alloca(aSizeDeCompressed); // will be freed when function returns
memmove(buff,aDataBuf,aSizeDeCompressed);
+ SecureZeroMemory(aDataBuf, aSizeDeCompressed);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
textbuf.mLength = aSizeDeCompressed;
textbuf.mBuffer = buff;
}
}
aFileWasFound = true;
// NOTE: Ahk2Exe strips off the UTF-8 BOM.
- LPTSTR resource_script = (LPTSTR)_alloca(textbuf.mLength * sizeof(TCHAR));
+ LPTSTR resource_script = (LPTSTR)_alloca(textbuf.mLength);
tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF8);
+ if (aSizeDeCompressed)
+ SecureZeroMemory(textbuf.mBuffer, textbuf.mLength);
tmem.Read(resource_script, textbuf.mLength);
if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude)
{
// For each auto-included library-file, write out two #Include lines:
// 1) Use #Include in its "change working directory" mode so that any explicit #include directives
// or FileInstalls inside the library file itself will work consistently and properly.
// 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include
// the library file itself.
// We don't directly append library files onto the main script here because:
// 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files
// might contain #Include even though it's rare).
// 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or
// subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they
// wouldn't be properly interleaved/asynchronous, but instead brought out of their library file
// and deposited separately/synchronously into the temp-include file by some new logic at the
// AutoHotkey.exe's code for the #Include directive.
// 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts.
mIncludeLibraryFunctionsThenExit->Format(_T("%*s\n")
, (DWORD_PTR)_tcslen(resource_script), resource_script);
// Now continue on normally so that our caller can continue looking for syntax errors.
}
// g->CurrentFunc is non-NULL when the function-call being resolved is inside
// a function. Save and reset it for correct behaviour in the include file:
Func *current_func = g->CurrentFunc;
g->CurrentFunc = NULL;
// Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the
// above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written.
if (!LoadIncludedText(resource_script, class_name_buf)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included).
{
+ SecureZeroMemory(resource_script, textbuf.mLength);
g->CurrentFunc = current_func; // Restore.
aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier.
return NULL;
}
-
+
+ SecureZeroMemory(resource_script, textbuf.mLength);
g->CurrentFunc = current_func; // Restore.
return FindFunc(aFuncName, aFuncNameLength);
winapi:
TCHAR parameter[1024] = { L'#', L'D', L'l', L'l', L'I', L'm', L'p', L'o', L'r', L't', L'\\' };
memmove(¶meter[11], aFuncName, aFuncNameLength*sizeof(TCHAR));
parameter[aFuncNameLength + 11] = L',';
parameter[aFuncNameLength + 12] = '\0';
LPTSTR found;
if (found = _tcsstr(winapi, (LPTSTR)¶meter[10]))
{
parameter[10] = L',';
LPTSTR aDest = (LPTSTR)¶meter[aFuncNameLength + 12];
LPTSTR aDllName = _tcsstr(found, _T("\t")) + 1;
size_t aNameLen = _tcsstr(aDllName, _T("\\")) - aDllName + 1;
_tcsncpy(aDest, aDllName, aNameLen);
aDest = aDest + aNameLen;
_tcsncpy(aDest, found + 1, aFuncNameLength + 1);
// Override _ in the end of definition (ahk function like SendMessage, Sleep, Send, SendInput ...
if (*(aFuncName + aFuncNameLength - 1) == '_')
{
*(aDest + aFuncNameLength - 1) = ',';
*(aDest + aFuncNameLength) = '\0';
aDest = aDest + aFuncNameLength;
}
else
{
aDest = aDest + aFuncNameLength + 1;
}
for (found = _tcsstr(found, _T(",")) + 1; *found != L'\\'; found++)
{
if (*found == L'U' || *found == L'u')
{
*aDest = L'U';
aDest++;
continue;
}
else if (*found == L'z' || *found == L'Z')
{
#ifdef _UNICODE
_tcscpy(aDest, _T("USHORT"));
aDest = aDest + 6;
#else
_tcscpy(aDest, _T("UCHAR"));
aDest = aDest + 5;
#endif
}
else if (*found == L's' || *found == L'S')
{
_tcscpy(aDest, _T("STR"));
aDest = aDest + 3;
}
else if (*found == L't' || *found == L't')
{
_tcscpy(aDest, _T("PTR"));
aDest = aDest + 3;
}
else if (*found == L'a' || *found == L'A')
{
_tcscpy(aDest, _T("ASTR"));
aDest = aDest + 4;
}
else if (*found == L'w' || *found == L'W')
{
_tcscpy(aDest, _T("WSTR"));
aDest = aDest + 4;
}
else if (*found == L'x' || *found == L'X') //TCHAR
{
#ifdef _UNICODE
_tcscpy(aDest, _T("USHORT"));
aDest = aDest + 6;
#else
_tcscpy(aDest, _T("UCHAR"));
aDest = aDest + 5;
#endif
}
else if ((*found == L'i' || *found == L'I') && *(found + 1) == L'6')
{
_tcscpy(aDest, _T("INT64"));
aDest = aDest + 5;
found++;
}
else if (*found == L'i' || *found == L'I')
{
if (*(found + 1) != L'\\' || *(aDest - 1) == 'u' || *(aDest - 1) == 'U')
{ // Not default return type int, no need to define
_tcscpy(aDest, _T("INT"));
aDest = aDest + 3;
}
else // remove last , since no return type is given
{
aDest--;
}
}
else if (*found == L'h' || *found == L'H')
{
_tcscpy(aDest, _T("SHORT"));
aDest = aDest + 5;
}
else if (*found == L'c' || *found == L'C')
{
_tcscpy(aDest, _T("CHAR"));
aDest = aDest + 4;
}
else if (*found == L'f' || *found == L'F')
{
_tcscpy(aDest, _T("FLOAT"));
aDest = aDest + 5;
}
else if (*found == L'd' || *found == L'D')
{
_tcscpy(aDest, _T("DOUBLE"));
aDest = aDest + 6;
}
if (*(found + 1) == L'*' || *(found + 1) == L'p' || *(found + 1) == L'P')
{
*aDest = *found;
aDest++;
}
_tcscpy(aDest, _T(",,"));
aDest = aDest + 2;
}
*(aDest - 2) = L'\0';
if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude)
{
// For each auto-included library-file, write out two #Include lines:
// 1) Use #Include in its "change working directory" mode so that any explicit #include directives
// or FileInstalls inside the library file itself will work consistently and properly.
// 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include
// the library file itself.
// We don't directly append library files onto the main script here because:
// 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files
// might contain #Include even though it's rare).
// 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or
// subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they
// wouldn't be properly interleaved/asynchronous, but instead brought out of their library file
// and deposited separately/synchronously into the temp-include file by some new logic at the
// AutoHotkey.exe's code for the #Include directive.
// 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts.
mIncludeLibraryFunctionsThenExit->Format(_T("%*s\n")
, _tcslen(parameter), parameter);
// Now continue on normally so that our caller can continue looking for syntax errors.
}
LoadDllFunction(_tcschr(parameter, L',') + 1, parameter);
return FindFunc(aFuncName, aFuncNameLength);
}
return NULL;
}
#endif
Func *Script::FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength, int *apInsertPos) // L27: Added apInsertPos for binary-search.
// Returns the Function whose name matches aFuncName (which caller has ensured isn't NULL).
// If it doesn't exist, NULL is returned.
{
if (!aFuncNameLength) // Caller didn't specify, so use the entire string.
aFuncNameLength = _tcslen(aFuncName);
if (apInsertPos) // L27: Set default for maintainability.
*apInsertPos = -1;
// For the below, no error is reported because callers don't want that. Instead, simply return
// NULL to indicate that names that are illegal or too long are not found. If the caller later
// tries to add the function, it will get an error then:
if (aFuncNameLength > MAX_VAR_NAME_LENGTH)
return NULL;
// The following copy is made because it allows the name searching to use _tcsicmp() instead of
// strlicmp(), which close to doubles the performance. The copy includes only the first aVarNameLength
// characters from aVarName:
TCHAR func_name[MAX_VAR_NAME_LENGTH + 1];
tcslcpy(func_name, aFuncName, aFuncNameLength + 1); // +1 to convert length to size.
Func *pfunc;
// Using a binary searchable array vs a linked list speeds up dynamic function calls, on average.
int left, right, mid, result;
for (left = 0, right = mFuncCount - 1; left <= right;)
{
mid = (left + right) / 2;
result = _tcsicmp(func_name, mFunc[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance.
if (result > 0)
left = mid + 1;
else if (result < 0)
right = mid - 1;
else // Match found.
return mFunc[mid];
}
if (apInsertPos)
*apInsertPos = left;
// Since above didn't return, there is no match. See if it's a built-in function that hasn't yet
// been added to the function list.
// Set defaults to be possibly overridden below:
int min_params = 1;
int max_params = 1;
BuiltInFunctionType bif;
LPTSTR suffix = func_name + 3;
#ifndef MINIDLL
if (!_tcsnicmp(func_name, _T("LV_"), 3)) // As a built-in function, LV_* can only be a ListView function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("GetNext")))
{
bif = BIF_LV_GetNextOrCount;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("GetCount")))
{
bif = BIF_LV_GetNextOrCount;
min_params = 0; // But leave max at its default of 1.
}
else if (!_tcsicmp(suffix, _T("GetText")))
{
bif = BIF_LV_GetText;
min_params = 2;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_LV_AddInsertModify;
min_params = 0; // 0 params means append a blank row.
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Insert")))
{
bif = BIF_LV_AddInsertModify;
// Leave min_params at 1. Passing only 1 param to it means "insert a blank row".
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Modify")))
{
bif = BIF_LV_AddInsertModify; // Although it shares the same function with "Insert", it can still have its own min/max params.
min_params = 2;
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Delete")))
{
bif = BIF_LV_Delete;
min_params = 0; // Leave max at its default of 1.
}
else if (!_tcsicmp(suffix, _T("InsertCol")))
{
bif = BIF_LV_InsertModifyDeleteCol;
// Leave min_params at 1 because inserting a blank column ahead of the first column
// does not seem useful enough to sacrifice the no-parameter mode, which might have
// potential future uses.
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("ModifyCol")))
{
bif = BIF_LV_InsertModifyDeleteCol;
min_params = 0;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("DeleteCol")))
bif = BIF_LV_InsertModifyDeleteCol; // Leave min/max set to 1.
else if (!_tcsicmp(suffix, _T("SetImageList")))
{
bif = BIF_LV_SetImageList;
max_params = 2; // Leave min at 1.
}
else
return NULL;
}
else if (!_tcsnicmp(func_name, _T("TV_"), 3)) // As a built-in function, TV_* can only be a TreeView function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_TV_AddModifyDelete;
max_params = 3; // Leave min at its default of 1.
}
else if (!_tcsicmp(suffix, _T("Modify")))
{
bif = BIF_TV_AddModifyDelete;
max_params = 3; // One-parameter mode is "select specified item".
}
else if (!_tcsicmp(suffix, _T("Delete")))
{
bif = BIF_TV_AddModifyDelete;
min_params = 0;
}
else if (!_tcsicmp(suffix, _T("GetParent")) || !_tcsicmp(suffix, _T("GetChild")) || !_tcsicmp(suffix, _T("GetPrev")))
bif = BIF_TV_GetRelatedItem;
else if (!_tcsicmp(suffix, _T("GetCount")) || !_tcsicmp(suffix, _T("GetSelection")))
{
bif = BIF_TV_GetRelatedItem;
min_params = 0;
max_params = 0;
}
else if (!_tcsicmp(suffix, _T("GetNext"))) // Unlike "Prev", Next also supports 0 or 2 parameters.
{
bif = BIF_TV_GetRelatedItem;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("Get")) || !_tcsicmp(suffix, _T("GetText")))
{
bif = BIF_TV_Get;
min_params = 2;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("SetImageList")))
{
bif = BIF_TV_SetImageList;
max_params = 2; // Leave min at 1.
}
else
return NULL;
}
else if (!_tcsnicmp(func_name, _T("IL_"), 3)) // It's an ImageList function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("Create")))
{
bif = BIF_IL_Create;
min_params = 0;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("Destroy")))
{
bif = BIF_IL_Destroy; // Leave Min/Max set to 1.
}
else if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_IL_Add;
min_params = 2;
max_params = 4;
}
else
return NULL;
}
else if (!_tcsicmp(func_name, _T("SB_SetText")))
{
bif = BIF_StatusBar;
max_params = 3; // Leave min_params at its default of 1.
}
else if (!_tcsicmp(func_name, _T("SB_SetParts")))
{
bif = BIF_StatusBar;
min_params = 0;
max_params = 255; // 255 params allows for up to 256 parts, which is SB's max.
}
else if (!_tcsicmp(func_name, _T("SB_SetIcon")))
{
bif = BIF_StatusBar;
max_params = 3; // Leave min_params at its default of 1.
}
else if (!_tcsicmp(func_name, _T("StrLen")))
#else
if (!_tcsicmp(func_name, _T("StrLen")))
#endif
bif = BIF_StrLen;
else if (!_tcsicmp(func_name, _T("SubStr")))
{
bif = BIF_SubStr;
min_params = 2;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("Struct")))
{
bif = BIF_Struct;
min_params = 1;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("Sizeof")))
{
bif = BIF_sizeof;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("CriticalObject")))
{
bif = BIF_CriticalObject;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("Lock")))
{
bif = BIF_Lock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("TryLock")))
{
bif = BIF_TryLock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("UnLock")))
{
bif = BIF_UnLock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("FindFunc"))) // addFile() Naveen v8.
{
bif = BIF_FindFunc;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("FindLabel"))) // HotKeyIt v1.1.02.00
{
bif = BIF_FindLabel;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("Alias"))) // lowlevel() Naveen v9.
{
bif = BIF_Alias;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("UnZipRawMemory"))) // lowlevel() Naveen v9.
{
bif = BIF_UnZipRawMemory;
min_params = 1;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("getTokenValue"))) // lowlevel() Naveen v9.
{
bif = BIF_getTokenValue;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("CacheEnable"))) // lowlevel() Naveen v9.
{
bif = BIF_CacheEnable;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("Getvar"))) // lowlevel() Naveen v9.
{
bif = BIF_Getvar;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("Trim")) || !_tcsicmp(func_name, _T("LTrim")) || !_tcsicmp(func_name, _T("RTrim"))) // L31
{
bif = BIF_Trim;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("InStr")))
{
bif = BIF_InStr;
min_params = 2;
max_params = 5;
}
else if (!_tcsicmp(func_name, _T("RegExMatch")))
{
bif = BIF_RegEx;
min_params = 2;
max_params = 4;
}
else if (!_tcsicmp(func_name, _T("RegExReplace")))
{
bif = BIF_RegEx;
min_params = 2;
max_params = 6;
}
else if (!_tcsicmp(func_name, _T("StrSplit")))
{
bif = BIF_StrSplit;
min_params = 1;
max_params = 3;
}
else if (!_tcsnicmp(func_name, _T("GetKey"), 6))
{
suffix = func_name + 6;
if (!_tcsicmp(suffix, _T("State")))
{
bif = BIF_GetKeyState;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("Name")) || !_tcsicmp(suffix, _T("VK")) || !_tcsicmp(suffix, _T("SC")))
bif = BIF_GetKeyName;
else
return NULL;
}
else if (!_tcsicmp(func_name, _T("Asc")))
bif = BIF_Asc;
else if (!_tcsicmp(func_name, _T("Chr")))
bif = BIF_Chr;
else if (!_tcsicmp(func_name, _T("Format")))
{
bif = BIF_Format;
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(func_name, _T("StrGet")))
{
bif = BIF_StrGetPut;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("StrPut")))
{
bif = BIF_StrGetPut;
max_params = 4;
}
else if (!_tcsicmp(func_name, _T("NumGet")))
{
bif = BIF_NumGet;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("NumPut")))
{
bif = BIF_NumPut;
diff --git a/source/script2.cpp b/source/script2.cpp
index 039d714..4aa3551 100644
--- a/source/script2.cpp
+++ b/source/script2.cpp
@@ -17326,1190 +17326,1192 @@ BIF_DECL(BIF_StrGetPut)
{
if (TokenIsPureNumeric(**aParam))
{
length = (int)TokenToInt64(**aParam);
if (length < -1 || !length)
return; // Invalid length; or caller of StrGet asked for 0 chars.
++aParam; // Let encoding be the next param, if present.
}
else if ((*aParam)->symbol == SYM_MISSING)
{
// Length was "explicitly omitted", as in StrGet(Address,, Encoding),
// which allows Encoding to be an integer without specifying Length.
++aParam;
}
// aParam now points to aParam_end or the Encoding param.
}
if (aParam < aParam_end)
{
if (!TokenIsPureNumeric(**aParam))
{
encoding = Line::ConvertFileEncoding(TokenToString(**aParam));
if (encoding == -1)
return; // Invalid param.
}
else encoding = (UINT)TokenToInt64(**aParam);
}
}
// Note: CP_AHKNOBOM is not supported; "-RAW" must be omitted.
// Check for obvious errors to prevent an Access Violation.
// Address can be zero for StrPut if length is also zero (see below).
if ( address < FIRST_VALID_ADDRESS
// Also check for overlap, in case memcpy is used instead of MultiByteToWideChar/WideCharToMultiByte.
// (Behaviour for memcpy would be "undefined", whereas MBTWC/WCTBM would fail.) Overlap in the
// other direction (source_string beginning inside address..length) should not be possible.
|| (address >= source_string && address <= ((LPTSTR)source_string + source_length)) )
return;
if (source_string) // StrPut
{
int char_count; // Either bytes or characters, depending on the target encoding.
aResultToken.symbol = SYM_INTEGER; // All paths below return an integer.
if (!source_length)
{ // Take a shortcut when source_string is empty, since some paths below might not handle it correctly.
if (length) {
if (encoding == CP_UTF16)
*(LPWSTR)address = '\0';
else
*(LPSTR)address = '\0';
}
aResultToken.value_int64 = 1;
return;
}
if (encoding == UorA(CP_UTF16, CP_ACP))
{
// No conversion required: target encoding is the same as the native encoding of this build.
char_count = source_length + 1; // + 1 because generally a null-terminator is wanted.
if (length)
{
// Check for sufficient buffer space. Cast to UINT and compare unsigned values: if length is
// -1 it should be interpreted as a very large unsigned value, in effect bypassing this check.
if ((UINT)source_length <= (UINT)length)
{
if (source_length == length)
// Exceptional case: caller doesn't want a null-terminator (or passed this length in error).
--char_count;
// Copy the string, including null-terminator if requested.
tmemcpy((LPTSTR)address, (LPCTSTR)source_string, char_count);
}
else
// For consistency with the sections below, don't truncate the string.
char_count = 0;
}
//else: Caller just wants the the required buffer size (char_count), which will be returned below.
// Note that although this seems equivalent to StrLen(), the caller might have explicitly
// passed an Encoding; in that case, the result of StrLen() might be different on the
// opposite build (ANSI vs Unicode) as the section below would be executed instead of this one.
}
else
{
// Conversion is required. For Unicode builds, this means encoding != CP_UTF16;
#ifndef UNICODE // therefore, this section is relevant only to ANSI builds:
if (encoding == CP_UTF16)
{
// See similar section below for comments.
if (length <= 0)
{
char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, NULL, 0) + 1;
if (length == 0)
{
aResultToken.value_int64 = char_count;
return;
}
length = char_count;
}
char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, (LPWSTR)address, length);
if (char_count && char_count < length)
((LPWSTR)address)[char_count++] = '\0';
}
else // encoding != CP_UTF16
{
// Convert native ANSI string to UTF-16 first.
CStringWCharFromChar wide_buf((LPCSTR)source_string, source_length, CP_ACP);
source_string = wide_buf.GetString();
source_length = wide_buf.GetLength();
#endif
// UTF-8 does not support this flag. Although the check further below would probably
// compensate for this, UTF-8 is probably common enough to leave this exception here.
DWORD flags = (encoding == CP_UTF8) ? 0 : WC_NO_BEST_FIT_CHARS;
if (length <= 0) // -1 or 0
{
// Determine required buffer size.
char_count = WideCharToMultiByte(encoding, flags, (LPCWSTR)source_string, source_length, NULL, 0, NULL, NULL);
if (!char_count) // Above has ensured source is not empty, so this must be an error.
{
if (GetLastError() == ERROR_INVALID_FLAGS)
{
// Try again without flags. MSDN lists a number of code pages for which flags must be 0, including UTF-7 and UTF-8 (but UTF-8 is handled above).
flags = 0; // Must be set for this call and the call further below.
char_count = WideCharToMultiByte(encoding, flags, (LPCWSTR)source_string, source_length, NULL, 0, NULL, NULL);
}
if (!char_count)
{
aResultToken.symbol = SYM_STRING;
// aResultToken.marker is already set to "".
return;
}
}
++char_count; // + 1 for null-terminator (source_length causes it to be excluded from char_count).
if (length == 0) // Caller just wants the required buffer size.
{
aResultToken.value_int64 = char_count;
return;
}
// Assume there is sufficient buffer space and hope for the best:
length = char_count;
}
// Convert to target encoding.
char_count = WideCharToMultiByte(encoding, flags, (LPCWSTR)source_string, source_length, (LPSTR)address, length, NULL, NULL);
// Since above did not null-terminate, check for buffer space and null-terminate if there's room.
// It is tempting to always null-terminate (potentially replacing the last byte of data),
// but that would exclude this function as a means to copy a string into a fixed-length array.
if (char_count && char_count < length)
((LPSTR)address)[char_count++] = '\0';
// else no space to null-terminate; or conversion failed.
#ifndef UNICODE
}
#endif
}
// Return the number of characters copied.
aResultToken.value_int64 = char_count;
}
else // StrGet
{
if (encoding != UorA(CP_UTF16, CP_ACP))
{
// Conversion is required.
int conv_length;
#ifdef UNICODE
// Convert multi-byte encoded string to UTF-16.
conv_length = MultiByteToWideChar(encoding, 0, (LPCSTR)address, length, NULL, 0);
if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator.
return; // Out of memory.
conv_length = MultiByteToWideChar(encoding, 0, (LPCSTR)address, length, aResultToken.marker, conv_length);
#else
CStringW wide_buf;
// If the target string is not UTF-16, convert it to that first.
if (encoding != CP_UTF16)
{
StringCharToWChar((LPCSTR)address, wide_buf, length, encoding);
address = (void *)wide_buf.GetString();
length = wide_buf.GetLength();
}
// Now convert UTF-16 to ACP.
conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)address, length, NULL, 0, NULL, NULL);
if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator.
return; // Out of memory.
conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)address, length, aResultToken.marker, conv_length, NULL, NULL);
#endif
if (conv_length && !aResultToken.marker[conv_length - 1])
--conv_length; // Exclude null-terminator.
else
aResultToken.marker[conv_length] = '\0';
aResultToken.marker_length = conv_length; // Update this in case TokenSetResult used mem_to_free.
return;
}
else if (length > -1)
{
// No conversion necessary, but we might not want the whole string.
if (length == 0)
return; // Already set marker = "" above.
// Copy and null-terminate at the specified length.
TokenSetResult(aResultToken, (LPCTSTR)address, length);
return;
}
// Return this null-terminated string, no conversion necessary.
aResultToken.marker = (LPTSTR) address;
}
}
BIF_DECL(BIF_IsLabel)
// For performance and code-size reasons, this function does not currently return what
// type of label it is (hotstring, hotkey, or generic). To preserve the option to do
// this in the future, it has been documented that the function returns non-zero rather
// than "true". However, if performance is an issue (since scripts that use IsLabel are
// often performance sensitive), it might be better to add a second parameter that tells
// IsLabel to look up the type of label, and return it as a number or letter.
{
aResultToken.value_int64 = g_script.FindLabel(ParamIndexToString(0, aResultToken.buf)) ? 1 : 0; // "? 1 : 0" produces 15 bytes smaller OBJ size than "!= NULL" in this case (but apparently not in comparisons like x==y ? TRUE : FALSE).
}
BIF_DECL(BIF_IsFunc) // Lexikos: Added for use with dynamic function calls.
// Although it's tempting to return an integer like 0x8000000_min_max, where min/max are the function's
// minimum and maximum number of parameters stored in the low-order DWORD, it would be more friendly and
// readable to implement those outputs as optional ByRef parameters;
// e.g. IsFunc(FunctionName, ByRef Minparameters, ByRef Maxparameters)
// It's also tempting to return something like 1+func.mInstances; but mInstances is tracked only due to
// the nature of the current implementation of function-recursion; it might not be something that would
// be tracked in future versions, and its value to the script is questionable. Finally, a pointer to
// the Func struct itself could be returns so that the script could use NumGet() to retrieve function
// attributes. However, that would expose implementation details that might be likely to change in the
// future, plus it would be cumbersome to use. Therefore, something simple seems best; and since a
// dynamic function-call fails when too few parameters are passed (but not too many), it seems best to
// indicate to the caller not only that the function exists, but also how many parameters are required.
{
Func *func = TokenToFunc(*aParam[0]);
aResultToken.value_int64 = func ? (__int64)func->mMinParams+1 : 0;
}
BIF_DECL(BIF_Func)
// Returns a reference to an existing user-defined or built-in function, as an object.
{
Func *func = g_script.FindFunc(ParamIndexToString(0, aResultToken.buf));
if (func)
{
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = func;
}
else
aResultToken.value_int64 = 0;
}
BIF_DECL(BIF_IsByRef)
{
if (aParam[0]->symbol != SYM_VAR)
{
// Incorrect usage: return empty string to indicate the error.
aResultToken.symbol = SYM_STRING;
aResultToken.marker = _T("");
}
else
{
// Return true if the var is an alias for another var.
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = (aParam[0]->var->ResolveAlias() != aParam[0]->var);
}
}
BIF_DECL(BIF_GetKeyState)
{
TCHAR key_name_buf[MAX_NUMBER_SIZE]; // Because aResultToken.buf is used for something else below.
LPTSTR key_name = ParamIndexToString(0, key_name_buf);
// Keep this in sync with GetKeyJoyState().
// See GetKeyJoyState() for more comments about the following lines.
JoyControls joy;
int joystick_id;
vk_type vk = TextToVK(key_name);
if (!vk)
{
aResultToken.symbol = SYM_STRING; // ScriptGetJoyState() also requires that this be initialized.
if ( !(joy = (JoyControls)ConvertJoy(key_name, &joystick_id)) )
aResultToken.marker = _T("");
else
{
// The following must be set for ScriptGetJoyState():
aResultToken.marker = aResultToken.buf; // If necessary, it will be moved to a persistent memory location by our caller.
ScriptGetJoyState(joy, joystick_id, aResultToken, true);
}
return;
}
// Since above didn't return: There is a virtual key (not a joystick control).
TCHAR mode_buf[MAX_NUMBER_SIZE];
LPTSTR mode = ParamIndexToOptionalString(1, mode_buf);
KeyStateTypes key_state_type;
switch (ctoupper(*mode)) // Second parameter.
{
case 'T': key_state_type = KEYSTATE_TOGGLE; break; // Whether a toggleable key such as CapsLock is currently turned on.
case 'P': key_state_type = KEYSTATE_PHYSICAL; break; // Physical state of key.
default: key_state_type = KEYSTATE_LOGICAL;
}
// Caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need to set it here.
aResultToken.value_int64 = ScriptGetKeyState(vk, key_state_type); // 1 for down and 0 for up.
}
BIF_DECL(BIF_GetKeyName)
{
// Get VK and/or SC from the first parameter, which may be a key name, scXXX or vkXX.
// Key names are allowed even for GetKeyName() for simplicity and so that it can be
// used to normalise a key name; e.g. GetKeyName("Esc") returns "Escape".
LPTSTR key = ParamIndexToString(0, aResultToken.buf);
vk_type vk = TextToVK(key, NULL, true); // Pass true for the third parameter to avoid it calling TextToSC(), in case this is something like vk23sc14F.
sc_type sc = TextToSC(key);
if (!sc)
{
if (LPTSTR cp = tcscasestr(key, _T("SC"))) // TextToSC() supports SCxxx but not VKxxSCyyy.
sc = (sc_type)_tcstoul(cp + 2, NULL, 16);
else
sc = vk_to_sc(vk);
}
else if (!vk)
vk = sc_to_vk(sc);
switch (ctoupper(aResultToken.marker[6]))
{
case 'V': // GetKey[V]K
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = vk;
break;
case 'S': // GetKey[S]C
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = sc;
break;
default: // GetKey[N]ame
aResultToken.symbol = SYM_STRING;
aResultToken.marker = GetKeyName(vk, sc, aResultToken.buf, MAX_NUMBER_SIZE, _T(""));
}
}
BIF_DECL(BIF_VarSetCapacity)
// Returns: The variable's new capacity.
// Parameters:
// 1: Target variable (unquoted).
// 2: Requested capacity.
// 3: Byte-value to fill the variable with (e.g. 0 to have the same effect as ZeroMemory).
{
// Caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need to set it here.
aResultToken.value_int64 = 0; // Set default. In spite of being ambiguous with the result of Free(), 0 seems a little better than -1 since it indicates "no capacity" and is also equal to "false" for easy use in expressions.
if (aParam[0]->symbol == SYM_VAR) // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions).
{
Var &var = *aParam[0]->var; // For performance and convenience. SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions).
if (aParamCount > 1) // Second parameter is present.
{
// in bytes
VarSizeType new_capacity = (VarSizeType)TokenToInt64(*aParam[1]);
if (new_capacity == -1) // Adjust variable's internal length. Since new_capacity is unsigned, compare directly to -1 rather than doing <0.
{
// Seems more useful to report length vs. capacity in this special case. Scripts might be able
// to use this to boost performance.
aResultToken.value_int64 = var.ByteLength() = ((VarSizeType)_tcslen(var.Contents()) * sizeof(TCHAR)); // Performance: Length() and Contents() will update mContents if necessary, it's unlikely to be necessary under the circumstances of this call. In any case, it seems appropriate to do it this way.
var.Close(); // v1.0.44.14: Removes attributes like VAR_ATTRIB_BINARY_CLIP (if present) because it seems more flexible to convert binary-to-normal rather than checking IsBinaryClip() then doing nothing if it binary.
return;
}
// Since above didn't return:
if (!new_capacity && aParam[1]->symbol == SYM_MISSING)
{
// This case is likely to be rare, but allows VarSetCapacity(v,,b) to fill
// v with byte b up to its current capacity, rather than freeing it.
if (new_capacity = var.ByteCapacity())
new_capacity -= sizeof(TCHAR);
}
if (new_capacity)
{
BYTE *aBkpContents;
VarSizeType aBkpCapacity;
if (aParamCount < 3 && (aBkpCapacity = var.Capacity()) > 1) // Third parameter is present and var has enough capacity to make memmove() meaningful.
{ // backup variables content to restore later
// usefull when size of a variable is changed without loosing its content, e.g. increase memory array
aBkpContents = (BYTE*)_alloca(aBkpCapacity);
memmove(aBkpContents,var.Contents(false),aBkpCapacity);
}
var.SetCapacity(new_capacity, true, false); // This also destroys the variables contents.
// in characters
VarSizeType capacity;
if (aParamCount > 2 && (capacity = var.Capacity()) > 1) // Third parameter is present and var has enough capacity to make FillMemory() meaningful.
{
--capacity; // Convert to script-POV capacity. To avoid underflow, do this only now that Capacity() is known not to be zero.
// The following uses capacity-1 because the last byte of a variable should always
// be left as a binary zero to avoid crashes and problems due to unterminated strings.
// In other words, a variable's usable capacity from the script's POV is always one
// less than its actual capacity:
BYTE fill_byte = (BYTE)TokenToInt64(*aParam[2]); // For simplicity, only numeric characters are supported, not something like "a" to mean the character 'a'.
LPTSTR contents = var.Contents();
FillMemory(contents, capacity * sizeof(TCHAR), fill_byte); // Last byte of variable is always left as a binary zero.
contents[capacity] = '\0'; // Must terminate because nothing else is explicitly responsible for doing it.
var.SetCharLength(fill_byte ? capacity : 0); // Length is same as capacity unless fill_byte is zero.
}
else
{
// restore variables content if FillMemory parameter is not used and the size is apropriate
if (aParamCount < 3 && aBkpCapacity > 1 && (var.Capacity()) > 1)
memmove(var.Contents(false),aBkpContents,var.Capacity() < aBkpCapacity ? var.Capacity() : aBkpCapacity);
// By design, Assign() has already set the length of the variable to reflect new_capacity.
// This is not what is wanted in this case since it should be truly empty.
var.ByteLength() = 0;
}
}
else // ALLOC_SIMPLE, due to its nature, will not actually be freed, which is documented.
var.Free();
} // if (aParamCount > 1)
//else
//{
// RequestedCapacity was omitted, so the var is not altered; instead, the current capacity
// is reported, which seems more intuitive/useful than having it do a Free(). In this case
// it's an input var rather than an output var, so check if it has been initialized:
// v1.1.11.01: Support VarSetCapacity(var) as a means for the script to check if it
// has initialized a var. In other words, don't show a warning even in that case.
//var.MaybeWarnUninitialized();
//}
if (aResultToken.value_int64 = var.ByteCapacity()) // Don't subtract 1 here in lieu doing it below (avoids underflow).
aResultToken.value_int64 -= sizeof(TCHAR); // Omit the room for the zero terminator since script capacity is defined as length vs. size.
} // (aParam[0]->symbol == SYM_VAR)
}
BIF_DECL(BIF_FileExist)
{
TCHAR filename_buf[MAX_NUMBER_SIZE]; // Because aResultToken.buf is used for something else below.
LPTSTR filename = ParamIndexToString(0, filename_buf);
aResultToken.marker = aResultToken.buf; // If necessary, it will be moved to a persistent memory location by our caller.
aResultToken.symbol = SYM_STRING;
DWORD attr;
if (DoesFilePatternExist(filename, &attr))
{
// Yield the attributes of the first matching file. If not match, yield an empty string.
// This relies upon the fact that a file's attributes are never legitimately zero, which
// seems true but in case it ever isn't, this forces a non-empty string be used.
// UPDATE for v1.0.44.03: Someone reported that an existing file (created by NTbackup.exe) can
// apparently have undefined/invalid attributes (i.e. attributes that have no matching letter in
// "RASHNDOCT"). Although this is unconfirmed, it's easy to handle that possibility here by
// checking for a blank string. This allows FileExist() to report boolean TRUE rather than FALSE
// for such "mystery files":
FileAttribToStr(aResultToken.marker, attr);
if (!*aResultToken.marker) // See above.
{
// The attributes might be all 0, but more likely the file has some of the newer attributes
// such as FILE_ATTRIBUTE_ENCRYPTED (or has undefined attributes). So rather than storing attr as
// a hex number (which could be zero and thus defeat FileExist's ability to detect the file), it
// seems better to store some arbitrary letter (other than those in "RASHNDOCT") so that FileExist's
// return value is seen as boolean "true".
aResultToken.marker[0] = 'X';
aResultToken.marker[1] = '\0';
}
}
else // Empty string is the indicator of "not found" (seems more consistent than using an integer 0, since caller might rely on it being SYM_STRING).
*aResultToken.marker = '\0';
}
BIF_DECL(BIF_WinExistActive)
{
LPTSTR bif_name = aResultToken.marker; // Save this early for maintainability (it is the name of the function, provided by the caller).
aResultToken.symbol = SYM_STRING; // Returns a string to preserve hex format.
TCHAR *param[4], param_buf[4][MAX_NUMBER_SIZE];
for (int j = 0; j < 4; ++j) // For each formal parameter, including optional ones.
param[j] = ParamIndexToOptionalString(j, param_buf[j]);
// Should be called the same was as ACT_IFWINEXIST and ACT_IFWINACTIVE:
HWND found_hwnd = (ctoupper(bif_name[3]) == 'E') // Win[E]xist.
? WinExist(*g, param[0], param[1], param[2], param[3], false, true)
: WinActive(*g, param[0], param[1], param[2], param[3], true);
aResultToken.marker = HwndToString(found_hwnd, aResultToken.buf);
}
BIF_DECL(BIF_ResourceLoadLibrary)
{
aResultToken.symbol = PURE_INTEGER;
aResultToken.value_int64 = 0;
if (TokenIsEmptyString(*aParam[0]))
return;
HMEMORYMODULE module = NULL;
TextMem::Buffer textbuf;
HRSRC hRes;
HGLOBAL hResData = NULL;
hRes = FindResource(NULL, aParam[0]->symbol == SYM_VAR ? aParam[0]->var->Contents() : aParam[0]->marker, MAKEINTRESOURCE(RT_RCDATA));
if ( !( hRes
&& (textbuf.mLength = SizeofResource(NULL, hRes))
&& (hResData = LoadResource(NULL, hRes))
&& (textbuf.mBuffer = LockResource(hResData)) ) )
return;
DWORD aSizeDeCompressed = NULL;
if (*(unsigned int*)textbuf.mBuffer == 0x04034b50)
{
LPVOID aDataBuf;
aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf,g_default_pwd);
if (aSizeDeCompressed)
{
module = MemoryLoadLibrary( aDataBuf );
+ SecureZeroMemory(aDataBuf, aSizeDeCompressed);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
}
}
if (!aSizeDeCompressed)
module = MemoryLoadLibrary( textbuf.mBuffer );
aResultToken.value_int64 = (UINT_PTR)module;
}
BIF_DECL(BIF_MemoryLoadLibrary)
{
HMEMORYMODULE module = NULL;
unsigned char *data = NULL;
aResultToken.symbol = SYM_INTEGER;
if (TokenIsEmptyString(*aParam[0]))
{
aResultToken.value_int64 = 0;
return;
}
else if (!TokenIsPureNumeric(*aParam[0]))
{
FILE *fp;
size_t size;
fp = _tfopen(TokenToString(*aParam[0]), _T("rb"));
if (fp == NULL)
return;
fseek(fp, 0, SEEK_END);
size = ftell(fp);
data = (unsigned char *)_alloca(size);
fseek(fp, 0, SEEK_SET);
fread(data, 1, size, fp);
fclose(fp);
}
else
data = (unsigned char*)TokenToInt64(*aParam[0]);
if (data)
module = MemoryLoadLibraryEx(data,
(CustomLoadLibraryFunc)(aParamCount > 1 ? (HCUSTOMMODULE)TokenToInt64(*aParam[1]) : _LoadLibrary),
(CustomGetProcAddressFunc)(aParamCount > 2 ? (HCUSTOMMODULE)TokenToInt64(*aParam[2]) : _GetProcAddress),
(CustomFreeLibraryFunc)(aParamCount > 3 ? (HCUSTOMMODULE)TokenToInt64(*aParam[3]) : _FreeLibrary),
(void*)(aParamCount > 4 ? TokenToInt64(*aParam[4]) : NULL));
aResultToken.value_int64 = (UINT_PTR)module;
}
BIF_DECL(BIF_MemoryGetProcAddress)
{
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = 0;
if (!TokenToInt64(*aParam[0]))
return;
//if (!aParam[0]->deref->marker)
//return;
TCHAR *FuncName = TokenToString(*aParam[1]);
#ifdef _UNICODE
char *buf = (char*)_alloca(_tcslen(FuncName)+sizeof(char*));
wcstombs(buf,FuncName,_tcslen(FuncName));
buf[_tcslen(FuncName)] = '\0';
#endif
aResultToken.value_int64 = (__int64)MemoryGetProcAddress((HMEMORYMODULE)TokenToInt64(*aParam[0])
#ifdef _UNICODE
,buf);
#else
,FuncName);
#endif
}
BIF_DECL(BIF_MemoryFreeLibrary)
{
aResultToken.symbol = SYM_STRING;
aResultToken.marker =_T("");
if (!TokenToInt64(*aParam[0]))
return;
MemoryFreeLibrary((HMEMORYMODULE)TokenToInt64(*aParam[0]));
}
BIF_DECL(BIF_MemoryFindResource)
{
aResultToken.symbol = SYM_STRING;
aResultToken.marker =_T("");
if (!TokenToInt64(*aParam[0]))
return;
HMEMORYRSRC resource = NULL;
if (ParamIndexIsOmitted(3)) // FindResource
resource = MemoryFindResource((HMEMORYMODULE)TokenToInt64(*aParam[0]),TokenIsPureNumeric(*aParam[1]) ? (LPCTSTR)TokenToInt64(*aParam[1]) : TokenToString(*aParam[1]),TokenIsPureNumeric(*aParam[2]) ? (LPCTSTR)TokenToInt64(*aParam[2]) : TokenToString(*aParam[2]));
else // FindResourceEx
resource = MemoryFindResourceEx((HMEMORYMODULE)TokenToInt64(*aParam[0]),TokenIsPureNumeric(*aParam[1]) ? (LPCTSTR)TokenToInt64(*aParam[1]) : TokenToString(*aParam[1]),TokenIsPureNumeric(*aParam[2]) ? (LPCTSTR)TokenToInt64(*aParam[2]) : TokenToString(*aParam[2]),(WORD)TokenToInt64(*aParam[3]));
if (resource)
{
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = (__int64)resource;
}
}
BIF_DECL(BIF_MemorySizeOfResource)
{
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = 0;
if (!TokenToInt64(*aParam[0]))
return;
aResultToken.value_int64 = MemorySizeOfResource((HMEMORYMODULE)TokenToInt64(*aParam[0]),(HMEMORYRSRC)TokenToInt64(*aParam[1]));
}
BIF_DECL(BIF_MemoryLoadResource)
{
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = 0;
if (!TokenToInt64(*aParam[0]))
return;
aResultToken.value_int64 = (__int64)MemoryLoadResource((HMEMORYMODULE)TokenToInt64(*aParam[0]),(HMEMORYRSRC)TokenToInt64(*aParam[1]));
}
BIF_DECL(BIF_MemoryLoadString)
{
aResultToken.symbol = SYM_STRING;
aResultToken.marker = _T("");
if (!TokenToInt64(*aParam[0]))
return;
LPVOID result;
if (ParamIndexIsOmitted(2) || TokenToInt64(*aParam[2]) == 0 )
result = MemoryLoadStringEx((HMEMORYMODULE)TokenToInt64(*aParam[0]),(UINT)TokenToInt64(*aParam[1]),0,0,ParamIndexIsOmitted(4) ? 0 : (WORD)TokenToInt64(*aParam[4]));
else
result = MemoryLoadStringEx((HMEMORYMODULE)TokenToInt64(*aParam[0]),(UINT)TokenToInt64(*aParam[1]),TokenToString(*aParam[2]),(int)TokenToInt64(*aParam[3]),ParamIndexIsOmitted(4) ? 0 : (WORD)TokenToInt64(*aParam[4]));
if (result)
{
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = (__int64)result;
}
else
{
aResultToken.symbol = SYM_STRING;
aResultToken.marker =_T("");
}
}
BIF_DECL(BIF_UnZipRawMemory)
{
if (TokenToInt64(*aParam[0]))
{
LPVOID aDataBuf = NULL;
TCHAR *pw[1024] = {};
if (!ParamIndexIsOmittedOrEmpty(2))
{
TCHAR *pwd = TokenToString(*aParam[2]);
size_t pwlen = _tcslen(TokenToString(*aParam[2]));
for(size_t i = 0;i <= pwlen;i++)
pw[i] = &pwd[i];
}
aResultToken.value_int64 = DecompressBuffer((void *)TokenToInt64(*aParam[0]), aDataBuf,pw);
if (aResultToken.value_int64)
{
aResultToken.symbol = SYM_INTEGER;
if (!ParamIndexIsOmitted(1))
{
if (aParam[1]->symbol == SYM_VAR)
{
aParam[1]->var->SetCapacity((VarSizeType)aResultToken.value_int64 + sizeof(TCHAR));
memmove(aParam[1]->var->mCharContents,aDataBuf,(SIZE_T)aResultToken.value_int64 + sizeof(TCHAR));
}
else if (TokenToInt64(*aParam[1]) > 1024) // Assume address
memmove((void *)TokenToInt64(*aParam[1]),aDataBuf,(SIZE_T)aResultToken.value_int64);
}
- VirtualFree(aDataBuf,(SIZE_T)aResultToken.value_int64,MEM_RELEASE);
+ SecureZeroMemory(aDataBuf, (size_t)aResultToken.value_int64);
+ VirtualFree(aDataBuf,(size_t)aResultToken.value_int64,MEM_RELEASE);
return;
}
}
aResultToken.symbol = SYM_STRING;
aResultToken.marker =_T("");
}
BIF_DECL(BIF_Round)
// For simplicity and backward compatibility, this always yields something numeric (or a string that's numeric).
// Even Round(empty_or_unintialized_var) is zero rather than "".
{
LPTSTR buf = aResultToken.buf; // Must be saved early since below overwrites the union (better maintainability too).
// See TRANS_CMD_ROUND for details.
int param2;
double multiplier;
if (aParamCount > 1)
{
param2 = ParamIndexToInt(1);
multiplier = qmathPow(10, param2);
}
else // Omitting the parameter is the same as explicitly specifying 0 for it.
{
param2 = 0;
multiplier = 1;
}
double value = ParamIndexToDouble(0);
aResultToken.value_double = (value >= 0.0 ? qmathFloor(value * multiplier + 0.5)
: qmathCeil(value * multiplier - 0.5)) / multiplier;
// If incoming value is an integer, it seems best for flexibility to convert it to a
// floating point number whenever the second param is >0. That way, it can be used
// to "cast" integers into floats. Conversely, it seems best to yield an integer
// whenever the second param is <=0 or omitted.
if (param2 > 0) // aResultToken.value_double already contains the result.
{
// v1.0.44.01: Since Round (in its param2>0 mode) is almost always used to facilitate some kind of
// display or output of the number (hardly ever for intentional reducing the precision of a floating
// point math operation), it seems best by default to omit only those trailing zeroes that are beyond
// the specified number of decimal places. This is done by converting the result into a string here,
// which will cause the expression evaluation to write out the final result as this very string as long
// as no further floating point math is done on it (such as Round(3.3333, 2)+0). Also note that not
// all trailing zeros are removed because it is often the intent that exactly the number of decimal
// places specified should be *shown* (for column alignment, etc.). For example, Round(3.5, 2) should
// be 3.50 not 3.5. Similarly, Round(1, 2) should be 1.00 not 1 (see above comment about "casting" for
// why.
// Performance: This method is about twice as slow as the old method (which did merely the line
// "aResultToken.symbol = SYM_FLOAT" in place of the below). However, that might be something
// that can be further optimized in the caller (its calls to _tcslen, memcpy, etc. might be optimized
// someday to omit certain calls when very simply situations allow it). In addition, twice as slow is
// not going to impact the vast majority of scripts since as mentioned above, Round (in its param2>0
// mode) is almost always used for displaying data, not for intensive operations within a expressions.
// AS DOCUMENTED: Round(..., positive_number) doesn't obey SetFormat (nor scientific notation).
// The script can force Round(x, 2) to obey SetFormat by adding 0 to the result (if it wants).
// Also, a new parameter an be added someday to trim excess trailing zeros from param2>0's result
// (e.g. Round(3.50, 2, true) can be 3.5 rather than 3.50), but this seems less often desired due to
// column alignment and other goals where consistency is important.
_stprintf(buf, _T("%0.*f"), param2, aResultToken.value_double); // %f can handle doubles in MSVC++.
aResultToken.marker = buf;
aResultToken.symbol = SYM_STRING;
}
else
// Fix for v1.0.47.04: See BIF_FloorCeil() for explanation of this fix. Currently, the only known example
// of when the fix is necessary is the following script in release mode (not debug mode):
// myNumber := 1043.22 ; Bug also happens with -1043.22 (negative).
// myRounded1 := Round( myNumber, -1 ) ; Stores 1040 (correct).
// ChartModule := DllCall("LoadLibrary", "str", "rmchart.dll")
// myRounded2 := Round( myNumber, -1 ) ; Stores 1039 (wrong).
aResultToken.value_int64 = (__int64)(aResultToken.value_double + (aResultToken.value_double > 0 ? 0.2 : -0.2));
// Formerly above was: aResultToken.value_int64 = (__int64)aResultToken.value_double;
// Caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need to set it here.
}
BIF_DECL(BIF_FloorCeil)
// Probably saves little code size to merge extremely short/fast functions, hence FloorCeil.
// Floor() rounds down to the nearest integer; that is, to the integer that lies to the left on the
// number line (this is not the same as truncation because Floor(-1.2) is -2, not -1).
// Ceil() rounds up to the nearest integer; that is, to the integer that lies to the right on the number line.
//
// For simplicity and backward compatibility, a numeric result is always returned (even if the input
// is non-numeric or an empty string).
{
// The code here is similar to that in TRANS_CMD_FLOOR/CEIL, so maintain them together.
// The qmath routines are used because Floor() and Ceil() are deceptively difficult to implement in a way
// that gives the correct result in all permutations of the following:
// 1) Negative vs. positive input.
// 2) Whether or not the input is already an integer.
// Therefore, do not change this without conduction a thorough test.
double x = ParamIndexToDouble(0);
x = (ctoupper(aResultToken.marker[0]) == 'F') ? qmathFloor(x) : qmathCeil(x);
// Fix for v1.0.40.05: For some inputs, qmathCeil/Floor yield a number slightly to the left of the target
// integer, while for others they yield one slightly to the right. For example, Ceil(62/61) and Floor(-4/3)
// yield a double that would give an incorrect answer if it were simply truncated to an integer via
// type casting. The below seems to fix this without breaking the answers for other inputs (which is
// surprisingly harder than it seemed). There is a similar fix in BIF_Round().
aResultToken.value_int64 = (__int64)(x + (x > 0 ? 0.2 : -0.2));
// Caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need to set it here.
}
BIF_DECL(BIF_Mod)
{
// Load-time validation has already ensured there are exactly two parameters.
// "Cast" each operand to Int64/Double depending on whether it has a decimal point.
ExprTokenType param0, param1;
if (!ParamIndexToNumber(0, param0) || !ParamIndexToNumber(1, param1)) // Non-operand or non-numeric string.
{
aResultToken.symbol = SYM_STRING;
aResultToken.marker = _T("");
return;
}
if (param0.symbol == SYM_INTEGER && param1.symbol == SYM_INTEGER)
{
if (!param1.value_int64) // Divide by zero.
{
aResultToken.symbol = SYM_STRING;
aResultToken.marker = _T("");
}
else
// For performance, % is used vs. qmath for integers.
// Caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need to set it here.
aResultToken.value_int64 = param0.value_int64 % param1.value_int64;
}
else // At least one is a floating point number.
{
double dividend = TokenToDouble(param0);
double divisor = TokenToDouble(param1);
if (divisor == 0.0) // Divide by zero.
{
aResultToken.symbol = SYM_STRING;
aResultToken.marker = _T("");
}
else
{
aResultToken.symbol = SYM_FLOAT;
aResultToken.value_double = qmathFmod(dividend, divisor);
}
}
}
BIF_DECL(BIF_Abs)
{
// Unlike TRANS_CMD_ABS, which removes the minus sign from the string if it has one,
// this is done in a more traditional way. It's hard to imagine needing the minus
// sign removal method here since a negative hex literal such as -0xFF seems too rare
// to worry about. One additional reason not to remove minus signs from strings is
// that it might produce inconsistent results depending on whether the operand is
// generic (SYM_OPERAND) and numeric. In other words, abs() shouldn't treat a
// sub-expression differently than a numeric literal.
if (!TokenToDoubleOrInt64(*aParam[0], aResultToken)) // "Cast" token to Int64/Double depending on whether it has a decimal point.
// Non-operand or non-numeric string. TokenToDoubleOrInt64() has already set the token to be an
// empty string for us.
return;
if (aResultToken.symbol == SYM_INTEGER)
{
// The following method is used instead of __abs64() to allow linking against the multi-threaded
// DLLs (vs. libs) if that option is ever used (such as for a minimum size AutoHotkeySC.bin file).
// It might be somewhat faster than __abs64() anyway, unless __abs64() is a macro or inline or something.
if (aResultToken.value_int64 < 0)
aResultToken.value_int64 = -aResultToken.value_int64;
}
else // Must be SYM_FLOAT due to the conversion above.
aResultToken.value_double = qmathFabs(aResultToken.value_double);
}
BIF_DECL(BIF_Sin)
// For simplicity and backward compatibility, a numeric result is always returned (even if the input
// is non-numeric or an empty string).
{
aResultToken.symbol = SYM_FLOAT;
aResultToken.value_double = qmathSin(ParamIndexToDouble(0));
}
BIF_DECL(BIF_Cos)
// For simplicity and backward compatibility, a numeric result is always returned (even if the input
// is non-numeric or an empty string).
{
aResultToken.symbol = SYM_FLOAT;
aResultToken.value_double = qmathCos(ParamIndexToDouble(0));
}
BIF_DECL(BIF_Tan)
// For simplicity and backward compatibility, a numeric result is always returned (even if the input
// is non-numeric or an empty string).
{
aResultToken.symbol = SYM_FLOAT;
aResultToken.value_double = qmathTan(ParamIndexToDouble(0));
}
BIF_DECL(BIF_ASinACos)
{
double value = ParamIndexToDouble(0);
if (value > 1 || value < -1) // ASin and ACos aren't defined for such values.
{
aResultToken.symbol = SYM_STRING;
aResultToken.marker = _T("");
}
else
{
// For simplicity and backward compatibility, a numeric result is always returned in this case (even if
// the input is non-numeric or an empty string).
aResultToken.symbol = SYM_FLOAT;
// Below: marker contains either "ASin" or "ACos"
aResultToken.value_double = (ctoupper(aResultToken.marker[1]) == 'S') ? qmathAsin(value) : qmathAcos(value);
}
}
BIF_DECL(BIF_ATan)
// For simplicity and backward compatibility, a numeric result is always returned (even if the input
// is non-numeric or an empty string).
{
aResultToken.symbol = SYM_FLOAT;
aResultToken.value_double = qmathAtan(ParamIndexToDouble(0));
}
BIF_DECL(BIF_Exp)
// For simplicity and backward compatibility, a numeric result is always returned (even if the input
// is non-numeric or an empty string).
{
aResultToken.symbol = SYM_FLOAT;
aResultToken.value_double = qmathExp(ParamIndexToDouble(0));
}
BIF_DECL(BIF_SqrtLogLn)
{
double value = ParamIndexToDouble(0);
if (value < 0) // Result is undefined in these cases, so make blank to indicate.
{
aResultToken.symbol = SYM_STRING;
aResultToken.marker = _T("");
}
else
{
// For simplicity and backward compatibility, a numeric result is always returned in this case (even if
// the input is non-numeric or an empty string).
aResultToken.symbol = SYM_FLOAT;
switch (ctoupper(aResultToken.marker[1]))
{
case 'Q': // S[q]rt
aResultToken.value_double = qmathSqrt(value);
break;
case 'O': // L[o]g
aResultToken.value_double = qmathLog10(value);
break;
default: // L[n]
aResultToken.value_double = qmathLog(value);
}
}
}
BIF_DECL(BIF_OnMessage)
// Returns: An empty string on failure or the name of a function (depends on mode) on success.
// Parameters:
// 1: Message number to monitor.
// 2: Name of the function that will monitor the message.
// 3: (FUTURE): A flex-list of space-delimited option words/letters.
{
LPTSTR buf = aResultToken.buf; // Must be saved early since below overwrites the union (better maintainability too).
// Set default result in case of early return; a blank value:
aResultToken.symbol = SYM_STRING;
aResultToken.marker = _T("");
// Load-time validation has ensured there's at least one parameter for use here:
UINT specified_msg = (UINT)ParamIndexToInt64(0); // Parameter #1
HWND specified_hwnd;
if (aParamCount > 1 && TokenToInt64(*aParam[1])) // Parameter #2
specified_hwnd = (HWND)TokenToInt64(*aParam[1]);
else
specified_hwnd = 0;
Func *func = NULL; // Set defaults.
bool mode_is_delete = false; //
if (!ParamIndexIsOmitted(specified_hwnd ? 2 : 1)) // Parameter #2 is present (#3 if func is present).
{
LPTSTR func_name;
if (func = dynamic_cast<Func*>(TokenToObject(*aParam[specified_hwnd ? 2 : 1])))
{
if (func->mIsBuiltIn || func->mMinParams > 4) // Requires too many params.
return; // Yield the default return value set earlier.
}
else if (*(func_name = ParamIndexToString(specified_hwnd ? 2 : 1, buf))) // Resolve parameter #2.
{
if ( !(func = g_script.FindFunc(func_name)) ) // Nonexistent function.
{
if ( !(func = dynamic_cast<Func*>(TokenToObject(*aParam[specified_hwnd ? 2 : 1]))))
return; // Yield the default return value set earlier.
}
// If too many formal parameters or any are ByRef/optional, indicate failure.
// This helps catch bugs in scripts that are assigning the wrong function to a monitor.
// It also preserves additional parameters for possible future use (i.e. avoids breaking
// existing scripts if more formal parameters are supported in a future version).
// Lexikos: The flexibility of allowing ByRef and optional parameters seems to outweigh
// the small chance that these checks will actually catch an error and the even smaller
// chance that any parameters will be added in future. For instance, a function may be
// called directly by the script to set or retrieve static vars which are used when the
// message monitor calls the function. For these checks to actually catch an error, the
// author must have typed the name of the wrong function (i.e. probably not a typo), and
// that function must accept more than four parameters or have optional/ByRef parameters:
//if (func->mIsBuiltIn || func->mParamCount > 4 || func->mMinParams < func->mParamCount) // Too many params, or some are optional.
if (func->mIsBuiltIn || func->mMinParams > 4) // Requires too many params.
return; // Yield the default return value set earlier.
//for (int i = 0; i < func->mParamCount; ++i) // Check if any formal parameters are ByRef.
// if (func->mParam[i].is_byref)
// return; // Yield the default return value set earlier.
}
else // Explicitly blank function name ("") means delete this item. By contrast, an omitted second parameter means "give me current function of this message".
mode_is_delete = true;
}
// If this is the first use of the g_MsgMonitor array, create it now rather than later to reduce code size
// and help the maintainability of sections further below. The following relies on short-circuit boolean order:
if (!g_MsgMonitor && !(g_MsgMonitor = (MsgMonitorStruct *)malloc(sizeof(MsgMonitorStruct) * MAX_MSG_MONITORS)))
return; // Yield the default return value set earlier.
// Check if this message already exists in the array:
int msg_index;
for (msg_index = 0; msg_index < g_MsgMonitorCount; ++msg_index)
if (g_MsgMonitor[msg_index].msg == specified_msg && g_MsgMonitor[msg_index].hwnd == specified_hwnd )
break;
bool item_already_exists = (msg_index < g_MsgMonitorCount);
MsgMonitorStruct &monitor = g_MsgMonitor[msg_index == MAX_MSG_MONITORS ? 0 : msg_index]; // The 0th item is just a placeholder.
if (item_already_exists)
{
// In all cases, yield the OLD function's name as the return value:
_tcscpy(buf, monitor.func->mName); // Caller has ensured that buf large enough to support max function name.
aResultToken.marker = buf;
if (mode_is_delete)
{
// The msg-monitor is deleted from the array for two reasons:
// 1) It improves performance because every incoming message for the app now needs to be compared
// to one less filter. If the count will now be zero, performance is improved even more because
// the overhead of the call to MsgMonitor() is completely avoided for every incoming message.
// 2) It conserves space in the array in a situation where the script creates hundreds of
// msg-monitors and then later deletes them, then later creates hundreds of filters for entirely
// different message numbers.
// The main disadvantage to deleting message filters from the array is that the deletion might
// occur while the monitor is currently running, which requires more complex handling within
// MsgMonitor() (see its comments for details).
--g_MsgMonitorCount; // Must be done prior to the below.
if (msg_index < g_MsgMonitorCount) // An element other than the last is being removed. Shift the array to cover/delete it.
MoveMemory(g_MsgMonitor+msg_index, g_MsgMonitor+msg_index+1, sizeof(MsgMonitorStruct)*(g_MsgMonitorCount-msg_index));
return;
}
if (aParamCount < (specified_hwnd ? 3 : 2)) // Single-parameter mode: Report existing item's function name.
return; // Everything was already set up above to yield the proper return value.
// Otherwise, an existing item is being assigned a new function or MaxThreads limit.
// Continue on to update this item's attributes.
}
else // This message doesn't exist in array yet.
{
if (!func) // Delete or report function-name of a non-existent item.
return; // Yield the default return value set earlier (an empty string).
// Since above didn't return, the message is to be added as a new element. The above already
// verified that func is not NULL.
if (msg_index == MAX_MSG_MONITORS) // No room in array.
return; // Indicate failure by yielding the default return value set earlier.
// Otherwise, the message is to be added, so increment the total:
++g_MsgMonitorCount;
_tcscpy(buf, func->mName); // Yield the NEW name as an indicator of success. Caller has ensured that buf large enough to support max function name.
aResultToken.marker = buf;
monitor.instance_count = 0; // Reset instance_count only for new items since existing items might currently be running.
monitor.msg = specified_msg;
// Continue on to the update-or-create logic below.
}
// Since above didn't return, above has ensured that msg_index is the index of the existing or new
// MsgMonitorStruct in the array. In addition, it has set the proper return value for us.
// Update those struct attributes that get the same treatment regardless of whether this is an update or creation.
if (func) // i.e. not OnMessage(Msg,,MaxThreads).
monitor.func = func;
monitor.hwnd = specified_hwnd;
if (!ParamIndexIsOmitted(specified_hwnd ? 3 : 2))
monitor.max_instances = (short)ParamIndexToInt64(specified_hwnd ? 3 : 2); // No validation because it seems harmless if it's negative or some huge number.
else // Unspecified, so if this item is being newly created fall back to the default.
if (!item_already_exists)
monitor.max_instances = 1;
}
#ifdef ENABLE_REGISTERCALLBACK
struct RCCallbackFunc // Used by BIF_RegisterCallback() and related.
{
#ifdef WIN32_PLATFORM
ULONG data1; //E8 00 00 00
ULONG data2; //00 8D 44 24
ULONG data3; //08 50 FF 15
UINT_PTR (CALLBACK **callfuncptr)(UINT_PTR*, char*);
ULONG data4; //59 84 C4 nn
USHORT data5; //FF E1
#endif
#ifdef _WIN64
UINT64 data1; // 0xfffffffff9058d48
UINT64 data2; // 0x9090900000000325
void (*stub)();
UINT_PTR (CALLBACK *callfuncptr)(UINT_PTR*, char*);
#endif
//code ends
UCHAR actual_param_count; // This is the actual (not formal) number of parameters passed from the caller to the callback. Kept adjacent to the USHORT above to conserve memory due to 4-byte struct alignment.
bool create_new_thread; // Kept adjacent to above to conserve memory due to 4-byte struct alignment.
EventInfoType event_info; // A_EventInfo
Func *func; // The UDF to be called whenever the callback's caller calls callfuncptr.
};
#ifdef _WIN64
extern "C" void RegisterCallbackAsmStub();
#endif
UINT_PTR CALLBACK RegisterCallbackCStub(UINT_PTR *params, char *address) // Used by BIF_RegisterCallback().
// JGR: On Win32 parameters are always 4 bytes wide. The exceptions are functions which work on the FPU stack
// (not many of those). Win32 is quite picky about the stack always being 4 byte-aligned, (I have seen only one
// application which defied that and it was a patched ported DOS mixed mode application). The Win32 calling
// convention assumes that the parameter size equals the pointer size. 64 integers on Win32 are passed on
// pointers, or as two 32 bit halves for some functions...
{
#define DEFAULT_CB_RETURN_VALUE 0 // The value returned to the callback's caller if script doesn't provide one.
#ifdef WIN32_PLATFORM
RCCallbackFunc &cb = *((RCCallbackFunc*)(address-5)); //second instruction is 5 bytes after start (return address pushed by call)
#else
RCCallbackFunc &cb = *((RCCallbackFunc*) address);
#endif
Func &func = *cb.func; // For performance and convenience.
TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE];
EventInfoType EventInfo_saved;
BOOL pause_after_execute;
// NOTES ABOUT INTERRUPTIONS / CRITICAL:
// An incoming call to a callback is considered an "emergency" for the purpose of determining whether
// critical/high-priority threads should be interrupted because there's no way easy way to buffer or
// postpone the call. Therefore, NO check of the following is done here:
// - Current thread's priority (that's something of a deprecated feature anyway).
// - Current thread's status of Critical (however, Critical would prevent us from ever being called in
// cases where the callback is triggered indirectly via message/dispatch due to message filtering
// and/or Critical's ability to pump messes less often).
// - INTERRUPTIBLE_IN_EMERGENCY (which includes g_MenuIsVisible and g_AllowInterruption), which primarily
// affects SLEEP_WITHOUT_INTERRUPTION): It's debatable, but to maximize flexibility it seems best to allow
// callbacks during the display of a menu and during SLEEP_WITHOUT_INTERRUPTION. For most callers of
// SLEEP_WITHOUT_INTERRUPTION, interruptions seem harmless. For some it could be a problem, but when you
// consider how rare such callbacks are (mostly just subclassing of windows/controls) and what those
// callbacks tend to do, conflicts seem very rare.
// Of course, a callback can also be triggered through explicit script action such as a DllCall of
// EnumWindows, in which case the script would want to be interrupted unconditionally to make the call.
// However, in those cases it's hard to imagine that INTERRUPTIBLE_IN_EMERGENCY wouldn't be true anyway.
if (cb.create_new_thread)
{
if (g_nThreads >= g_MaxThreadsTotal) // Since this is a callback, it seems too rare to make an exemption for functions whose first line is ExitApp. In any case, to avoid array overflow, g_MaxThreadsTotal must not be exceeded except where otherwise documented.
return DEFAULT_CB_RETURN_VALUE;
// See MsgSleep() for comments about the following section.
tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved));
InitNewThread(0, false, true, func.mJumpToLine->mActionType);
DEBUGGER_STACK_PUSH(_T("Callback"))
}
else // Backup/restore only A_EventInfo. This avoids callbacks changing A_EventInfo for the current thread/context (that would be counterintuitive and a source of script bugs).
{
EventInfo_saved = g->EventInfo;
if (pause_after_execute = g->IsPaused) // Assign.
{
// v1.0.48: If the current thread is paused, this threadless callback would get stuck in
// ExecUntil()'s pause loop (keep in mind that this situation happens only when a fast-mode
// callback has been created without a script thread to control it, which goes against the
// advice in the documentation). To avoid that, it seems best to temporarily unpause the
// thread until the callback finishes. But for performance, tray icon color isn't updated.
g->IsPaused = false;
--g_nPausedThreads; // See below.
// If g_nPausedThreads isn't adjusted here, g_nPausedThreads could become corrupted if the
// callback (or some thread that interrupts it) uses the Pause command/menu-item because
// those aren't designed to deal with g->IsPaused being out-of-sync with g_nPausedThreads.
// However, if --g_nPausedThreads reduces g_nPausedThreads to 0, timers would allowed to
// run during the callback. But that seems like the lesser evil, especially given that
// this whole situation is very rare, and the documentation advises against doing it.
}
//else the current thread wasn't paused, which is usually the case.
// TRAY ICON: g_script.UpdateTrayIcon() is not called because it's already in the right state
// except when pause_after_execute==true, in which case it seems best not to change the icon
// because it's likely to hurt any callback that's performance-sensitive.
}
g->EventInfo = cb.event_info; // This is the means to identify which caller called the callback (if the script assigned more than one caller to this callback).
// For performance and to preserve stack space, the indirect method of calling a function via the new
// Func::Call overload is not used here. Using it would only be necessary to support variadic functions,
// which have very limited use as callbacks; instead, we pass such functions a pointer to surplus params.
// Need to check if backup of function's variables is needed in case:
// 1) The UDF is assigned to more than one callback, in which case the UDF could be running more than once
// simultaneously.
// 2) The callback is intended to be reentrant (e.g. a subclass/WindowProc that doesn't use Critical).
// 3) Script explicitly calls the UDF in addition to using it as a callback.
|
tinku99/ahkdll
|
ff764ac59e470a37f8ca878903ab00b4012bff50
|
/iLib support for WinApi and Resource library
|
diff --git a/source/script.cpp b/source/script.cpp
index b982772..b1845f2 100644
--- a/source/script.cpp
+++ b/source/script.cpp
@@ -9671,1162 +9671,1202 @@ ResultType Script::DefineClassVars(LPTSTR aBuf, bool aStatic)
break;
case ':':
if (item_end[1] == '=')
{
item_end += 2; // Point to the character after the ":=".
break;
}
// Otherwise, fall through to below:
default:
return ScriptError(ERR_INVALID_CLASS_VAR, item);
}
// Since above didn't "continue", this declared variable also has an initializer.
// Append the class name, ":=" and initializer to pending_buf, to be turned into
// an expression below, and executed at script start-up.
item_end = omit_leading_whitespace(item_end);
LPTSTR right_side_of_operator = item_end; // Save for use below.
item_end += FindNextDelimiter(item_end); // Find the next comma which is not part of the initializer (or find end of string).
// Append "ClassNameOrThis.VarName := Initializer, " to the buffer.
int chars_written = _sntprintf(buf + buf_used, _countof(buf) - buf_used, _T("%s.%.*s := %.*s, ")
, aStatic ? mClassName : _T("this"), name_length, item, item_end - right_side_of_operator, right_side_of_operator);
if (chars_written < 0)
return ScriptError(_T("Declaration too long.")); // Short message since should be rare.
buf_used += chars_written;
// Set "item" for use by the next iteration:
item = (*item_end == ',') // i.e. it's not the terminator and thus not the final item in the list.
? omit_leading_whitespace(item_end + 1)
: item_end; // It's the terminator, so let the loop detect that to finish.
}
if (buf_used)
{
// Above wrote at least one initializer expression into buf.
buf[buf_used -= 2] = '\0'; // Remove the final ", "
// The following section temporarily replaces mLastLine in order to insert script lines
// either at the end of the list of static initializers (separate from the main script)
// or at the end of the __Init method belonging to this class. Save the current values:
Line *script_first_line = mFirstLine, *script_last_line = mLastLine;
Line *block_end;
Func *init_func = NULL;
if (aStatic)
{
mLastLine = mLastStaticLine;
mFirstLine = mFirstStaticLine;
}
else
{
ExprTokenType token;
if (class_object->GetItem(token, _T("__Init")) && token.symbol == SYM_OBJECT
&& (init_func = dynamic_cast<Func *>(token.object))) // This cast SHOULD always succeed; done for maintainability.
{
// __Init method already exists, so find the end of its body.
for (block_end = init_func->mJumpToLine;
block_end->mActionType != ACT_BLOCK_END || !block_end->mAttribute;
block_end = block_end->mNextLine);
}
else
{
// Create an __Init method for this class.
TCHAR def[] = _T("__Init()");
if (!DefineFunc(def, NULL) || !AddLine(ACT_BLOCK_BEGIN)
|| (class_object->Base() && !ParseAndAddLine(_T("base.__Init()"), ACT_EXPRESSION))) // Initialize base-class variables first. Relies on short-circuit evaluation.
return FAIL;
mLastLine->mLineNumber = 0; // Signal the debugger to skip this line while stepping in/over/out.
init_func = g->CurrentFunc;
init_func->mDefaultVarType = VAR_DECLARE_GLOBAL; // Allow global variables/class names in initializer expressions.
if (!AddLine(ACT_BLOCK_END)) // This also resets g->CurrentFunc to NULL.
return FAIL;
block_end = mLastLine;
block_end->mLineNumber = 0; // See above.
// These must be updated as one or both have changed:
script_first_line = mFirstLine;
script_last_line = mLastLine;
}
g->CurrentFunc = init_func; // g->CurrentFunc should be NULL prior to this.
mLastLine = block_end->mPrevLine; // i.e. insert before block_end.
mLastLine->mNextLine = NULL; // For maintainability; AddLine() should overwrite it regardless.
mCurrLine = NULL; // Fix for v1.1.09.02: Leaving this non-NULL at best causes error messages to show irrelevant vicinity lines, and at worst causes a crash because the linked list is in an inconsistent state.
}
LPTSTR arg[] = { ConvertEscapeSequences(buf, g_EscapeChar, false) };
if (!AddLine(ACT_EXPRESSION, arg, UCHAR_MAX + 1)) // v1.1.17: Avoid pointing labels at this line by passing UCHAR_MAX+ for aArgc.
return FAIL; // Above already displayed the error.
if (aStatic)
{
if (!mFirstStaticLine)
mFirstStaticLine = mLastLine;
mLastStaticLine = mLastLine;
// The following is necessary if there weren't any executable lines above this static
// initializer (i.e. mFirstLine was NULL and has been set to the newly created line):
mFirstLine = script_first_line;
}
else
{
if (init_func->mJumpToLine == block_end) // This can be true only for the first initializer of a class with no base-class.
init_func->mJumpToLine = mLastLine;
// Rejoin the function's block-end (and any lines following it) to the main script.
mLastLine->mNextLine = block_end;
block_end->mPrevLine = mLastLine;
// mFirstLine should be left as it is: if it was NULL, it now contains a pointer to our
// __init function's block-begin, which is now the very first executable line in the script.
g->CurrentFunc = NULL;
}
// Restore mLastLine so that any subsequent script lines are added at the correct point.
mLastLine = script_last_line;
}
return OK;
}
Object *Script::FindClass(LPCTSTR aClassName, size_t aClassNameLength)
{
if (!aClassNameLength)
aClassNameLength = _tcslen(aClassName);
if (!aClassNameLength || aClassNameLength > MAX_CLASS_NAME_LENGTH)
return NULL;
LPTSTR cp, key;
ExprTokenType token;
Object *base_object = NULL;
TCHAR class_name[MAX_CLASS_NAME_LENGTH + 2]; // Extra +1 for '.' to simplify parsing.
// Make temporary copy which we can modify.
tmemcpy(class_name, aClassName, aClassNameLength);
class_name[aClassNameLength] = '.'; // To simplify parsing.
class_name[aClassNameLength + 1] = '\0';
// Get base variable; e.g. "MyClass" in "MyClass.MySubClass".
cp = _tcschr(class_name + 1, '.');
Var *base_var = FindVar(class_name, cp - class_name, NULL, FINDVAR_GLOBAL);
if (!base_var)
return NULL;
// Although at load time only the "Object" type can exist, dynamic_cast is used in case we're called at run-time:
if ( !(base_var->IsObject() && (base_object = dynamic_cast<Object *>(base_var->Object()))) )
return NULL;
// Even if the loop below has no iterations, it initializes 'key' to the appropriate value:
for (key = cp + 1; cp = _tcschr(key, '.'); key = cp + 1) // For each key in something like TypeVar.Key1.Key2.
{
if (cp == key)
return NULL; // ScriptError(_T("Missing name."), cp);
*cp = '\0'; // Terminate at the delimiting dot.
if (!base_object->GetItem(token, key))
return NULL;
base_object = (Object *)token.object; // See comment about Object() above.
}
return base_object;
}
Object *Object::GetUnresolvedClass(LPTSTR &aName)
// This method is only valid for mUnresolvedClass.
{
if (!mFieldCount)
return NULL;
aName = mFields[0].key.s;
return (Object *)mFields[0].object;
}
ResultType Script::ResolveClasses()
{
LPTSTR name;
Object *base = mUnresolvedClasses->GetUnresolvedClass(name);
if (!base)
return OK;
// There is at least one unresolved class.
ExprTokenType token;
if (base->GetItem(token, _T("__Class")))
{
// In this case (an object in the mUnresolvedClasses list), it is always an integer
// containing the file index and line number:
mCurrFileIndex = int(token.value_int64 >> 32);
mCombinedLineNumber = LineNumberType(token.value_int64);
}
mCurrLine = NULL;
return ScriptError(_T("Unknown class."), name);
}
#ifndef AUTOHOTKEYSC
struct FuncLibrary
{
LPTSTR path;
DWORD_PTR length;
};
Func *Script::FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool &aErrorWasShown, bool &aFileWasFound, bool aIsAutoInclude)
// Caller must ensure that aFuncName doesn't already exist as a defined function.
// If aFuncNameLength is 0, the entire length of aFuncName is used.
{
aErrorWasShown = false; // Set default for this output parameter.
aFileWasFound = false;
int i;
LPTSTR char_after_last_backslash, terminate_here;
TCHAR buf[MAX_PATH+1];
DWORD attr;
TextMem tmem;
TextMem::Buffer textbuf(NULL, 0, false);
#define FUNC_LIB_EXT _T(".ahk")
#define FUNC_LIB_EXT_LENGTH (_countof(FUNC_LIB_EXT) - 1)
#define FUNC_LOCAL_LIB _T("\\Lib\\") // Needs leading and trailing backslash.
#define FUNC_LOCAL_LIB_LENGTH (_countof(FUNC_LOCAL_LIB) - 1)
#define FUNC_USER_LIB _T("\\AutoHotkey\\Lib\\") // Needs leading and trailing backslash.
#define FUNC_USER_LIB_LENGTH (_countof(FUNC_USER_LIB) - 1)
#define FUNC_STD_LIB _T("Lib\\") // Needs trailing but not leading backslash.
#define FUNC_STD_LIB_LENGTH (_countof(FUNC_STD_LIB) - 1)
#define FUNC_LIB_COUNT 4
static FuncLibrary sLib[FUNC_LIB_COUNT] = {0};
static LPTSTR winapi;
if (!sLib[0].path) // Allocate & discover paths only upon first use because many scripts won't use anything from the library. This saves a bit of memory and performance.
{
LPVOID aDataBuf;
HRSRC hResInfo = FindResource(g_hInstance, _T("WINAPI"), MAKEINTRESOURCE(10));
DecompressBuffer(LockResource(LoadResource(g_hInstance, hResInfo)), aDataBuf, g_default_pwd);
#ifdef _UNICODE
winapi = UTF8ToWide((LPCSTR)aDataBuf);
#else
winapi = (LPTSTR)aDataBuf;
#endif
for (i = 0; i < FUNC_LIB_COUNT; ++i)
#ifdef _USRDLL
if ( !(sLib[i].path = tmalloc(MAX_PATH)) ) // When dll script is restarted, SimpleHeap is deleted and we don't want to delete static memberst
#else
if ( !(sLib[i].path = (LPTSTR) SimpleHeap::Malloc(MAX_PATH * sizeof(TCHAR))) ) // Need MAX_PATH for to allow room for appending each candidate file/function name.
#endif
return NULL; // Due to rarity, simply pass the failure back to caller.
FuncLibrary *this_lib;
// DETERMINE PATH TO "LOCAL" LIBRARY:
this_lib = sLib; // For convenience and maintainability.
this_lib->length = BIV_ScriptDir(NULL, _T(""));
if (this_lib->length < MAX_PATH-FUNC_LOCAL_LIB_LENGTH)
{
this_lib->length = BIV_ScriptDir(this_lib->path, _T(""));
_tcscpy(this_lib->path + this_lib->length, FUNC_LOCAL_LIB);
this_lib->length += FUNC_LOCAL_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "USER" LIBRARY:
this_lib++; // For convenience and maintainability.
this_lib->length = BIV_MyDocuments(this_lib->path, _T(""));
if (this_lib->length < MAX_PATH-FUNC_USER_LIB_LENGTH)
{
_tcscpy(this_lib->path + this_lib->length, FUNC_USER_LIB);
this_lib->length += FUNC_USER_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "STANDARD" LIBRARY:
this_lib++; // For convenience and maintainability.
GetModuleFileName(NULL, this_lib->path, MAX_PATH); // The full path to the currently-running AutoHotkey.exe.
char_after_last_backslash = 1 + _tcsrchr(this_lib->path, '\\'); // Should always be found, so failure isn't checked.
this_lib->length = (DWORD)(char_after_last_backslash - this_lib->path); // The length up to and including the last backslash.
if (this_lib->length < MAX_PATH-FUNC_STD_LIB_LENGTH)
{
_tcscpy(this_lib->path + this_lib->length, FUNC_STD_LIB);
this_lib->length += FUNC_STD_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "AHKPATH\Lib.lnk" LIBRARY:
this_lib++; // For convenience and maintainability.
BIV_AhkPath(this_lib->path, _T(""));
_tcscpy(_tcsrchr(this_lib->path,'\\')+1,_T("Lib.lnk"));
*(_tcsrchr(this_lib->path,'\\')+8) = '\0';
CoInitialize(NULL);
IShellLink *psl;
if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *)&psl)))
{
IPersistFile *ppf;
if (SUCCEEDED(psl->QueryInterface(IID_IPersistFile, (LPVOID *)&ppf)))
{
#ifdef UNICODE
if (SUCCEEDED(ppf->Load(this_lib->path, 0)))
#else
WCHAR wsz[MAX_PATH+1]; // +1 hasn't been explained, but is retained in case it's needed.
ToWideChar(this_lib->path, wsz, MAX_PATH+1); // Dest. size is in wchars, not bytes.
if (SUCCEEDED(ppf->Load((const WCHAR*)wsz, 0)))
#endif
{
TCHAR buf[MAX_PATH+1];
psl->GetPath(buf, MAX_PATH, NULL, SLGP_UNCPRIORITY);
_tcscpy(this_lib->path,buf);
_tcscpy(this_lib->path + _tcslen(buf),_T("\\\0"));
}
ppf->Release();
}
psl->Release();
}
CoUninitialize();
if ( !_tcsrchr(FileAttribToStr(buf, GetFileAttributes(this_lib->path)),'D') )
{
this_lib->length = 0;
*this_lib->path = '\0';
}
else
this_lib->length = _tcslen(this_lib->path);
for (i = 0; i < FUNC_LIB_COUNT; ++i)
{
attr = GetFileAttributes(sLib[i].path); // Seems to accept directories that have a trailing backslash, which is good because it simplifies the code.
if (attr == 0xFFFFFFFF || !(attr & FILE_ATTRIBUTE_DIRECTORY)) // Directory doesn't exist or it's a file vs. directory. Relies on short-circuit boolean order.
{
*sLib[i].path = '\0'; // Mark this library as disabled.
sLib[i].length = 0; //
}
}
}
// Above must ensure that all sLib[].path elements are non-NULL (but they can be "" to indicate "no library").
if (!aFuncNameLength) // Caller didn't specify, so use the entire string.
aFuncNameLength = _tcslen(aFuncName);
TCHAR *dest, *first_underscore, class_name_buf[MAX_VAR_NAME_LENGTH + 1];
LPTSTR naked_filename = aFuncName; // Set up for the first iteration.
size_t naked_filename_length = aFuncNameLength; //
for (int second_iteration = 0; second_iteration < 2; ++second_iteration)
{
for (i = 0; i < FUNC_LIB_COUNT; ++i)
{
if (!*sLib[i].path) // Library is marked disabled, so skip it.
continue;
if (sLib[i].length + naked_filename_length >= MAX_PATH-FUNC_LIB_EXT_LENGTH)
continue; // Path too long to match in this library, but try others.
dest = (LPTSTR) tmemcpy(sLib[i].path + sLib[i].length, naked_filename, naked_filename_length); // Append the filename to the library path.
_tcscpy(dest + naked_filename_length, FUNC_LIB_EXT); // Append the file extension.
attr = GetFileAttributes(sLib[i].path); // Testing confirms that GetFileAttributes() doesn't support wildcards; which is good because we want filenames containing question marks to be "not found" rather than being treated as a match-pattern.
if (attr == 0xFFFFFFFF || (attr & FILE_ATTRIBUTE_DIRECTORY)) // File doesn't exist or it's a directory. Relies on short-circuit boolean order.
continue;
aFileWasFound = true; // Indicate success for #include <lib>, which doesn't necessarily expect a function to be found.
// Since above didn't "continue", a file exists whose name matches that of the requested function.
// Before loading/including that file, set the working directory to its folder so that if it uses
// #Include, it will be able to use more convenient/intuitive relative paths. This is similar to
// the "#Include DirName" feature.
// Call SetWorkingDir() vs. SetCurrentDirectory() so that it succeeds even for a root drive like
// C: that lacks a backslash (see SetWorkingDir() for details).
terminate_here = sLib[i].path + sLib[i].length - 1; // The trailing backslash in the full-path-name to this library.
*terminate_here = '\0'; // Temporarily terminate it for use with SetWorkingDir().
SetWorkingDir(sLib[i].path); // See similar section in the #Include directive.
*terminate_here = '\\'; // Undo the termination.
if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude)
{
// For each auto-included library-file, write out two #Include lines:
// 1) Use #Include in its "change working directory" mode so that any explicit #include directives
// or FileInstalls inside the library file itself will work consistently and properly.
// 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include
// the library file itself.
// We don't directly append library files onto the main script here because:
// 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files
// might contain #Include even though it's rare).
// 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or
// subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they
// wouldn't be properly interleaved/asynchronous, but instead brought out of their library file
// and deposited separately/synchronously into the temp-include file by some new logic at the
// AutoHotkey.exe's code for the #Include directive.
// 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts.
mIncludeLibraryFunctionsThenExit->Format(_T("#Include %-0.*s\n#IncludeAgain %s\n")
, sLib[i].length, sLib[i].path, sLib[i].path);
// Now continue on normally so that our caller can continue looking for syntax errors.
}
// g->CurrentFunc is non-NULL when the function-call being resolved is inside
// a function. Save and reset it for correct behaviour in the include file:
Func *current_func = g->CurrentFunc;
g->CurrentFunc = NULL;
// Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the
// above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written.
if (!LoadIncludedFile(sLib[i].path, false, false)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included).
{
g->CurrentFunc = current_func; // Restore.
aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier.
return NULL;
}
g->CurrentFunc = current_func; // Restore.
// Now that a matching filename has been found, it seems best to stop searching here even if that
// file doesn't actually contain the requested function. This helps library authors catch bugs/typos.
// HotKeyIt, override so resource can be tried too
if (current_func = FindFunc(aFuncName, aFuncNameLength))
return current_func;
continue;
} // for() each library directory.
// Now that the first iteration is done, set up for the second one that searches by class/prefix.
// Notes about ambiguity and naming collisions:
// By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a
// match in a filename that isn't really a class, it seems inconsequential because at worst it will
// still not find the function and will then say "call to nonexistent function". In addition, the
// ability to customize which libraries are searched is planned. This would allow a publicly
// distributed script to turn off all libraries except stdlib.
if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed.
break; // All loops are done because second iteration is the last possible attempt.
naked_filename_length = first_underscore - aFuncName;
if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently).
break; // All loops are done because second iteration is the last possible attempt.
naked_filename = class_name_buf; // Point it to a buffer for use below.
tmemcpy(naked_filename, aFuncName, naked_filename_length);
naked_filename[naked_filename_length] = '\0';
} // 2-iteration for().
// HotKeyIt find library in Resource
// Since above didn't return, no match found in any library.
// Search in Resource for a library
//
// If using dll, first try find function in dll resource, then function + underscore (function_) in dll resource
// If nothing in dll resource is found, search again in main executable.
tmemcpy(class_name_buf, aFuncName, aFuncNameLength);
tmemcpy(class_name_buf + aFuncNameLength,_T(".ahk"),4);
class_name_buf[aFuncNameLength + 4] = '\0';
HRSRC lib_hResource;
BOOL aUseHinstance = true;
if (!(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB"))))
{
// Now that the resource is not found, set up for the second one that searches by class/prefix.
// Notes about ambiguity and naming collisions:
// By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a
// match in a filename that isn't really a class, it seems inconsequential because at worst it will
// still not find the function and will then say "call to nonexistent function". In addition, the
// ability to customize which libraries are searched is planned. This would allow a publicly
// distributed script to turn off all libraries except stdlib.
aUseHinstance = false;
if ( !(lib_hResource = FindResource(NULL, class_name_buf, _T("LIB"))) )
{
if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed.
goto winapi;
else
{
naked_filename_length = first_underscore - aFuncName;
if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently).
goto winapi;
tmemcpy(class_name_buf, aFuncName, naked_filename_length);
tmemcpy(class_name_buf + naked_filename_length,_T(".ahk"),4);
class_name_buf[naked_filename_length + 4] = '\0';
if ( !(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB"))) )
{
if ( !(lib_hResource = FindResource(NULL, class_name_buf, _T("LIB"))) )
goto winapi;
}
else
aUseHinstance = true;
}
}
}
// Now a resouce was found and it can be loaded
HGLOBAL hResData;
HINSTANCE ahInstance = aUseHinstance ? g_hInstance : NULL;
if ( !( (textbuf.mLength = SizeofResource(ahInstance, lib_hResource))
&& (hResData = LoadResource(ahInstance, lib_hResource))
&& (textbuf.mBuffer = LockResource(hResData)) ) )
{ // aErrorWasShown = true; // Do not display errors here
goto winapi;
}
if (*(unsigned int*)textbuf.mBuffer == 0x04034b50)
{
LPVOID aDataBuf;
DWORD aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf);
if (aSizeDeCompressed)
{
LPVOID buff = _alloca(aSizeDeCompressed); // will be freed when function returns
memmove(buff,aDataBuf,aSizeDeCompressed);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
textbuf.mLength = aSizeDeCompressed;
textbuf.mBuffer = buff;
}
}
aFileWasFound = true;
// NOTE: Ahk2Exe strips off the UTF-8 BOM.
LPTSTR resource_script = (LPTSTR)_alloca(textbuf.mLength * sizeof(TCHAR));
tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF8);
tmem.Read(resource_script, textbuf.mLength);
+ if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude)
+ {
+ // For each auto-included library-file, write out two #Include lines:
+ // 1) Use #Include in its "change working directory" mode so that any explicit #include directives
+ // or FileInstalls inside the library file itself will work consistently and properly.
+ // 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include
+ // the library file itself.
+ // We don't directly append library files onto the main script here because:
+ // 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files
+ // might contain #Include even though it's rare).
+ // 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or
+ // subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they
+ // wouldn't be properly interleaved/asynchronous, but instead brought out of their library file
+ // and deposited separately/synchronously into the temp-include file by some new logic at the
+ // AutoHotkey.exe's code for the #Include directive.
+ // 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts.
+ mIncludeLibraryFunctionsThenExit->Format(_T("%*s\n")
+ , (DWORD_PTR)_tcslen(resource_script), resource_script);
+ // Now continue on normally so that our caller can continue looking for syntax errors.
+ }
// g->CurrentFunc is non-NULL when the function-call being resolved is inside
// a function. Save and reset it for correct behaviour in the include file:
Func *current_func = g->CurrentFunc;
g->CurrentFunc = NULL;
// Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the
// above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written.
if (!LoadIncludedText(resource_script, class_name_buf)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included).
{
g->CurrentFunc = current_func; // Restore.
aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier.
return NULL;
}
g->CurrentFunc = current_func; // Restore.
return FindFunc(aFuncName, aFuncNameLength);
winapi:
TCHAR parameter[1024] = { L'#', L'D', L'l', L'l', L'I', L'm', L'p', L'o', L'r', L't', L'\\' };
memmove(¶meter[11], aFuncName, aFuncNameLength*sizeof(TCHAR));
parameter[aFuncNameLength + 11] = L',';
parameter[aFuncNameLength + 12] = '\0';
LPTSTR found;
if (found = _tcsstr(winapi, (LPTSTR)¶meter[10]))
{
parameter[10] = L',';
LPTSTR aDest = (LPTSTR)¶meter[aFuncNameLength + 12];
LPTSTR aDllName = _tcsstr(found, _T("\t")) + 1;
size_t aNameLen = _tcsstr(aDllName, _T("\\")) - aDllName + 1;
_tcsncpy(aDest, aDllName, aNameLen);
aDest = aDest + aNameLen;
_tcsncpy(aDest, found + 1, aFuncNameLength + 1);
// Override _ in the end of definition (ahk function like SendMessage, Sleep, Send, SendInput ...
if (*(aFuncName + aFuncNameLength - 1) == '_')
{
*(aDest + aFuncNameLength - 1) = ',';
*(aDest + aFuncNameLength) = '\0';
aDest = aDest + aFuncNameLength;
}
else
{
aDest = aDest + aFuncNameLength + 1;
}
for (found = _tcsstr(found, _T(",")) + 1; *found != L'\\'; found++)
{
if (*found == L'U' || *found == L'u')
{
*aDest = L'U';
aDest++;
continue;
}
else if (*found == L'z' || *found == L'Z')
{
#ifdef _UNICODE
_tcscpy(aDest, _T("USHORT"));
aDest = aDest + 6;
#else
_tcscpy(aDest, _T("UCHAR"));
aDest = aDest + 5;
#endif
}
else if (*found == L's' || *found == L'S')
{
_tcscpy(aDest, _T("STR"));
aDest = aDest + 3;
}
else if (*found == L't' || *found == L't')
{
_tcscpy(aDest, _T("PTR"));
aDest = aDest + 3;
}
else if (*found == L'a' || *found == L'A')
{
_tcscpy(aDest, _T("ASTR"));
aDest = aDest + 4;
}
else if (*found == L'w' || *found == L'W')
{
_tcscpy(aDest, _T("WSTR"));
aDest = aDest + 4;
}
else if (*found == L'x' || *found == L'X') //TCHAR
{
#ifdef _UNICODE
_tcscpy(aDest, _T("USHORT"));
aDest = aDest + 6;
#else
_tcscpy(aDest, _T("UCHAR"));
aDest = aDest + 5;
#endif
}
else if ((*found == L'i' || *found == L'I') && *(found + 1) == L'6')
{
_tcscpy(aDest, _T("INT64"));
aDest = aDest + 5;
found++;
}
else if (*found == L'i' || *found == L'I')
{
if (*(found + 1) != L'\\' || *(aDest - 1) == 'u' || *(aDest - 1) == 'U')
{ // Not default return type int, no need to define
_tcscpy(aDest, _T("INT"));
aDest = aDest + 3;
}
else // remove last , since no return type is given
{
aDest--;
}
}
else if (*found == L'h' || *found == L'H')
{
_tcscpy(aDest, _T("SHORT"));
aDest = aDest + 5;
}
else if (*found == L'c' || *found == L'C')
{
_tcscpy(aDest, _T("CHAR"));
aDest = aDest + 4;
}
else if (*found == L'f' || *found == L'F')
{
_tcscpy(aDest, _T("FLOAT"));
aDest = aDest + 5;
}
else if (*found == L'd' || *found == L'D')
{
_tcscpy(aDest, _T("DOUBLE"));
aDest = aDest + 6;
}
if (*(found + 1) == L'*' || *(found + 1) == L'p' || *(found + 1) == L'P')
{
*aDest = *found;
aDest++;
}
_tcscpy(aDest, _T(",,"));
aDest = aDest + 2;
}
*(aDest - 2) = L'\0';
+ if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude)
+ {
+ // For each auto-included library-file, write out two #Include lines:
+ // 1) Use #Include in its "change working directory" mode so that any explicit #include directives
+ // or FileInstalls inside the library file itself will work consistently and properly.
+ // 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include
+ // the library file itself.
+ // We don't directly append library files onto the main script here because:
+ // 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files
+ // might contain #Include even though it's rare).
+ // 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or
+ // subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they
+ // wouldn't be properly interleaved/asynchronous, but instead brought out of their library file
+ // and deposited separately/synchronously into the temp-include file by some new logic at the
+ // AutoHotkey.exe's code for the #Include directive.
+ // 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts.
+ mIncludeLibraryFunctionsThenExit->Format(_T("%*s\n")
+ , _tcslen(parameter), parameter);
+ // Now continue on normally so that our caller can continue looking for syntax errors.
+ }
LoadDllFunction(_tcschr(parameter, L',') + 1, parameter);
return FindFunc(aFuncName, aFuncNameLength);
}
return NULL;
}
#endif
Func *Script::FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength, int *apInsertPos) // L27: Added apInsertPos for binary-search.
// Returns the Function whose name matches aFuncName (which caller has ensured isn't NULL).
// If it doesn't exist, NULL is returned.
{
if (!aFuncNameLength) // Caller didn't specify, so use the entire string.
aFuncNameLength = _tcslen(aFuncName);
if (apInsertPos) // L27: Set default for maintainability.
*apInsertPos = -1;
// For the below, no error is reported because callers don't want that. Instead, simply return
// NULL to indicate that names that are illegal or too long are not found. If the caller later
// tries to add the function, it will get an error then:
if (aFuncNameLength > MAX_VAR_NAME_LENGTH)
return NULL;
// The following copy is made because it allows the name searching to use _tcsicmp() instead of
// strlicmp(), which close to doubles the performance. The copy includes only the first aVarNameLength
// characters from aVarName:
TCHAR func_name[MAX_VAR_NAME_LENGTH + 1];
tcslcpy(func_name, aFuncName, aFuncNameLength + 1); // +1 to convert length to size.
Func *pfunc;
// Using a binary searchable array vs a linked list speeds up dynamic function calls, on average.
int left, right, mid, result;
for (left = 0, right = mFuncCount - 1; left <= right;)
{
mid = (left + right) / 2;
result = _tcsicmp(func_name, mFunc[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance.
if (result > 0)
left = mid + 1;
else if (result < 0)
right = mid - 1;
else // Match found.
return mFunc[mid];
}
if (apInsertPos)
*apInsertPos = left;
// Since above didn't return, there is no match. See if it's a built-in function that hasn't yet
// been added to the function list.
// Set defaults to be possibly overridden below:
int min_params = 1;
int max_params = 1;
BuiltInFunctionType bif;
LPTSTR suffix = func_name + 3;
#ifndef MINIDLL
if (!_tcsnicmp(func_name, _T("LV_"), 3)) // As a built-in function, LV_* can only be a ListView function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("GetNext")))
{
bif = BIF_LV_GetNextOrCount;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("GetCount")))
{
bif = BIF_LV_GetNextOrCount;
min_params = 0; // But leave max at its default of 1.
}
else if (!_tcsicmp(suffix, _T("GetText")))
{
bif = BIF_LV_GetText;
min_params = 2;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_LV_AddInsertModify;
min_params = 0; // 0 params means append a blank row.
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Insert")))
{
bif = BIF_LV_AddInsertModify;
// Leave min_params at 1. Passing only 1 param to it means "insert a blank row".
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Modify")))
{
bif = BIF_LV_AddInsertModify; // Although it shares the same function with "Insert", it can still have its own min/max params.
min_params = 2;
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Delete")))
{
bif = BIF_LV_Delete;
min_params = 0; // Leave max at its default of 1.
}
else if (!_tcsicmp(suffix, _T("InsertCol")))
{
bif = BIF_LV_InsertModifyDeleteCol;
// Leave min_params at 1 because inserting a blank column ahead of the first column
// does not seem useful enough to sacrifice the no-parameter mode, which might have
// potential future uses.
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("ModifyCol")))
{
bif = BIF_LV_InsertModifyDeleteCol;
min_params = 0;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("DeleteCol")))
bif = BIF_LV_InsertModifyDeleteCol; // Leave min/max set to 1.
else if (!_tcsicmp(suffix, _T("SetImageList")))
{
bif = BIF_LV_SetImageList;
max_params = 2; // Leave min at 1.
}
else
return NULL;
}
else if (!_tcsnicmp(func_name, _T("TV_"), 3)) // As a built-in function, TV_* can only be a TreeView function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_TV_AddModifyDelete;
max_params = 3; // Leave min at its default of 1.
}
else if (!_tcsicmp(suffix, _T("Modify")))
{
bif = BIF_TV_AddModifyDelete;
max_params = 3; // One-parameter mode is "select specified item".
}
else if (!_tcsicmp(suffix, _T("Delete")))
{
bif = BIF_TV_AddModifyDelete;
min_params = 0;
}
else if (!_tcsicmp(suffix, _T("GetParent")) || !_tcsicmp(suffix, _T("GetChild")) || !_tcsicmp(suffix, _T("GetPrev")))
bif = BIF_TV_GetRelatedItem;
else if (!_tcsicmp(suffix, _T("GetCount")) || !_tcsicmp(suffix, _T("GetSelection")))
{
bif = BIF_TV_GetRelatedItem;
min_params = 0;
max_params = 0;
}
else if (!_tcsicmp(suffix, _T("GetNext"))) // Unlike "Prev", Next also supports 0 or 2 parameters.
{
bif = BIF_TV_GetRelatedItem;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("Get")) || !_tcsicmp(suffix, _T("GetText")))
{
bif = BIF_TV_Get;
min_params = 2;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("SetImageList")))
{
bif = BIF_TV_SetImageList;
max_params = 2; // Leave min at 1.
}
else
return NULL;
}
else if (!_tcsnicmp(func_name, _T("IL_"), 3)) // It's an ImageList function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("Create")))
{
bif = BIF_IL_Create;
min_params = 0;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("Destroy")))
{
bif = BIF_IL_Destroy; // Leave Min/Max set to 1.
}
else if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_IL_Add;
min_params = 2;
max_params = 4;
}
else
return NULL;
}
else if (!_tcsicmp(func_name, _T("SB_SetText")))
{
bif = BIF_StatusBar;
max_params = 3; // Leave min_params at its default of 1.
}
else if (!_tcsicmp(func_name, _T("SB_SetParts")))
{
bif = BIF_StatusBar;
min_params = 0;
max_params = 255; // 255 params allows for up to 256 parts, which is SB's max.
}
else if (!_tcsicmp(func_name, _T("SB_SetIcon")))
{
bif = BIF_StatusBar;
max_params = 3; // Leave min_params at its default of 1.
}
else if (!_tcsicmp(func_name, _T("StrLen")))
#else
if (!_tcsicmp(func_name, _T("StrLen")))
#endif
bif = BIF_StrLen;
else if (!_tcsicmp(func_name, _T("SubStr")))
{
bif = BIF_SubStr;
min_params = 2;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("Struct")))
{
bif = BIF_Struct;
min_params = 1;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("Sizeof")))
{
bif = BIF_sizeof;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("CriticalObject")))
{
bif = BIF_CriticalObject;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("Lock")))
{
bif = BIF_Lock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("TryLock")))
{
bif = BIF_TryLock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("UnLock")))
{
bif = BIF_UnLock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("FindFunc"))) // addFile() Naveen v8.
{
bif = BIF_FindFunc;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("FindLabel"))) // HotKeyIt v1.1.02.00
{
bif = BIF_FindLabel;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("Alias"))) // lowlevel() Naveen v9.
{
bif = BIF_Alias;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("UnZipRawMemory"))) // lowlevel() Naveen v9.
{
bif = BIF_UnZipRawMemory;
min_params = 1;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("getTokenValue"))) // lowlevel() Naveen v9.
{
bif = BIF_getTokenValue;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("CacheEnable"))) // lowlevel() Naveen v9.
{
bif = BIF_CacheEnable;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("Getvar"))) // lowlevel() Naveen v9.
{
bif = BIF_Getvar;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("Trim")) || !_tcsicmp(func_name, _T("LTrim")) || !_tcsicmp(func_name, _T("RTrim"))) // L31
{
bif = BIF_Trim;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("InStr")))
{
bif = BIF_InStr;
min_params = 2;
max_params = 5;
}
else if (!_tcsicmp(func_name, _T("RegExMatch")))
{
bif = BIF_RegEx;
min_params = 2;
max_params = 4;
}
else if (!_tcsicmp(func_name, _T("RegExReplace")))
{
bif = BIF_RegEx;
min_params = 2;
max_params = 6;
}
else if (!_tcsicmp(func_name, _T("StrSplit")))
{
bif = BIF_StrSplit;
min_params = 1;
max_params = 3;
}
else if (!_tcsnicmp(func_name, _T("GetKey"), 6))
{
suffix = func_name + 6;
if (!_tcsicmp(suffix, _T("State")))
{
bif = BIF_GetKeyState;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("Name")) || !_tcsicmp(suffix, _T("VK")) || !_tcsicmp(suffix, _T("SC")))
bif = BIF_GetKeyName;
else
return NULL;
}
else if (!_tcsicmp(func_name, _T("Asc")))
bif = BIF_Asc;
else if (!_tcsicmp(func_name, _T("Chr")))
bif = BIF_Chr;
else if (!_tcsicmp(func_name, _T("Format")))
{
bif = BIF_Format;
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(func_name, _T("StrGet")))
{
bif = BIF_StrGetPut;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("StrPut")))
{
bif = BIF_StrGetPut;
max_params = 4;
}
else if (!_tcsicmp(func_name, _T("NumGet")))
{
bif = BIF_NumGet;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("NumPut")))
{
bif = BIF_NumPut;
min_params = 2;
max_params = 4;
}
else if (!_tcsicmp(func_name, _T("IsLabel")))
bif = BIF_IsLabel;
else if (!_tcsicmp(func_name, _T("Func")))
bif = BIF_Func;
else if (!_tcsicmp(func_name, _T("IsFunc")))
bif = BIF_IsFunc;
else if (!_tcsicmp(func_name, _T("IsByRef")))
bif = BIF_IsByRef;
#ifdef ENABLE_DLLCALL
else if (!_tcsicmp(func_name, _T("DllCall")))
{
bif = BIF_DllCall;
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
#endif
else if (!_tcsicmp(func_name, _T("ResourceLoadLibrary")))
{
bif = BIF_ResourceLoadLibrary;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("MemoryLoadLibrary")))
{
bif = BIF_MemoryLoadLibrary;
min_params = 1;
max_params = 5;
}
else if (!_tcsicmp(func_name, _T("MemoryGetProcAddress")))
{
bif = BIF_MemoryGetProcAddress;
min_params = 2;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("MemoryFreeLibrary")))
{
bif = BIF_MemoryFreeLibrary;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("MemoryFindResource")))
{
bif = BIF_MemoryFindResource;
min_params = 3;
max_params = 4;
}
else if (!_tcsicmp(func_name, _T("MemorySizeOfResource")))
{
bif = BIF_MemorySizeOfResource;
min_params = 2;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("MemoryLoadResource")))
{
bif = BIF_MemoryLoadResource;
min_params = 2;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("MemoryLoadString")))
{
bif = BIF_MemoryLoadString;
min_params = 2;
max_params = 5;
}
else if (!_tcsicmp(func_name, _T("DynaCall")))
{
bif = BIF_DynaCall;
min_params = 0;
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(func_name, _T("VarSetCapacity")))
{
bif = BIF_VarSetCapacity;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("FileExist")))
bif = BIF_FileExist;
else if (!_tcsicmp(func_name, _T("WinExist")) || !_tcsicmp(func_name, _T("WinActive")))
{
bif = BIF_WinExistActive;
min_params = 0;
max_params = 4;
}
else if (!_tcsicmp(func_name, _T("Round")))
{
bif = BIF_Round;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("Floor")) || !_tcsicmp(func_name, _T("Ceil")))
bif = BIF_FloorCeil;
else if (!_tcsicmp(func_name, _T("Mod")))
{
bif = BIF_Mod;
min_params = 2;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("Abs")))
bif = BIF_Abs;
else if (!_tcsicmp(func_name, _T("Sin")))
bif = BIF_Sin;
else if (!_tcsicmp(func_name, _T("Cos")))
bif = BIF_Cos;
else if (!_tcsicmp(func_name, _T("Tan")))
bif = BIF_Tan;
else if (!_tcsicmp(func_name, _T("ASin")) || !_tcsicmp(func_name, _T("ACos")))
bif = BIF_ASinACos;
else if (!_tcsicmp(func_name, _T("ATan")))
bif = BIF_ATan;
else if (!_tcsicmp(func_name, _T("Exp")))
bif = BIF_Exp;
else if (!_tcsicmp(func_name, _T("Sqrt")) || !_tcsicmp(func_name, _T("Log")) || !_tcsicmp(func_name, _T("Ln")))
bif = BIF_SqrtLogLn;
else if (!_tcsicmp(func_name, _T("OnMessage")))
{
bif = BIF_OnMessage;
max_params = 3; // Leave min at 1.
// By design, scripts that use OnMessage are persistent by default. Doing this here
// also allows WinMain() to later detect whether this script should become #SingleInstance.
// Note: Don't directly change g_AllowOnlyOneInstance here in case the remainder of the
// script-loading process comes across any explicit uses of #SingleInstance, which would
// override the default set here.
g_persistent = true;
}
#ifdef ENABLE_REGISTERCALLBACK
else if (!_tcsicmp(func_name, _T("RegisterCallback")))
{
bif = BIF_RegisterCallback;
max_params = 4; // Leave min_params at 1.
}
#endif
else if (!_tcsicmp(func_name, _T("IsObject"))) // L31
{
bif = BIF_IsObject;
max_params = 10000; // Leave min_params at 1.
}
else if (!_tcsnicmp(func_name, _T("Obj"), 3)) // L31: See script_object.cpp for details.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("ect"))) // i.e. "Object"
{
bif = BIF_ObjCreate;
|
tinku99/ahkdll
|
8762efcd5ed397d403112679b81e567e71162156
|
Added A_IsMini and fixed getvar() to return alias pointer
|
diff --git a/source/lowlevelbif.cpp b/source/lowlevelbif.cpp
index d859c03..16be9ef 100644
--- a/source/lowlevelbif.cpp
+++ b/source/lowlevelbif.cpp
@@ -1,133 +1,136 @@
#include "stdafx.h" // pre-compiled headers
#include "globaldata.h" // for access to many global vars
#include "application.h" // for MsgSleep()
#include "exports.h"
#include "script.h"
BIF_DECL(BIF_FindFunc) // Added in Nv8.
{
// Set default return value in case of early return.
aResultToken.symbol = SYM_INTEGER ;
aResultToken.marker = _T("");
// Get the first arg, which is the string used as the source of the extraction. Call it "findfunc" for clarity.
TCHAR funcname_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result.
LPTSTR funcname = TokenToString(*aParam[0], funcname_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float).
int funcname_length = (int)EXPR_TOKEN_LENGTH(aParam[0], funcname);
aResultToken.value_int64 = (__int64)ahkFindFunc(funcname);
return;
}
BIF_DECL(BIF_FindLabel) // HotKeyIt Added in 1.1.02.00
{
// Set default return value in case of early return.
aResultToken.symbol = SYM_INTEGER ;
aResultToken.marker = _T("");
// Get the first arg, which is the string used as the source of the extraction. Call it "findfunc" for clarity.
TCHAR labelname_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result.
LPTSTR labelname = TokenToString(*aParam[0], labelname_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float).
int labelname_length = (int)EXPR_TOKEN_LENGTH(aParam[0], labelname);
aResultToken.value_int64 = (__int64)ahkFindLabel(labelname);
return;
}
BIF_DECL(BIF_Getvar)
{
switch(aParam[0]->symbol)
{
case SYM_STRING:
case SYM_OPERAND:
if (!(TokenToInt64(*aParam[0])))
aResultToken.value_int64 = (__int64)g_script.FindOrAddVar(aParam[0]->marker);
break;
case SYM_VAR:
- aResultToken.value_int64 = (__int64)aParam[0]->var;
+ if (aParam[0]->var->mType == VAR_ALIAS)
+ aResultToken.value_int64 = (__int64)aParam[0]->var->mAliasFor;
+ else
+ aResultToken.value_int64 = (__int64)aParam[0]->var;
break;
default:
aResultToken.value_int64 = 0;
}
}
BIF_DECL(BIF_Alias)
{
ExprTokenType &aParam0 = *aParam[0];
ExprTokenType &aParam1 = *aParam[1];
aResultToken.symbol = SYM_STRING;
aResultToken.marker = _T("");
if (aParam0.symbol == SYM_VAR)
{
Var &var = *aParam0.var;
UINT_PTR len = 0;
if (aParamCount == 2)
switch (aParam1.symbol)
{
case SYM_VAR:
len = (UINT_PTR)(aParam[1]->var->mType == VAR_ALIAS ? aParam1.var->ResolveAlias() : aParam1.var);
break;
case SYM_INTEGER:
// HotKeyIt added to accept var pointer
len = (UINT_PTR)aParam[1]->value_int64;
break;
// HotKeyIt H10 added to accept dynamic text and also when value is returned by ahkgetvar in AutoHotkey.dll
case SYM_STRING:
case SYM_OPERAND:
len = (UINT_PTR)ATOI64(aParam1.marker);
}
var.mType = len ? VAR_ALIAS : VAR_NORMAL;
var.mByteLength = len;
if (len && var.mAliasFor->HasObject()){
var.mObject = var.mAliasFor->Object();
var.mObject->AddRef();
}
}
}
BIF_DECL(BIF_CacheEnable)
{
if (aParam[0]->symbol == SYM_VAR)
{
(aParam[0]->var->mType == VAR_ALIAS ? aParam[0]->var->mAliasFor : aParam[0]->var)
->mAttrib &= ~VAR_ATTRIB_CACHE_DISABLED;
}
}
BIF_DECL(BIF_getTokenValue)
{
ExprTokenType *token = aParam[0];
if (token->symbol != SYM_INTEGER)
return;
token = (ExprTokenType*) token->value_int64;
if (token->symbol == SYM_VAR)
{
Var &var = *token->var;
VarAttribType cache_attrib = var.mAttrib & (VAR_ATTRIB_HAS_VALID_INT64 | VAR_ATTRIB_HAS_VALID_DOUBLE);
if (cache_attrib)
{
aResultToken.symbol = (SymbolType) (cache_attrib >> 4);
aResultToken.value_int64 = var.mContentsInt64;
}
else if (var.mAttrib & VAR_ATTRIB_OBJECT)
{
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = var.mObject;
}
else
{
aResultToken.symbol = SYM_OPERAND;
aResultToken.marker = var.mCharContents;
}
}
else
{
aResultToken.symbol = token->symbol;
aResultToken.value_int64 = token->value_int64;
}
if (aResultToken.symbol == SYM_OBJECT)
aResultToken.object->AddRef();
}
\ No newline at end of file
diff --git a/source/script.cpp b/source/script.cpp
index 9e89ab3..b25bf3c 100644
--- a/source/script.cpp
+++ b/source/script.cpp
@@ -11487,1024 +11487,1025 @@ Var *Script::FindVar(LPTSTR aVarName, size_t aVarNameLength, int *apInsertPos, i
else if (result < 0)
right = mid - 1;
else // Match found.
return var[mid];
}
}
}
else // !search_static && !search_local
{
var = mVar;
right = mVarCount - 1;
// Binary search:
for (left = 0; left <= right;) // "right" was already initialized above.
{
mid = (left + right) / 2;
result = _tcsicmp(var_name, var[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance.
if (result > 0)
left = mid + 1;
else if (result < 0)
right = mid - 1;
else // Match found.
return var[mid];
}
if (!search_local)
{
var = mLazyVar;
right = mLazyVarCount - 1;
}
if (var) // There is a lazy list to search (and even if the list is empty, left must be reset to 0 below).
{
// Binary search:
for (left = 0; left <= right;) // "right" was already initialized above.
{
mid = (left + right) / 2;
result = _tcsicmp(var_name, var[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance.
if (result > 0)
left = mid + 1;
else if (result < 0)
right = mid - 1;
else // Match found.
return var[mid];
}
}
}
// Since above didn't return, no match was found and "left" always contains the position where aVarName
// should be inserted to keep the list sorted. The item is always inserted into the lazy list unless
// there is no lazy list.
// Set the output parameter, if present:
if (apInsertPos) // Caller wants this value even if we'll be resorting to searching the global list below.
*apInsertPos = left; // This is the index a newly inserted item should have to keep alphabetical order.
if (apIsLocal) // Its purpose is to inform caller of type it would have been in case we don't find a match.
*apIsLocal = search_local;
// Since no match was found, if this is a local fall back to searching the list of globals at runtime
// if the caller didn't insist on a particular type:
if (search_local && aScope == FINDVAR_DEFAULT)
{
// In this case, callers want to fall back to globals when a local wasn't found. However,
// they want the insertion (if our caller will be doing one) to insert according to the
// current assume-mode. Therefore, if the mode is assume-global, pass the apIsLocal
// and apInsertPos variables to FindVar() so that it will update them to be global.
if (g.CurrentFunc->mDefaultVarType == VAR_DECLARE_GLOBAL)
return FindVar(aVarName, aVarNameLength, apInsertPos, FINDVAR_GLOBAL, apIsLocal);
// v1: Each *dynamic* variable reference may resolve to a global if one exists.
if (mIsReadyToExecute)
return FindVar(aVarName, aVarNameLength, NULL, FINDVAR_GLOBAL);
// Otherwise, caller only wants globals which are declared in *this* function:
for (int i = 0; i < g.CurrentFunc->mGlobalVarCount; ++i)
if (!_tcsicmp(var_name, g.CurrentFunc->mGlobalVar[i]->mName)) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance.
return g.CurrentFunc->mGlobalVar[i];
// As a last resort, check for a super-global:
Var *gvar = FindVar(aVarName, aVarNameLength, NULL, FINDVAR_GLOBAL, NULL);
if (gvar && gvar->IsSuperGlobal())
return gvar;
}
// Otherwise, since above didn't return:
return NULL; // No match.
}
Var *Script::AddVar(LPTSTR aVarName, size_t aVarNameLength, int aInsertPos, int aScope)
// Returns the address of the new variable or NULL on failure.
// Caller must ensure that g->CurrentFunc!=NULL whenever aIsLocal!=0.
// Caller must ensure that aVarName isn't NULL and that this isn't a duplicate variable name.
// In addition, it has provided aInsertPos, which is the insertion point so that the list stays sorted.
// Finally, aIsLocal has been provided to indicate which list, global or local, should receive this
// new variable, as well as the type of local variable. (See the declaration of VAR_LOCAL etc.)
{
if (!*aVarName) // Should never happen, so just silently indicate failure.
return NULL;
if (!aVarNameLength) // Caller didn't specify, so use the entire string.
aVarNameLength = _tcslen(aVarName);
if (aVarNameLength > MAX_VAR_NAME_LENGTH)
{
ScriptError(_T("Variable name too long."), aVarName);
return NULL;
}
// Make a temporary copy that includes only the first aVarNameLength characters from aVarName:
TCHAR var_name[MAX_VAR_NAME_LENGTH + 1];
tcslcpy(var_name, aVarName, aVarNameLength + 1); // See explanation above. +1 to convert length to size.
if (!Var::ValidateName(var_name))
// Above already displayed error for us. This can happen at loadtime or runtime (e.g. StringSplit).
return NULL;
bool aIsLocal = (aScope & VAR_LOCAL);
// Not necessary or desirable to add built-in variables to a function's list of locals. Always keep
// built-in vars in the global list for efficiency and to keep them out of ListVars. Note that another
// section at loadtime displays an error for any attempt to explicitly declare built-in variables as
// either global or local.
void *var_type = GetVarType(var_name);
if (aIsLocal && (var_type != (void *)VAR_NORMAL || !_tcsicmp(var_name, _T("ErrorLevel")))) // Attempt to create built-in variable as local.
{
if ( !(aScope & VAR_LOCAL_FUNCPARAM) ) // It's not a UDF's parameter, so fall back to the global built-in variable of this name rather than displaying an error.
return FindOrAddVar(var_name, aVarNameLength, FINDVAR_GLOBAL); // Force find-or-create of global.
else // (aIsLocal & VAR_LOCAL_FUNCPARAM), which means "this is a local variable and a function's parameter".
{
ScriptError(_T("Illegal parameter name."), aVarName); // Short message since so rare.
return NULL;
}
}
// Allocate some dynamic memory to pass to the constructor:
LPTSTR new_name = SimpleHeap::Malloc(var_name, aVarNameLength);
if (!new_name)
// It already displayed the error for us.
return NULL;
// Below specifically tests for VAR_LOCAL and excludes other non-zero values/flags:
// VAR_LOCAL_FUNCPARAM should not be made static.
// VAR_LOCAL_STATIC is already static.
// VAR_DECLARED indicates mDefaultVarType is irrelevant.
if (aScope == VAR_LOCAL && g->CurrentFunc->mDefaultVarType == VAR_DECLARE_STATIC)
// v1.0.48: Lexikos: Current function is assume-static, so set static attribute.
aScope |= VAR_LOCAL_STATIC;
bool aIsStatic = aIsLocal ? (aScope & VAR_LOCAL_STATIC) : false;
Var *the_new_var = new Var(new_name, var_type, aScope);
if (the_new_var == NULL)
{
ScriptError(ERR_OUTOFMEM);
return NULL;
}
// If there's a lazy var list, aInsertPos provided by the caller is for it, so this new variable
// always gets inserted into that list because there's always room for one more (because the
// previously added variable would have purged it if it had reached capacity).
Var **lazy_var = aIsStatic ? g->CurrentFunc->mStaticLazyVar : (aIsLocal ? g->CurrentFunc->mLazyVar : mLazyVar);
int &lazy_var_count = aIsStatic ? g->CurrentFunc->mStaticLazyVarCount : (aIsLocal ? g->CurrentFunc->mLazyVarCount : mLazyVarCount); // Used further below too.
if (lazy_var)
{
if (aInsertPos != lazy_var_count) // Need to make room at the indicated position for this variable.
memmove(lazy_var + aInsertPos + 1, lazy_var + aInsertPos, (lazy_var_count - aInsertPos) * sizeof(Var *));
//else both are zero or the item is being inserted at the end of the list, so it's easy.
lazy_var[aInsertPos] = the_new_var;
++lazy_var_count;
// In a testing creating between 200,000 and 400,000 variables, using a size of 1000 vs. 500 improves
// the speed by 17%, but when you subtract out the binary search time (leaving only the insert time),
// the increase is more like 34%. But there is a diminishing return after that: Going to 2000 only
// gains 20%, and to 4000 only gains an addition 10%. Therefore, to conserve memory in functions that
// have so many variables that the lazy list is used, a good trade-off seems to be 2000 (8 KB of memory)
// per function that needs it.
#define MAX_LAZY_VARS 2000 // Don't make this larger than 90000 without altering the incremental increase of alloc_count further below.
if (lazy_var_count < MAX_LAZY_VARS) // The lazy list hasn't yet reached capacity, so no need to merge it into the main list.
return the_new_var;
}
// Since above didn't return, either there is no lazy list or the lazy list is full and needs to be
// merged into the main list.
// Create references to whichever variable list (local or global) is being acted upon. These
// references simplify the code:
Var **&var = aIsStatic ? g->CurrentFunc->mStaticVar : (aIsLocal ? g->CurrentFunc->mVar : mVar); // This needs to be a ref. too in case it needs to be realloc'd.
int &var_count = aIsStatic ? g->CurrentFunc->mStaticVarCount : (aIsLocal ? g->CurrentFunc->mVarCount : mVarCount);
int &var_count_max = aIsStatic ? g->CurrentFunc->mStaticVarCountMax : (aIsLocal ? g->CurrentFunc->mVarCountMax : mVarCountMax);
int alloc_count;
// Since the above would have returned if the lazy list is present but not yet full, if the left side
// of the OR below is false, it also means that lazy_var is NULL. Thus lazy_var==NULL is implicit for the
// right side of the OR:
if ((lazy_var && var_count + MAX_LAZY_VARS > var_count_max) || var_count == var_count_max)
{
// Increase by orders of magnitude each time because realloc() is probably an expensive operation
// in terms of hurting performance. So here, a little bit of memory is sacrificed to improve
// the expected level of performance for scripts that use hundreds of thousands of variables.
if (!var_count_max)
alloc_count = aIsLocal ? 100 : 1000; // 100 conserves memory since every function needs such a block, and most functions have much fewer than 100 local variables.
else if (var_count_max < 1000)
alloc_count = 1000;
else if (var_count_max < 9999) // Making this 9999 vs. 10000 allows an exact/whole number of lazy_var blocks to fit into main indices between 10000 and 99999
alloc_count = 9999;
else if (var_count_max < 100000)
{
alloc_count = 100000;
// This is also the threshold beyond which the lazy list is used to accelerate performance.
// Create the permanent lazy list:
Var **&lazy_var = aIsStatic ? g->CurrentFunc->mStaticLazyVar : (aIsLocal ? g->CurrentFunc->mLazyVar : mLazyVar);
if ( !(lazy_var = (Var **)malloc(MAX_LAZY_VARS * sizeof(Var *))) )
{
ScriptError(ERR_OUTOFMEM);
return NULL;
}
}
else if (var_count_max < 1000000)
alloc_count = 1000000;
else
alloc_count = var_count_max + 1000000; // i.e. continue to increase by 4MB (1M*4) each time.
Var **temp = (Var **)realloc(var, alloc_count * sizeof(Var *)); // If passed NULL, realloc() will do a malloc().
if (!temp)
{
ScriptError(ERR_OUTOFMEM);
return NULL;
}
var = temp;
var_count_max = alloc_count;
}
if (!lazy_var)
{
if (aInsertPos != var_count) // Need to make room at the indicated position for this variable.
memmove(var + aInsertPos + 1, var + aInsertPos, (var_count - aInsertPos) * sizeof(Var *));
//else both are zero or the item is being inserted at the end of the list, so it's easy.
var[aInsertPos] = the_new_var;
++var_count;
return the_new_var;
}
//else the variable was already inserted into the lazy list, so the above is not done.
// Since above didn't return, the lazy list is not only present, but full because otherwise it
// would have returned higher above.
// Since the lazy list is now at its max capacity, merge it into the main list (if the
// main list was at capacity, this section relies upon the fact that the above already
// increased its capacity by an amount far larger than the number of items contained
// in the lazy list).
// LAZY LIST: Although it's not nearly as good as hashing (which might be implemented in the future,
// though it would be no small undertaking since it affects so many design aspects, both load-time
// and runtime for scripts), this method of accelerating insertions into a binary search array is
// enormously beneficial because it improves the scalability of binary-search by two orders
// of magnitude (from about 100,000 variables to at least 5M). Credit for the idea goes to Lazlo.
// DETAILS:
// The fact that this merge operation is so much faster than total work required
// to insert each one into the main list is the whole reason for having the lazy
// list. In other words, the large memmove() that would otherwise be required
// to insert each new variable into the main list is completely avoided. Large memmove()s
// become dramatically more costly than small ones because apparently they can't fit into
// the CPU cache, so the operation would take hundreds or even thousands of times longer
// depending on the speed difference between main memory and CPU cache. But above and
// beyond the CPU cache issue, the lazy sorting method results in vastly less memory
// being moved than would have been required without it, so even if the CPU doesn't have
// a cache, the lazy list method vastly increases performance for scripts that have more
// than 100,000 variables, allowing at least 5 million variables to be created without a
// dramatic reduction in performance.
LPTSTR target_name;
Var **insert_pos, **insert_pos_prev;
int i, left, right, mid;
// Append any items from the lazy list to the main list that are alphabetically greater than
// the last item in the main list. Above has already ensured that the main list is large enough
// to accept all items in the lazy list.
for (i = lazy_var_count - 1, target_name = var[var_count - 1]->mName
; i > -1 && _tcsicmp(target_name, lazy_var[i]->mName) < 0
; --i);
// Above is a self-contained loop.
// Now do a separate loop to append (in the *correct* order) anything found above.
for (int j = i + 1; j < lazy_var_count; ++j) // Might have zero iterations.
var[var_count++] = lazy_var[j];
lazy_var_count = i + 1; // The number of items that remain after moving out those that qualified.
// This will have zero iterations if the above already moved them all:
for (insert_pos = var + var_count, i = lazy_var_count - 1; i > -1; --i)
{
// Modified binary search that relies on the fact that caller has ensured a match will never
// be found in the main list for each item in the lazy list:
for (target_name = lazy_var[i]->mName, left = 0, right = (int)(insert_pos - var - 1); left <= right;)
{
mid = (left + right) / 2;
if (_tcsicmp(target_name, var[mid]->mName) > 0) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance.
left = mid + 1;
else // it must be < 0 because caller has ensured it can't be equal (i.e. that there will be no match)
right = mid - 1;
}
// Now "left" contains the insertion point and is known to be less than var_count due to a previous
// set of loops above. Make a gap there large enough to hold all items because that allows a
// smaller total amount of memory to be moved by shifting the gap to the left in the main list,
// gradually filling it as we go:
insert_pos_prev = insert_pos; // "prev" is the now the position of the beginning of the gap, but the gap is about to be shifted left by moving memory right.
insert_pos = var + left; // This is where it *would* be inserted if we weren't doing the accelerated merge.
memmove(insert_pos + i + 1, insert_pos, (insert_pos_prev - insert_pos) * sizeof(Var *));
var[left + i] = lazy_var[i]; // Now insert this item at the far right side of the gap just created.
}
var_count += lazy_var_count;
lazy_var_count = 0; // Indicate that the lazy var list is now empty.
return the_new_var;
}
void *Script::GetVarType(LPTSTR aVarName)
{
// Convert to lowercase to help performance a little (it typically only helps loadtime performance because
// this function is rarely called during script-runtime).
TCHAR lowercase[MAX_VAR_NAME_LENGTH + 1];
tcslcpy(lowercase, aVarName, _countof(lowercase)); // Caller should have ensured it fits, but call strlcpy() for maintainability.
CharLower(lowercase);
// Above: CharLower() is smaller in code size than strlwr(), but CharLower uses the OS locale and strlwr uses
// the setlocal() locale (which is always the same if setlocal() is never called). However, locale
// differences shouldn't affect the cases checked below; some evidence of this is at MSDN:
// "CharLower always maps uppercase I to lowercase I, even when the current language is Turkish or Azeri."
if (lowercase[0] != 'a' || lowercase[1] != '_') // This check helps average-case performance.
{
if ( !_tcscmp(lowercase, _T("true"))
|| !_tcscmp(lowercase, _T("false"))
|| !_tcscmp(lowercase, _T("null"))) return BIV_True_False_Null;
if (!_tcscmp(lowercase, _T("clipboard"))) return (void *)VAR_CLIPBOARD;
if (!_tcscmp(lowercase, _T("clipboardall"))) return (void *)VAR_CLIPBOARDALL;
if (!_tcscmp(lowercase, _T("comspec"))) return BIV_ComSpec; // Lacks an "A_" prefix for backward compatibility with pre-NoEnv scripts and also it's easier to type & remember.
if (!_tcscmp(lowercase, _T("programfiles"))) return BIV_SpecialFolderPath; // v1.0.43.08: Added to ease the transition to #NoEnv.
// Otherwise:
return (void *)VAR_NORMAL;
}
// Otherwise, lowercase begins with "a_", so it's probably one of the built-in variables.
LPTSTR lower = lowercase + 2;
// Keeping the most common ones near the top helps performance a little.
if (!_tcscmp(lower, _T("index"))) return BIV_LoopIndex; // A short name since it's typed so often.
if ( !_tcscmp(lower, _T("mmmm")) // Long name of month.
|| !_tcscmp(lower, _T("mmm")) // 3-char abbrev. month name.
|| !_tcscmp(lower, _T("dddd")) // Name of weekday, e.g. Sunday
|| !_tcscmp(lower, _T("ddd")) ) // Abbrev., e.g. Sun
return BIV_MMM_DDD;
if ( !_tcscmp(lower, _T("yyyy"))
|| !_tcscmp(lower, _T("year")) // Same as above.
|| !_tcscmp(lower, _T("mm")) // 01 thru 12
|| !_tcscmp(lower, _T("mon")) // Same
|| !_tcscmp(lower, _T("dd")) // 01 thru 31
|| !_tcscmp(lower, _T("mday")) // Same
|| !_tcscmp(lower, _T("wday"))
|| !_tcscmp(lower, _T("yday"))
|| !_tcscmp(lower, _T("yweek"))
|| !_tcscmp(lower, _T("hour"))
|| !_tcscmp(lower, _T("min"))
|| !_tcscmp(lower, _T("sec"))
|| !_tcscmp(lower, _T("msec")) )
return BIV_DateTime;
if (!_tcscmp(lower, _T("tickcount"))) return BIV_TickCount;
if ( !_tcscmp(lower, _T("now"))
|| !_tcscmp(lower, _T("nowutc"))) return BIV_Now;
if (!_tcscmp(lower, _T("workingdir"))) return BIV_WorkingDir;
if (!_tcscmp(lower, _T("scriptname"))) return BIV_ScriptName;
if (!_tcscmp(lower, _T("scriptdir"))) return BIV_ScriptDir;
if (!_tcscmp(lower, _T("scriptfullpath"))) return BIV_ScriptFullPath;
if (!_tcscmp(lower, _T("scripthwnd"))) return BIV_ScriptHwnd;
if (!_tcscmp(lower, _T("linenumber"))) return BIV_LineNumber;
if (!_tcscmp(lower, _T("linefile"))) return BIV_LineFile;
//#ifdef AUTOHOTKEYSC
if (!_tcscmp(lower, _T("iscompiled"))) return BIV_IsCompiled;
//#endif
if (!_tcscmp(lower, _T("isunicode"))) return BIV_IsUnicode;
if (!_tcscmp(lower, _T("ptrsize"))) return BIV_PtrSize;
if ( !_tcscmp(lower, _T("batchlines"))
|| !_tcscmp(lower, _T("numbatchlines"))) return BIV_BatchLines;
if (!_tcscmp(lower, _T("titlematchmode"))) return BIV_TitleMatchMode;
if (!_tcscmp(lower, _T("titlematchmodespeed"))) return BIV_TitleMatchModeSpeed;
if (!_tcscmp(lower, _T("detecthiddenwindows"))) return BIV_DetectHiddenWindows;
if (!_tcscmp(lower, _T("detecthiddentext"))) return BIV_DetectHiddenText;
if (!_tcscmp(lower, _T("autotrim"))) return BIV_AutoTrim;
if (!_tcscmp(lower, _T("stringcasesense"))) return BIV_StringCaseSense;
if (!_tcscmp(lower, _T("formatinteger"))) return BIV_FormatInteger;
if (!_tcscmp(lower, _T("formatfloat"))) return BIV_FormatFloat;
if (!_tcscmp(lower, _T("keydelay"))) return BIV_KeyDelay;
if (!_tcscmp(lower, _T("windelay"))) return BIV_WinDelay;
if (!_tcscmp(lower, _T("controldelay"))) return BIV_ControlDelay;
if (!_tcscmp(lower, _T("mousedelay"))) return BIV_MouseDelay;
if (!_tcscmp(lower, _T("defaultmousespeed"))) return BIV_DefaultMouseSpeed;
if (!_tcscmp(lower, _T("ispaused"))) return BIV_IsPaused;
if (!_tcscmp(lower, _T("iscritical"))) return BIV_IsCritical;
if (!_tcscmp(lower, _T("fileencoding"))) return BIV_FileEncoding;
if (!_tcscmp(lower, _T("regview"))) return BIV_RegView;
#ifndef MINIDLL
if (!_tcscmp(lower, _T("issuspended"))) return BIV_IsSuspended;
if (!_tcscmp(lower, _T("iconhidden"))) return BIV_IconHidden;
if (!_tcscmp(lower, _T("icontip"))) return BIV_IconTip;
if (!_tcscmp(lower, _T("iconfile"))) return BIV_IconFile;
if (!_tcscmp(lower, _T("iconnumber"))) return BIV_IconNumber;
#endif
if (!_tcscmp(lower, _T("exitreason"))) return BIV_ExitReason;
if (!_tcscmp(lower, _T("ostype"))) return BIV_OSType;
if (!_tcscmp(lower, _T("osversion"))) return BIV_OSVersion;
if (!_tcscmp(lower, _T("is64bitos"))) return BIV_Is64bitOS;
if (!_tcscmp(lower, _T("language"))) return BIV_Language;
if ( !_tcscmp(lower, _T("computername"))
|| !_tcscmp(lower, _T("username"))) return BIV_UserName_ComputerName;
if (!_tcscmp(lower, _T("windir"))) return BIV_WinDir;
if (!_tcscmp(lower, _T("temp"))) return BIV_Temp; // Debatably should be A_TempDir, but brevity seemed more popular with users, perhaps for heavy uses of the temp folder.
if (!_tcscmp(lower, _T("mydocuments"))) return BIV_MyDocuments;
if ( !_tcscmp(lower, _T("programfiles"))
|| !_tcscmp(lower, _T("appdata"))
|| !_tcscmp(lower, _T("appdatacommon"))
|| !_tcscmp(lower, _T("desktop"))
|| !_tcscmp(lower, _T("desktopcommon"))
|| !_tcscmp(lower, _T("startmenu"))
|| !_tcscmp(lower, _T("startmenucommon"))
|| !_tcscmp(lower, _T("programs"))
|| !_tcscmp(lower, _T("programscommon"))
|| !_tcscmp(lower, _T("startup"))
|| !_tcscmp(lower, _T("startupcommon")))
return BIV_SpecialFolderPath;
if (!_tcscmp(lower, _T("isadmin"))) return BIV_IsAdmin;
if (!_tcscmp(lower, _T("cursor"))) return BIV_Cursor;
if ( !_tcscmp(lower, _T("caretx"))
|| !_tcscmp(lower, _T("carety"))) return BIV_Caret;
if ( !_tcscmp(lower, _T("screenwidth"))
|| !_tcscmp(lower, _T("screenheight"))) return BIV_ScreenWidth_Height;
if (!_tcsncmp(lower, _T("ipaddress"), 9))
{
lower += 9;
return (*lower >= '1' && *lower <= '4'
&& !lower[1]) // Make sure has only one more character rather than none or several (e.g. A_IPAddress1abc should not be match).
? BIV_IPAddress
: (void *)VAR_NORMAL; // Otherwise it can't be a match for any built-in variable.
}
if (!_tcsncmp(lower, _T("loop"), 4))
{
lower += 4;
if (!_tcscmp(lower, _T("readline"))) return BIV_LoopReadLine;
if (!_tcscmp(lower, _T("field"))) return BIV_LoopField;
if (!_tcsncmp(lower, _T("file"), 4))
{
lower += 4;
if (!_tcscmp(lower, _T("name"))) return BIV_LoopFileName;
if (!_tcscmp(lower, _T("shortname"))) return BIV_LoopFileShortName;
if (!_tcscmp(lower, _T("ext"))) return BIV_LoopFileExt;
if (!_tcscmp(lower, _T("dir"))) return BIV_LoopFileDir;
if (!_tcscmp(lower, _T("fullpath"))) return BIV_LoopFileFullPath;
if (!_tcscmp(lower, _T("longpath"))) return BIV_LoopFileLongPath;
if (!_tcscmp(lower, _T("shortpath"))) return BIV_LoopFileShortPath;
if (!_tcscmp(lower, _T("attrib"))) return BIV_LoopFileAttrib;
if ( !_tcscmp(lower, _T("timemodified"))
|| !_tcscmp(lower, _T("timecreated"))
|| !_tcscmp(lower, _T("timeaccessed"))) return BIV_LoopFileTime;
if ( !_tcscmp(lower, _T("size"))
|| !_tcscmp(lower, _T("sizekb"))
|| !_tcscmp(lower, _T("sizemb"))) return BIV_LoopFileSize;
// Otherwise, it can't be a match for any built-in variable:
return (void *)VAR_NORMAL;
}
if (!_tcsncmp(lower, _T("reg"), 3))
{
lower += 3;
if (!_tcscmp(lower, _T("type"))) return BIV_LoopRegType;
if (!_tcscmp(lower, _T("key"))) return BIV_LoopRegKey;
if (!_tcscmp(lower, _T("subkey"))) return BIV_LoopRegSubKey;
if (!_tcscmp(lower, _T("name"))) return BIV_LoopRegName;
if (!_tcscmp(lower, _T("timemodified"))) return BIV_LoopRegTimeModified;
// Otherwise, it can't be a match for any built-in variable:
return (void *)VAR_NORMAL;
}
}
if (!_tcscmp(lower, _T("thisfunc"))) return BIV_ThisFunc;
if (!_tcscmp(lower, _T("thislabel"))) return BIV_ThisLabel;
#ifndef MINIDLL
if (!_tcscmp(lower, _T("thismenuitem"))) return BIV_ThisMenuItem;
if (!_tcscmp(lower, _T("thismenuitempos"))) return BIV_ThisMenuItemPos;
if (!_tcscmp(lower, _T("thismenu"))) return BIV_ThisMenu;
if (!_tcscmp(lower, _T("thishotkey"))) return BIV_ThisHotkey;
if (!_tcscmp(lower, _T("priorhotkey"))) return BIV_PriorHotkey;
if (!_tcscmp(lower, _T("timesincethishotkey"))) return BIV_TimeSinceThisHotkey;
if (!_tcscmp(lower, _T("timesincepriorhotkey"))) return BIV_TimeSincePriorHotkey;
if (!_tcscmp(lower, _T("endchar"))) return BIV_EndChar;
#endif
if (!_tcscmp(lower, _T("lasterror"))) return BIV_LastError;
if (!_tcscmp(lower, _T("globalstruct"))) return BIV_GlobalStruct;
if (!_tcscmp(lower, _T("scriptstruct"))) return BIV_ScriptStruct;
if (!_tcscmp(lower, _T("modulehandle"))) return BIV_ModuleHandle;
if (!_tcscmp(lower, _T("memorymodule"))) return BIV_MemoryModule;
if (!_tcscmp(lower, _T("isdll"))) return BIV_IsDll;
+ if (!_tcscmp(lower, _T("ismini"))) return BIV_IsMini;
if (!_tcsncmp(lower, _T("coordmode"), 9)) return BIV_CoordMode;
if (!_tcscmp(lower, _T("eventinfo"))) return BIV_EventInfo; // It's called "EventInfo" vs. "GuiEventInfo" because it applies to non-Gui events such as OnClipboardChange.
#ifndef MINIDLL
if (!_tcscmp(lower, _T("guicontrol"))) return BIV_GuiControl;
if ( !_tcscmp(lower, _T("guicontrolevent")) // v1.0.36: A_GuiEvent was added as a synonym for A_GuiControlEvent because it seems unlikely that A_GuiEvent will ever be needed for anything:
|| !_tcscmp(lower, _T("guievent"))) return BIV_GuiEvent;
if ( !_tcscmp(lower, _T("gui"))
|| !_tcscmp(lower, _T("guiwidth"))
|| !_tcscmp(lower, _T("guiheight"))
|| !_tcscmp(lower, _T("guix")) // Naming: Brevity seems more a benefit than would A_GuiEventX's improved clarity.
|| !_tcscmp(lower, _T("guiy"))) return BIV_Gui; // These can be overloaded if a GuiMove label or similar is ever needed.
if (!_tcscmp(lower, _T("priorkey"))) return BIV_PriorKey;
if (!_tcscmp(lower, _T("screendpi"))) return BIV_ScreenDPI;
#endif
if (!_tcscmp(lower, _T("timeidle"))) return BIV_TimeIdle;
if (!_tcscmp(lower, _T("timeidlephysical"))) return BIV_TimeIdlePhysical;
if ( !_tcscmp(lower, _T("space"))
|| !_tcscmp(lower, _T("tab"))) return BIV_Space_Tab;
if (!_tcscmp(lower, _T("ahkversion"))) return BIV_AhkVersion;
if (!_tcscmp(lower, _T("ahkpath"))) return BIV_AhkPath;
if (!_tcscmp(lower, _T("ahkdir"))) return BIV_AhkDir;
if (!_tcscmp(lower, _T("dllpath"))) return BIV_DllPath;
if (!_tcscmp(lower, _T("dlldir"))) return BIV_DllDir;
// Since above didn't return:
return (void *)VAR_NORMAL;
}
WinGroup *Script::FindGroup(LPTSTR aGroupName, bool aCreateIfNotFound)
// Caller must ensure that aGroupName isn't NULL. But if it's the empty string, NULL is returned.
// Returns the Group whose name matches aGroupName. If it doesn't exist, it is created if aCreateIfNotFound==true.
// Thread-safety: This function is thread-safe (except when called with aCreateIfNotFound==true) even when
// the main thread happens to be calling AddGroup() and changing the linked list while it's being traversed here
// by the hook thread. However, any subsequent changes to this function or AddGroup() must be carefully reviewed.
{
if (!*aGroupName)
{
if (aCreateIfNotFound)
// An error message must be shown in this case since or caller is about to
// exit the current script thread (and we don't want it to happen silently).
ScriptError(_T("Blank group name."));
return NULL;
}
for (WinGroup *group = mFirstGroup; group != NULL; group = group->mNextGroup)
if (!_tcsicmp(group->mName, aGroupName)) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance.
return group; // Match found.
// Otherwise, no match found, so create a new group.
if (!aCreateIfNotFound || AddGroup(aGroupName) != OK)
return NULL;
return mLastGroup;
}
ResultType Script::AddGroup(LPTSTR aGroupName)
// Returns OK or FAIL.
// The caller must already have verified that this isn't a duplicate group.
// This function is not thread-safe because it adds an entry to the quasi-global list of window groups.
// In addition, if this function is being called by one thread while another thread is calling FindGroup(),
// the thread-safety notes in FindGroup() apply.
{
size_t aGroupName_length = _tcslen(aGroupName);
if (aGroupName_length > MAX_VAR_NAME_LENGTH)
return ScriptError(_T("Group name too long."), aGroupName);
if (!Var::ValidateName(aGroupName, DISPLAY_NO_ERROR)) // Seems best to use same validation as var names.
return ScriptError(_T("Illegal group name."), aGroupName);
LPTSTR new_name = SimpleHeap::Malloc(aGroupName, aGroupName_length);
if (!new_name)
return FAIL; // It already displayed the error for us.
// The precise method by which the follows steps are done should be thread-safe even if
// some other thread calls FindGroup() in the middle of the operation. But any changes
// must be carefully reviewed:
WinGroup *the_new_group = new WinGroup(new_name);
if (the_new_group == NULL)
return ScriptError(ERR_OUTOFMEM);
if (mFirstGroup == NULL)
mFirstGroup = the_new_group;
else
mLastGroup->mNextGroup = the_new_group;
// This must be done after the above:
mLastGroup = the_new_group;
return OK;
}
Line *Script::PreparseBlocks(Line *aStartingLine, bool aFindBlockEnd, Line *aParentLine)
// aFindBlockEnd should be true, only when this function is called
// by itself. The end of this function relies upon this definition.
// Will return NULL to the top-level caller if there's an error, or if
// mLastLine is NULL (i.e. the script is empty).
{
// Not thread-safe, so this can only parse one script at a time.
// Not a problem for the foreseeable future:
static int nest_level; // Level zero is the outermost one: outside all blocks.
static bool abort;
if (!aParentLine)
{
// We were called from outside, not recursively, so init these. This is
// very important if this function is ever to be called from outside
// more than once, even though it isn't currently:
nest_level = 0;
abort = false;
}
int i;
DerefType *deref;
// Don't check aStartingLine here at top: only do it at the bottom
// for its differing return values.
for (Line *line = aStartingLine; line;)
{
// Check if any of each arg's derefs are function calls. If so, do some validation and
// preprocessing to set things up for better runtime performance:
for (i = 0; i < line->mArgc; ++i) // For each arg.
{
ArgStruct &this_arg = line->mArg[i]; // For performance and convenience.
// Exclude the derefs of output and input vars from consideration, since they can't
// be function calls:
if (!this_arg.is_expression) // For now, only expressions are capable of calling functions. If ever change this, might want to add a check here for this_arg.type != ARG_TYPE_NORMAL (for performance).
continue;
if (this_arg.deref) // No function-calls are present because the expression contains neither variables nor function calls.
{
for (deref = this_arg.deref; deref->marker; ++deref) // For each deref.
{
if (!deref->is_function)
continue;
if ( !(deref->func = FindFunc(deref->marker, deref->length)) )
{
#ifndef AUTOHOTKEYSC
bool error_was_shown, file_was_found;
if ( !(deref->func = FindFuncInLibrary(deref->marker, deref->length, error_was_shown, file_was_found, true)) )
{
abort = true; // So that the caller doesn't also report an error.
// When above already displayed the proximate cause of the error, it's usually
// undesirable to show the cascade effects of that error in a second dialog:
return error_was_shown ? NULL : line->PreparseError(ERR_NONEXISTENT_FUNCTION, deref->marker);
}
#else
abort = true;
return line->PreparseError(ERR_NONEXISTENT_FUNCTION, deref->marker);
#endif
}
// L31: Parameter counting and validation was previously done in this section,
// but is now handled by ExpressionToPostfix.
} // for each deref of this arg
} // if (this_arg.deref)
if (!line->ExpressionToPostfix(this_arg)) // At this stage, this_arg.is_expression is known to be true. Doing this here, after the script has been loaded, might improve the compactness/adjacent-ness of the compiled expressions in memory, which might improve performance due to CPU caching.
{
abort = true; // So that the caller doesn't also report an error.
return NULL; // The function above already displayed the error msg.
}
} // for each arg of this line
// All lines in our recursion layer are assigned to the block that the caller specified:
if (line->mParentLine == NULL) // i.e. don't do it if it's already "owned" by an IF or ELSE.
line->mParentLine = aParentLine; // Can be NULL.
#define ACT_IS_BLOCK_OWNER(act) (ACT_IS_IF_OR_ELSE_OR_LOOP(act) || (act) == ACT_TRY || (act) == ACT_CATCH || (act) == ACT_FINALLY)
if (ACT_IS_BLOCK_OWNER(line->mActionType))
{
// In this case, the loader should have already ensured that line->mNextLine is not NULL.
if (line->mNextLine->mActionType == ACT_BLOCK_BEGIN && line->mNextLine->mAttribute == ATTR_TRUE)
{
abort = true; // So that the caller doesn't also report an error.
return line->PreparseError(_T("Improper line below this.")); // Short message since so rare. A function must not be defined directly below an IF/ELSE/LOOP because runtime evaluation won't handle it properly.
}
if (line->mActionType == ACT_FOR)
{
ASSERT(line->mArgc == 3);
// Now that this FOR's expression has been pre-parsed, exclude it from mArgc so that ExpandArgs()
// won't evaluate it -- PerformLoopFor() needs to call ExpandExpression() directly in order to
// receive the object reference which is the result of the expression.
line->mArgc--;
}
// Make the line immediately following each ELSE, IF or LOOP be enclosed by that stmt.
// This is done to make it illegal for a Goto or Gosub to jump into a deeper layer,
// such as in this example:
// #y::
// ifwinexist, pad
// {
// goto, label1
// ifwinexist, pad
// label1:
// ; With or without the enclosing block, the goto would still go to an illegal place
// ; in the below, resulting in an "unexpected else" error:
// {
// msgbox, ifaction
// } ; not necessary to make this line enclosed by the if because labels can't point to it?
// else
// msgbox, elseaction
// }
// return
line->mNextLine->mParentLine = line;
// Go onto the IF's or ELSE's action in case it too is an IF, rather than skipping over it:
line = line->mNextLine;
continue;
}
switch (line->mActionType)
{
case ACT_BLOCK_BEGIN:
// Some insane limit too large to ever likely be exceeded, yet small enough not
// to be a risk of stack overflow when recursing in ExecUntil(). Mostly, this is
// here to reduce the chance of a program crash if a binary file, a corrupted file,
// or something unexpected has been loaded as a script when it shouldn't have been.
// Update: Increased the limit from 100 to 1000 so that large "else if" ladders
// can be constructed. Going much larger than 1000 seems unwise since ExecUntil()
// will have to recurse for each nest-level, possibly resulting in stack overflow
// if things get too deep:
if (nest_level > 1000)
{
abort = true; // So that the caller doesn't also report an error.
return line->PreparseError(_T("Nesting too deep.")); // Short msg since so rare.
}
// Since the current convention is to store the line *after* the
// BLOCK_END as the BLOCK_BEGIN's related line, that line can
// be legitimately NULL if this block's BLOCK_END is the last
// line in the script. So it's up to the called function
// to report an error if it never finds a BLOCK_END for us.
// UPDATE: The design requires that we do it here instead:
++nest_level;
if (NULL == (line->mRelatedLine = PreparseBlocks(line->mNextLine, 1, line)))
if (abort) // the above call already reported the error.
return NULL;
else
{
abort = true; // So that the caller doesn't also report an error.
return line->PreparseError(ERR_MISSING_CLOSE_BRACE);
}
--nest_level;
// The convention is to have the BLOCK_BEGIN's related_line
// point to the line *after* the BLOCK_END.
line->mRelatedLine = line->mRelatedLine->mNextLine; // Might be NULL now.
// Otherwise, since any blocks contained inside this one would already
// have been handled by the recursion in the above call, continue searching
// from the end of this block:
line = line->mRelatedLine; // If NULL, the loop-condition will catch it.
break;
case ACT_BLOCK_END:
// Return NULL (failure) if the end was found but we weren't looking for one
// (i.e. it's an orphan). Otherwise return the line after the block_end line,
// which will become the caller's mRelatedLine. UPDATE: Return the
// END_BLOCK line itself so that the caller can differentiate between
// a NULL due to end-of-script and a NULL caused by an error:
return aFindBlockEnd ? line // Doesn't seem necessary to set abort to true.
: line->PreparseError(ERR_MISSING_OPEN_BRACE);
default: // Continue line-by-line.
line = line->mNextLine;
} // switch()
} // for each line
// End of script has been reached. <line> is now NULL so don't attempt to dereference it.
// If we were still looking for an EndBlock to match up with a begin, that's an error.
// Don't report the error here because we don't know which begin-block is waiting
// for an end (the caller knows and must report the error). UPDATE: Must report
// the error here (see comments further above for explanation). UPDATE #2: Changed
// it again: Now we let the caller handle it again:
if (aFindBlockEnd)
//return mLastLine->PreparseError("The script ends while a block is still open (missing }).");
return NULL;
// If no error, return something non-NULL to indicate success to the top-level caller.
// We know we're returning to the top-level caller because aFindBlockEnd is only true
// when we're recursed, and in that case the above would have returned. Thus,
// we're not recursed upon reaching this line:
return mLastLine;
}
Line *Script::PreparseIfElse(Line *aStartingLine, ExecUntilMode aMode, AttributeType aLoopType)
// Zero is the default for aMode, otherwise:
// Will return NULL to the top-level caller if there's an error, or if
// mLastLine is NULL (i.e. the script is empty).
// Note: This function should be called with aMode == ONLY_ONE_LINE
// only when aStartingLine's ActionType is something recursable such
// as IF and BEGIN_BLOCK. Otherwise, it won't return after only one line.
{
static BOOL sInFunctionBody = FALSE; // Improves loadtime performance by allowing IsOutsideAnyFunctionBody() to be called only when necessary.
// Don't check aStartingLine here at top: only do it at the bottom
// for it's differing return values.
Line *line_temp;
AttributeType loop_type = aLoopType;
for (Line *line = aStartingLine; line != NULL;)
{
if ( ACT_IS_IF(line->mActionType)
|| line->mActionType == ACT_LOOP
|| line->mActionType == ACT_WHILE
|| line->mActionType == ACT_FOR
|| line->mActionType == ACT_TRY )
{
// ActionType is an IF or a LOOP or a TRY.
line_temp = line->mNextLine; // line_temp is now this IF's or LOOP's or TRY's action-line.
// Update: Below is commented out because it's now impossible (since all scripts end in ACT_EXIT):
//if (line_temp == NULL) // This is an orphan IF/LOOP (has no action-line) at the end of the script.
// return line->PreparseError(_T("Q")); // Placeholder. Formerly "This if-statement or loop has no action."
// Other things rely on this check having been done, such as "if (line->mRelatedLine != NULL)":
#define IS_BAD_ACTION_LINE(l) ((l)->mActionType == ACT_ELSE || (l)->mActionType == ACT_BLOCK_END || (l)->mActionType == ACT_CATCH || (l)->mActionType == ACT_FINALLY)
if (IS_BAD_ACTION_LINE(line_temp))
return line->PreparseError(ERR_EXPECTED_BLOCK_OR_ACTION);
// Lexikos: This section once maintained separate variables for file-pattern, registry, file-reading
// and parsing loops. The intention seemed to be to validate certain commands such as FileAppend
// differently depending on whether they're contained within a qualifying type of loop (even if some
// other type of loop lies in between). However, that validation apparently wasn't implemented,
// and implementing it now seems unnecessary. Doing so would also remove a useful capability:
//
// Loop, Read, %InputFile%, %OutputFile%
// {
// MyFunc(A_LoopReadLine)
// }
// MyFunc(line) {
// ... do some processing on %line% ...
// FileAppend, %line% ; This line could be considered an error, though it works in practice.
// }
//
// Check if the IF's action-line is something we want to recurse. UPDATE: Always
// recurse because other line types, such as Goto and Gosub, need to be preparsed
// by this function even if they are the single-line actions of an IF or an ELSE.
// Recurse this line rather than the next because we want the called function to
// recurse again if this line is a ACT_BLOCK_BEGIN or is itself an IF.
line_temp = PreparseIfElse(line_temp, ONLY_ONE_LINE, line->mAttribute ? line->mAttribute : loop_type);
// If not end-of-script or error, line_temp is now either:
// 1) If this if's/loop's action was a BEGIN_BLOCK: The line after the end of the block.
// 2) If this if's/loop's action was another IF or LOOP:
// a) the line after that if's else's action; or (if it doesn't have one):
// b) the line after that if's/loop's action
// 3) If this if's/loop's action was some single-line action: the line after that action.
// In all of the above cases, line_temp is now the line where we
// would expect to find an ELSE for this IF, if it has one.
// Now the above has ensured that line_temp is this line's else, if it has one.
// Note: line_temp will be NULL if the end of the script has been reached.
// UPDATE: That can't happen now because all scripts end in ACT_EXIT:
if (line_temp == NULL) // Error or end-of-script was reached.
return NULL;
// Seems best to keep this check for maintainability because changes to other checks can impact
// whether this check will ever be "true":
if (line->mRelatedLine != NULL)
return line->PreparseError(_T("Q")); // Placeholder since it shouldn't happen. Formerly "This if-statement or LOOP unexpectedly already had an ELSE or end-point."
// Set it to the else's action, rather than the else itself, since the else itself
// is never needed during execution. UPDATE: No, instead set it to the ELSE itself
// (if it has one) since we jump here at runtime when the IF is finished (whether
// it's condition was true or false), thus skipping over any nested IF's that
// aren't in blocks beneath it. If there's no ELSE, the below value serves as
// the jumppoint we go to when the if-statement is finished. Example:
// if x
// if y
// if z
// action1
// else
// action2
// action3
// x's jumppoint should be action3 so that all the nested if's
// under the first one can be skipped after the "if x" line is recursively
// evaluated. Because of this behavior, all IFs will have a related line
// with the possibly exception of the very last if-statement in the script
// (which is possible only if the script doesn't end in a Return or Exit).
line->mRelatedLine = line_temp; // Even if <line> is a LOOP and line_temp and else?
// Even if aMode == ONLY_ONE_LINE, an IF and its ELSE count as a single
// statement (one line) due to its very nature (at least for this purpose),
// so always continue on to evaluate the IF's ELSE, if present:
if (line_temp->mActionType == ACT_ELSE)
{
if (line->mActionType == ACT_LOOP || line->mActionType == ACT_WHILE || line->mActionType == ACT_FOR || line->mActionType == ACT_TRY)
{
// this can't be our else, so let the caller handle it.
if (aMode != ONLY_ONE_LINE)
// This ELSE was encountered while sequentially scanning the contents
// of a block or at the outermost nesting layer. More thought is required
// to verify this is correct. UPDATE: This check is very old and I haven't
// found a case that can produce it yet, but until proven otherwise its safer
// to assume it's possible.
return line_temp->PreparseError(ERR_ELSE_WITH_NO_IF);
// Let the caller handle this else, since it can't be ours:
return line_temp;
}
// Fix for v1.1.09: Correct the line hierarchy for ELSE nested in an IF/ELSE/LOOP
// without braces. This is needed for named loops and perhaps other things.
line_temp->mParentLine = line->mParentLine;
// Now use line vs. line_temp to hold the new values, so that line_temp
// stays as a marker to the ELSE line itself:
line = line_temp->mNextLine; // Set it to the else's action line.
// Update: The following is now impossible because all scripts end in ACT_EXIT.
// Thus, it's commented out:
//if (line == NULL) // An else with no action.
// return line_temp->PreparseError(_T("Q")); // Placeholder since impossible. Formerly "This ELSE has no action."
if (IS_BAD_ACTION_LINE(line))
return line_temp->PreparseError(ERR_EXPECTED_BLOCK_OR_ACTION);
// Assign to line rather than line_temp:
line = PreparseIfElse(line, ONLY_ONE_LINE, aLoopType);
if (line == NULL)
return NULL; // Error or end-of-script.
// Set this ELSE's jumppoint. This is similar to the jumppoint set for
// an ELSEless IF, so see related comments above:
line_temp->mRelatedLine = line;
}
else if (line_temp->mActionType == ACT_UNTIL)
{
if (line->mActionType != ACT_LOOP && line->mActionType != ACT_FOR) // Doesn't seem useful to allow it with WHILE?
{
// This is similar to the section above, so see there for comments.
if (aMode != ONLY_ONE_LINE)
return line_temp->PreparseError(ERR_UNTIL_WITH_NO_LOOP);
return line_temp;
}
// Continue processing *after* UNTIL.
line = line_temp->mNextLine;
}
else if (line_temp->mActionType == ACT_CATCH)
{
if (line->mActionType != ACT_TRY)
{
// Again, this is similar to the section above, so see there for comments.
if (aMode != ONLY_ONE_LINE)
return line_temp->PreparseError(ERR_CATCH_WITH_NO_TRY);
return line_temp;
}
line_temp->mParentLine = line->mParentLine;
line = line_temp->mNextLine;
if (IS_BAD_ACTION_LINE(line))
return line_temp->PreparseError(ERR_EXPECTED_BLOCK_OR_ACTION);
// Assign to line rather than line_temp:
line = PreparseIfElse(line, ONLY_ONE_LINE, aLoopType);
if (line == NULL)
return NULL; // Error or end-of-script.
// Set this CATCH's jumppoint.
line_temp->mRelatedLine = line;
// Detect and fix FINALLY.
if (line->mActionType == ACT_FINALLY)
{
line->mParentLine = line_temp->mParentLine;
Line* temp = line->mNextLine;
if (IS_BAD_ACTION_LINE(temp))
return line->PreparseError(ERR_EXPECTED_BLOCK_OR_ACTION);
// Preparse FINALLY block - obscure the loop type so that attempts to use
// break/continue to exit the FINALLY block are caught at load time.
line->mRelatedLine = PreparseIfElse(temp, ONLY_ONE_LINE, ATTR_OBSCURE(aLoopType));
if (!line->mRelatedLine)
return NULL; // Error or end-of-script.
line = line->mRelatedLine;
}
}
else if (line_temp->mActionType == ACT_FINALLY)
{
// This code section can only be triggered by try..finally (with no catch)
if (line->mActionType != ACT_TRY)
{
// Again, this is similar to the section above, so see there for comments.
if (aMode != ONLY_ONE_LINE)
return line_temp->PreparseError(ERR_FINALLY_WITH_NO_PRECEDENT);
return line_temp;
}
line_temp->mParentLine = line->mParentLine;
line = line_temp->mNextLine;
if (IS_BAD_ACTION_LINE(line))
return line_temp->PreparseError(ERR_EXPECTED_BLOCK_OR_ACTION);
// Assign to line rather than line_temp:
line = PreparseIfElse(line, ONLY_ONE_LINE, ATTR_OBSCURE(aLoopType)); // ATTR_OBSCURE: see above for more details.
if (line == NULL)
return NULL; // Error or end-of-script.
// Set this TRY's jumppoint.
line_temp->mRelatedLine = line;
}
else // line doesn't have an else, so just continue processing from line_temp's position
line = line_temp;
// Both cases above have ensured that line is now the first line beyond the
// scope of the if-statement and that of any ELSE it may have.
if (aMode == ONLY_ONE_LINE) // Return the next unprocessed line to the caller.
return line;
// Otherwise, continue processing at line's new location:
continue;
} // ActionType is "IF".
// Since above didn't continue, do the switch:
LPTSTR line_raw_arg1 = LINE_RAW_ARG1; // Resolve only once to help reduce code size.
LPTSTR line_raw_arg2 = LINE_RAW_ARG2; //
switch (line->mActionType)
{
case ACT_BLOCK_BEGIN:
if (line->mAttribute == ATTR_TRUE) // This is the opening brace of a function definition.
sInFunctionBody = TRUE; // Must be set only for the above condition because functions can of course contain types of blocks other than the function's own block.
line = PreparseIfElse(line->mNextLine, UNTIL_BLOCK_END, line->mAttribute ? 0 : aLoopType); // mAttribute usage: don't consider a function's body to be inside the loop, since it can be called from outside.
// "line" is now either NULL due to an error, or the location of the END_BLOCK itself.
if (line == NULL)
return NULL; // Error.
break;
case ACT_BLOCK_END:
if (line->mAttribute == ATTR_TRUE) // This is the closing brace of a function definition.
sInFunctionBody = FALSE; // Must be set only for the above condition because functions can of course contain types of blocks other than the function's own block.
#ifdef _DEBUG
if (aMode == ONLY_ONE_LINE)
diff --git a/source/script.h b/source/script.h
index 684f5eb..39b50e9 100644
--- a/source/script.h
+++ b/source/script.h
@@ -2451,754 +2451,755 @@ struct GuiControlOptionsType
SYSTEMTIME sys_time[2]; // Needs to support 2 elements for MONTHCAL's multi/range mode.
SYSTEMTIME sys_time_range[2];
DWORD gdtr, gdtr_range; // Used in connection with sys_time and sys_time_range.
ResultType redraw; // Whether the state of WM_REDRAW should be changed.
TCHAR password_char; // When zeroed, indicates "use default password" for an edit control with the password style.
bool range_changed;
bool color_changed; // To discern when a control has been put back to the default color. [v1.0.26]
bool start_new_section;
bool use_theme; // v1.0.32: Provides the means for the window's current setting of mUseTheme to be overridden.
bool listview_no_auto_sort; // v1.0.44: More maintainable and frees up GUI_CONTROL_ATTRIB_ALTBEHAVIOR for other uses.
ATOM customClassAtom;
};
LRESULT CALLBACK GuiWindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK TabWindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam);
class GuiType
{
public:
#define GUI_STANDARD_WIDTH_MULTIPLIER 15 // This times font size = width, if all other means of determining it are exhausted.
#define GUI_STANDARD_WIDTH DPIScale(GUI_STANDARD_WIDTH_MULTIPLIER * sFont[mCurrentFontIndex].point_size)
// Update for v1.0.21: Reduced it to 8 vs. 9 because 8 causes the height each edit (with the
// default style) to exactly match that of a Combo or DropDownList. This type of spacing seems
// to be what other apps use too, and seems to make edits stand out a little nicer:
#define GUI_CTL_VERTICAL_DEADSPACE DPIScale(8)
#define PROGRESS_DEFAULT_THICKNESS DPIScale(2 * sFont[mCurrentFontIndex].point_size)
LPTSTR mName;
HWND mHwnd, mStatusBarHwnd;
HWND mOwner; // The window that owns this one, if any. Note that Windows provides no way to change owners after window creation.
// Control IDs are higher than their index in the array by the below amount. This offset is
// necessary because windows that behave like dialogs automatically return IDOK and IDCANCEL in
// response to certain types of standard actions:
GuiIndexType mControlCount;
GuiIndexType mControlCapacity; // How many controls can fit into the current memory size of mControl.
GuiControlType *mControl; // Will become an array of controls when the window is first created.
GuiIndexType mDefaultButtonIndex; // Index vs. pointer is needed for some things.
ULONG mReferenceCount; // For keeping this structure in memory during execution of the Gui's labels.
Label *mLabelForClose, *mLabelForEscape, *mLabelForSize, *mLabelForDropFiles, *mLabelForContextMenu;
bool mLabelForCloseIsRunning, mLabelForEscapeIsRunning, mLabelForSizeIsRunning; // DropFiles doesn't need one of these.
bool mLabelsHaveBeenSet;
DWORD mStyle, mExStyle; // Style of window.
bool mInRadioGroup; // Whether the control currently being created is inside a prior radio-group.
bool mUseTheme; // Whether XP theme and styles should be applied to the parent window and subsequently added controls.
TCHAR mDelimiter; // The default field delimiter when adding items to ListBox, DropDownList, ListView, etc.
GuiControlType *mCurrentListView, *mCurrentTreeView; // The ListView and TreeView upon which the LV/TV functions operate.
int mCurrentFontIndex;
COLORREF mCurrentColor; // The default color of text in controls.
COLORREF mBackgroundColorWin; // The window's background color itself.
COLORREF mBackgroundColorCtl; // Background color for controls.
HBRUSH mBackgroundBrushWin; // Brush corresponding to mBackgroundColorWin.
HBRUSH mBackgroundBrushCtl; // Brush corresponding to mBackgroundColorCtl.
HDROP mHdrop; // Used for drag and drop operations.
HICON mIconEligibleForDestruction; // The window's icon, which can be destroyed when the window is destroyed if nothing else is using it.
HICON mIconEligibleForDestructionSmall; // L17: A window may have two icons: ICON_SMALL and ICON_BIG.
HACCEL mAccel; // Keyboard accelerator table.
int mMarginX, mMarginY, mPrevX, mPrevY, mPrevWidth, mPrevHeight, mMaxExtentRight, mMaxExtentDown
, mSectionX, mSectionY, mMaxExtentRightSection, mMaxExtentDownSection;
LONG mMinWidth, mMinHeight, mMaxWidth, mMaxHeight;
TabControlIndexType mTabControlCount;
TabControlIndexType mCurrentTabControlIndex; // Which tab control of the window.
TabIndexType mCurrentTabIndex;// Which tab of a tab control is currently the default for newly added controls.
bool mGuiShowHasNeverBeenDone, mFirstActivation, mShowIsInProgress, mDestroyWindowHasBeenCalled;
bool mControlWidthWasSetByContents; // Whether the most recently added control was auto-width'd to fit its contents.
bool mUsesDPIScaling; // Whether the GUI uses DPI scaling.
#define MAX_GUI_FONTS 200 // v1.0.44.14: Increased from 100 to 200 due to feedback that 100 wasn't enough. But to alleviate memory usage, the array is now allocated upon first use.
static FontType *sFont; // An array of structs, allocated upon first use.
static int sFontCount;
static HWND sTreeWithEditInProgress; // Needed because TreeView's edit control for label-editing conflicts with IDOK (default button).
// Don't overload new and delete operators in this case since we want to use real dynamic memory
// (since GUIs can be destroyed and recreated, over and over).
// Keep the default destructor to avoid entering the "Law of the Big Three": If your class requires a
// copy constructor, copy assignment operator, or a destructor, then it very likely will require all three.
GuiType() // Constructor
: mName(NULL), mHwnd(NULL), mStatusBarHwnd(NULL), mControlCount(0), mControlCapacity(0)
, mDefaultButtonIndex(-1), mLabelForClose(NULL), mLabelForEscape(NULL), mLabelForSize(NULL)
, mLabelForDropFiles(NULL), mLabelForContextMenu(NULL), mReferenceCount(1)
, mLabelForCloseIsRunning(false), mLabelForEscapeIsRunning(false), mLabelForSizeIsRunning(false)
, mLabelsHaveBeenSet(false), mUsesDPIScaling(true)
// The styles DS_CENTER and DS_3DLOOK appear to be ineffectual in this case.
// Also note that WS_CLIPSIBLINGS winds up on the window even if unspecified, which is a strong hint
// that it should always be used for top level windows across all OSes. Usenet posts confirm this.
// Also, it seems safer to have WS_POPUP under a vague feeling that it seems to apply to dialog
// style windows such as this one, and the fact that it also allows the window's caption to be
// removed, which implies that POPUP windows are more flexible than OVERLAPPED windows.
, mStyle(WS_POPUP|WS_CLIPSIBLINGS|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX) // WS_CLIPCHILDREN (doesn't seem helpful currently)
, mExStyle(0) // This and the above should not be used once the window has been created since they might get out of date.
, mInRadioGroup(false), mUseTheme(true), mOwner(NULL), mDelimiter('|')
, mCurrentFontIndex(FindOrCreateFont()) // Must call this in constructor to ensure sFont array is never NULL while a GUI object exists. Omit params to tell it to find or create DEFAULT_GUI_FONT.
, mCurrentListView(NULL), mCurrentTreeView(NULL)
, mTabControlCount(0), mCurrentTabControlIndex(MAX_TAB_CONTROLS), mCurrentTabIndex(0)
, mCurrentColor(CLR_DEFAULT)
, mBackgroundColorWin(CLR_DEFAULT), mBackgroundBrushWin(NULL)
, mBackgroundColorCtl(CLR_DEFAULT), mBackgroundBrushCtl(NULL)
, mHdrop(NULL), mIconEligibleForDestruction(NULL), mIconEligibleForDestructionSmall(NULL)
, mAccel(NULL)
, mMarginX(COORD_UNSPECIFIED), mMarginY(COORD_UNSPECIFIED) // These will be set when the first control is added.
, mPrevX(0), mPrevY(0)
, mPrevWidth(0), mPrevHeight(0) // Needs to be zero for first control to start off at right offset.
, mMaxExtentRight(0), mMaxExtentDown(0)
, mSectionX(COORD_UNSPECIFIED), mSectionY(COORD_UNSPECIFIED)
, mMaxExtentRightSection(COORD_UNSPECIFIED), mMaxExtentDownSection(COORD_UNSPECIFIED)
, mMinWidth(COORD_UNSPECIFIED), mMinHeight(COORD_UNSPECIFIED)
, mMaxWidth(COORD_UNSPECIFIED), mMaxHeight(COORD_UNSPECIFIED)
, mGuiShowHasNeverBeenDone(true), mFirstActivation(true), mShowIsInProgress(false)
, mDestroyWindowHasBeenCalled(false), mControlWidthWasSetByContents(false)
{
// The array of controls is left uninitialized to catch bugs. Each control's attributes should be
// fully populated when it is created.
//ZeroMemory(mControl, sizeof(mControl));
}
static ResultType Destroy(GuiType &gui);
static void DestroyIconsIfUnused(HICON ahIcon, HICON ahIconSmall); // L17: Renamed function and added parameter to also handle the window's small icon.
ResultType Create();
void AddRef();
void Release();
void SetLabels(LPTSTR aLabelPrefix);
static void UpdateMenuBars(HMENU aMenu);
ResultType AddControl(GuiControls aControlType, LPTSTR aOptions, LPTSTR aText);
ResultType ParseOptions(LPTSTR aOptions, bool &aSetLastFoundWindow, ToggleValueType &aOwnDialogs, Var *&aHwndVar);
void GetNonClientArea(LONG &aWidth, LONG &aHeight);
void GetTotalWidthAndHeight(LONG &aWidth, LONG &aHeight);
ResultType ControlParseOptions(LPTSTR aOptions, GuiControlOptionsType &aOpt, GuiControlType &aControl
, GuiIndexType aControlIndex = -1); // aControlIndex is not needed upon control creation.
void ControlInitOptions(GuiControlOptionsType &aOpt, GuiControlType &aControl);
void ControlAddContents(GuiControlType &aControl, LPTSTR aContent, int aChoice, GuiControlOptionsType *aOpt = NULL);
ResultType Show(LPTSTR aOptions, LPTSTR aTitle);
ResultType Clear();
ResultType Cancel();
ResultType Close(); // Due to SC_CLOSE, etc.
ResultType Escape(); // Similar to close, except typically called when the user presses ESCAPE.
ResultType Submit(bool aHideIt);
ResultType ControlGetContents(Var &aOutputVar, GuiControlType &aControl, LPTSTR aMode = _T(""));
static VarSizeType ControlGetName(GuiType *aGuiWindow, GuiIndexType aControlIndex, LPTSTR aBuf);
static GuiType *FindGui(LPTSTR aName);
static GuiType *FindGui(HWND aHwnd);
static GuiType *FindGuiParent(HWND aHwnd);
static GuiType *ValidGui(GuiType *&aGuiRef); // Updates aGuiRef if it points to a destroyed Gui.
GuiIndexType FindControl(LPTSTR aControlID);
GuiControlType *FindControl(HWND aHwnd, bool aRetrieveIndexInstead = false)
{
GuiIndexType index = GUI_HWND_TO_INDEX(aHwnd); // Retrieves a small negative on failure, which will be out of bounds when converted to unsigned.
if (index >= mControlCount) // Not found yet; try again with parent.
{
// Since ComboBoxes (and possibly other future control types) have children, try looking
// up aHwnd's parent to see if its a known control of this dialog. Some callers rely on us making
// this extra effort:
if (aHwnd = GetParent(aHwnd)) // Note that a ComboBox's drop-list (class ComboLBox) is apparently a direct child of the desktop, so this won't help us in that case.
index = GUI_HWND_TO_INDEX(aHwnd); // Retrieves a small negative on failure, which will be out of bounds when converted to unsigned.
}
if (index < mControlCount && mControl[index].hwnd == aHwnd) // A match was found. Fix for v1.1.09.03: Confirm it is actually one of our controls.
return aRetrieveIndexInstead ? (GuiControlType *)(size_t)index : mControl + index;
else // No match, so indicate failure.
return aRetrieveIndexInstead ? (GuiControlType *)NO_CONTROL_INDEX : NULL;
}
int FindGroup(GuiIndexType aControlIndex, GuiIndexType &aGroupStart, GuiIndexType &aGroupEnd);
ResultType SetCurrentFont(LPTSTR aOptions, LPTSTR aFontName);
static int FindOrCreateFont(LPTSTR aOptions = _T(""), LPTSTR aFontName = _T(""), FontType *aFoundationFont = NULL
, COLORREF *aColor = NULL);
static int FindFont(FontType &aFont);
void Event(GuiIndexType aControlIndex, UINT aNotifyCode, USHORT aGuiEvent = GUI_EVENT_NONE, UINT_PTR aEventInfo = 0);
int CustomCtrlWmNotify(GuiIndexType aControlIndex, LPNMHDR aNmHdr);
static WORD TextToHotkey(LPTSTR aText);
static LPTSTR HotkeyToText(WORD aHotkey, LPTSTR aBuf);
void ControlCheckRadioButton(GuiControlType &aControl, GuiIndexType aControlIndex, WPARAM aCheckType);
void ControlSetUpDownOptions(GuiControlType &aControl, GuiControlOptionsType &aOpt);
int ControlGetDefaultSliderThickness(DWORD aStyle, int aThumbThickness);
void ControlSetSliderOptions(GuiControlType &aControl, GuiControlOptionsType &aOpt);
int ControlInvertSliderIfNeeded(GuiControlType &aControl, int aPosition);
void ControlSetListViewOptions(GuiControlType &aControl, GuiControlOptionsType &aOpt);
void ControlSetTreeViewOptions(GuiControlType &aControl, GuiControlOptionsType &aOpt);
void ControlSetProgressOptions(GuiControlType &aControl, GuiControlOptionsType &aOpt, DWORD aStyle);
bool ControlOverrideBkColor(GuiControlType &aControl);
void ControlUpdateCurrentTab(GuiControlType &aTabControl, bool aFocusFirstControl);
GuiControlType *FindTabControl(TabControlIndexType aTabControlIndex);
int FindTabIndexByName(GuiControlType &aTabControl, LPTSTR aName, bool aExactMatch = false);
int GetControlCountOnTabPage(TabControlIndexType aTabControlIndex, TabIndexType aTabIndex);
POINT GetPositionOfTabClientArea(GuiControlType &aTabControl);
ResultType SelectAdjacentTab(GuiControlType &aTabControl, bool aMoveToRight, bool aFocusFirstControl
, bool aWrapAround);
void ControlGetPosOfFocusedItem(GuiControlType &aControl, POINT &aPoint);
static void LV_Sort(GuiControlType &aControl, int aColumnIndex, bool aSortOnlyIfEnabled, TCHAR aForceDirection = '\0');
static DWORD ControlGetListViewMode(HWND aWnd);
static IObject *ControlGetActiveX(HWND aWnd);
void UpdateAccelerators(UserMenu &aMenu);
void UpdateAccelerators(UserMenu &aMenu, LPACCEL aAccel, int &aAccelCount);
void RemoveAccelerators();
static bool ConvertAccelerator(LPTSTR aString, ACCEL &aAccel);
// See DPIScale() and DPIUnscale() for more details.
int Scale(int x) { return mUsesDPIScaling ? DPIScale(x) : x; }
int Unscale(int x) { return mUsesDPIScaling ? DPIUnscale(x) : x; }
};
#endif // MINIDLL
typedef NTSTATUS (NTAPI *PFN_NT_QUERY_INFORMATION_PROCESS) (
HANDLE ProcessHandle,
PROCESSINFOCLASS ProcessInformationClass,
PVOID ProcessInformation,
ULONG ProcessInformationLength,
PULONG ReturnLength OPTIONAL);
typedef int (* ahkx_int_str)(LPTSTR ahkx_str); // ahkx N11
typedef int (* ahkx_int_str_str)(LPTSTR ahkx_str, LPTSTR ahkx_str2); // ahkx N11
class Script
{
private:
#ifndef MINIDLL
friend class Hotkey;
#endif
#ifdef CONFIG_DEBUGGER
friend class Debugger;
#endif
public:
Var **mVar, **mLazyVar; // Array of pointers-to-variable, allocated upon first use and later expanded as needed.
int mVarCount, mVarCountMax, mLazyVarCount; // Count of items in the above array as well as the maximum capacity.
WinGroup *mFirstGroup, *mLastGroup; // The first and last variables in the linked list.
int mCurrentFuncOpenBlockCount; // While loading the script, this is how many blocks are currently open in the current function's body.
bool mNextLineIsFunctionBody; // Whether the very next line to be added will be the first one of the body.
#define MAX_NESTED_CLASSES 5
#define MAX_CLASS_NAME_LENGTH UCHAR_MAX
int mClassObjectCount;
Object *mClassObject[MAX_NESTED_CLASSES]; // Class definition currently being parsed.
TCHAR mClassName[MAX_CLASS_NAME_LENGTH + 1]; // Only used during load-time.
Object *mUnresolvedClasses;
Property *mClassProperty;
LPTSTR mClassPropertyDef;
// These two track the file number and line number in that file of the line currently being loaded,
// which simplifies calls to ScriptError() and LineError() (reduces the number of params that must be passed).
// These are used ONLY while loading the script into memory. After that (while the script is running),
// only mCurrLine is kept up-to-date:
int mCurrFileIndex;
LineNumberType mCombinedLineNumber; // In the case of a continuation section/line(s), this is always the top line.
bool mNoHotkeyLabels;
#ifndef MINIDLL
bool mMenuUseErrorLevel; // Whether runtime errors should be displayed by the Menu command, vs. ErrorLevel.
#endif
#define UPDATE_TIP_FIELD tcslcpy(mNIC.szTip, (mTrayIconTip && *mTrayIconTip) ? mTrayIconTip \
: (mFileName ? mFileName : T_AHK_NAME), _countof(mNIC.szTip));
NOTIFYICONDATA mNIC; // For ease of adding and deleting our tray icon.
size_t GetLine(LPTSTR aBuf, int aMaxCharsToRead, int aInContinuationSection, TextStream *ts);
ResultType IsDirective(LPTSTR aBuf);
ResultType ParseAndAddLine(LPTSTR aLineText, ActionTypeType aActionType = ACT_INVALID
, ActionTypeType aOldActionType = OLD_INVALID, LPTSTR aActionName = NULL
, LPTSTR aEndMarker = NULL, LPTSTR aLiteralMap = NULL, size_t aLiteralMapLength = 0);
ResultType ParseDerefs(LPTSTR aArgText, LPTSTR aArgMap, DerefType *aDeref, int &aDerefCount);
LPTSTR ParseActionType(LPTSTR aBufTarget, LPTSTR aBufSource, bool aDisplayErrors);
static ActionTypeType ConvertActionType(LPTSTR aActionTypeString);
static ActionTypeType ConvertOldActionType(LPTSTR aActionTypeString);
ResultType AddLabel(LPTSTR aLabelName, bool aAllowDupe);
ResultType AddLine(ActionTypeType aActionType, LPTSTR aArg[] = NULL, int aArgc = 0, LPTSTR aArgMap[] = NULL);
// These aren't in the Line class because I think they're easier to implement
// if aStartingLine is allowed to be NULL (for recursive calls). If they
// were member functions of class Line, a check for NULL would have to
// be done before dereferencing any line's mNextLine, for example:
Line *PreparseBlocks(Line *aStartingLine, bool aFindBlockEnd = false, Line *aParentLine = NULL);
Line *PreparseIfElse(Line *aStartingLine, ExecUntilMode aMode = NORMAL_MODE, AttributeType aLoopType = ATTR_NONE);
Line *mFirstLine, *mLastLine; // The first and last lines in the linked list.
Line *mFirstStaticLine, *mLastStaticLine; // The first and last static var initializer.
Label *mFirstLabel, *mLastLabel; // The first and last labels in the linked list.
Func **mFunc; // Binary-searchable array of functions.
int mFuncCount, mFuncCountMax;
Line *mTempLine; // for use with dll Execute # Naveen N9
Label *mTempLabel; // for use with dll Execute # Naveen N9
Func *mTempFunc; // for use with dll Execute # Naveen N9
ahkx_int_str xifwinactive ; // ahkx N11 context sensitivity
ahkx_int_str xwingetid ; //
ahkx_int_str_str xsend ; // ahksend
// Naveen moved above from private
Line *mCurrLine; // Seems better to make this public than make Line our friend.
Label *mPlaceholderLabel; // Used in place of a NULL label to simplify code.
#ifndef MINIDLL
TCHAR mThisMenuItemName[MAX_MENU_NAME_LENGTH + 1];
TCHAR mThisMenuName[MAX_MENU_NAME_LENGTH + 1];
LPTSTR mThisHotkeyName, mPriorHotkeyName;
#endif
HWND mNextClipboardViewer;
bool mOnClipboardChangeIsRunning;
Label *mOnClipboardChangeLabel, *mOnExitLabel; // The label to run when the script terminates (NULL if none).
ExitReasons mExitReason;
ScriptTimer *mFirstTimer, *mLastTimer; // The first and last script timers in the linked list.
UINT mTimerCount, mTimerEnabledCount;
#ifndef MINIDLL
UserMenu *mFirstMenu, *mLastMenu;
UINT mMenuCount;
#endif
DWORD mThisHotkeyStartTime, mPriorHotkeyStartTime; // Tickcount timestamp of when its subroutine began.
#ifndef MINIDLL
TCHAR mEndChar; // The ending character pressed to trigger the most recent non-auto-replace hotstring.
#endif
modLR_type mThisHotkeyModifiersLR;
LPTSTR mFileSpec; // Will hold the full filespec, for convenience.
LPTSTR mFileDir; // Will hold the directory containing the script file.
LPTSTR mFileName; // Will hold the script's naked file name.
LPTSTR mOurEXE; // Will hold this app's module name (e.g. C:\Program Files\AutoHotkey\AutoHotkey.exe).
LPTSTR mOurEXEDir; // Same as above but just the containing directory (for convenience).
LPTSTR mMainWindowTitle; // Will hold our main window's title, for consistency & convenience.
bool mIsReadyToExecute;
bool mAutoExecSectionIsRunning;
bool mIsRestart; // The app is restarting rather than starting from scratch.
bool mErrorStdOut; // true if load-time syntax errors should be sent to stdout vs. a MsgBox.
#ifdef AUTOHOTKEYSC
bool mCompiledHasCustomIcon; // Whether the compiled script uses a custom icon.
#else
TextStream *mIncludeLibraryFunctionsThenExit;
#endif
__int64 mLinesExecutedThisCycle; // Use 64-bit to match the type of g->LinesPerCycle
int mUninterruptedLineCountMax; // 32-bit for performance (since huge values seem unnecessary here).
int mUninterruptibleTime;
DWORD mLastScriptRest, mLastPeekTime;
CStringW mRunAsUser, mRunAsPass, mRunAsDomain;
#ifndef MINIDLL
HICON mCustomIcon; // NULL unless the script has loaded a custom icon during its runtime.
HICON mCustomIconSmall; // L17: Use separate big/small icons for best results.
LPTSTR mCustomIconFile; // Filename of icon. Allocated on first use.
bool mIconFrozen; // If true, the icon does not change state when the state of pause or suspend changes.
LPTSTR mTrayIconTip; // Custom tip text for tray icon. Allocated on first use.
UINT mCustomIconNumber; // The number of the icon inside the above file.
UserMenu *mTrayMenu; // Our tray menu, which should be destroyed upon exiting the program.
#endif
#ifdef _USRDLL
void Destroy(); // HotKeyIt H1 destroy script
#endif
ResultType Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance,bool aIsText);
// ResultType InitDll(global_struct &g,HINSTANCE hInstance); // HotKeyIt init dll from text
ResultType CreateWindows();
#ifndef MINIDLL
void EnableOrDisableViewMenuItems(HMENU aMenu, UINT aFlags);
void CreateTrayIcon();
void UpdateTrayIcon(bool aForceUpdate = false);
#endif
ResultType AutoExecSection();
#ifndef MINIDLL
ResultType Edit();
#endif
ResultType Reload(bool aDisplayErrors);
ResultType ExitApp(ExitReasons aExitReason, LPTSTR aBuf = NULL, int ExitCode = 0);
void TerminateApp(ExitReasons aExitReason, int aExitCode); // L31: Added aExitReason. See script.cpp.
#ifdef AUTOHOTKEYSC
LineNumberType LoadFromFile();
#else
LineNumberType LoadFromFile(bool aScriptWasNotspecified,bool aCheckIfExpr = true);
#endif
#ifndef AUTOHOTKEYSC
LineNumberType LoadFromText(LPTSTR aScript,LPCTSTR aPathToShow = NULL, bool aCheckIfExpr = true); // HotKeyIt H1 load text instead file ahktextdll
ResultType LoadIncludedText(LPTSTR aScript,LPCTSTR aPathToShow = NULL); //New read text
#endif
ResultType LoadIncludedFile(LPTSTR aFileSpec, bool aAllowDuplicateInclude, bool aIgnoreLoadFailure);
ResultType UpdateOrCreateTimer(Label *aLabel, LPTSTR aPeriod, LPTSTR aPriority, bool aEnable
, bool aUpdatePriorityOnly);
ResultType DefineFunc(LPTSTR aBuf, Var *aFuncGlobalVar[]);
#ifndef AUTOHOTKEYSC
Func *FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool &aErrorWasShown, bool &aFileWasFound, bool aIsAutoInclude);
#endif
Func *FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength = 0, int *apInsertPos = NULL);
Func *AddFunc(LPCTSTR aFuncName, size_t aFuncNameLength, bool aIsBuiltIn, int aInsertPos, Object *aClassObject = NULL);
ResultType DefineClass(LPTSTR aBuf);
ResultType DefineClassVars(LPTSTR aBuf, bool aStatic);
ResultType DefineClassProperty(LPTSTR aBuf);
Object *FindClass(LPCTSTR aClassName, size_t aClassNameLength = 0);
ResultType ResolveClasses();
int AddBIF(LPTSTR aFuncName, BuiltInFunctionType bif, size_t minparams, size_t maxparams); // N10 added for dynamic BIFs
#define FINDVAR_DEFAULT (VAR_LOCAL | VAR_GLOBAL)
#define FINDVAR_GLOBAL VAR_GLOBAL
#define FINDVAR_LOCAL VAR_LOCAL
#define FINDVAR_STATIC (VAR_LOCAL | VAR_LOCAL_STATIC)
Var *FindOrAddVar(LPTSTR aVarName, size_t aVarNameLength = 0, int aScope = FINDVAR_DEFAULT);
Var *FindVar(LPTSTR aVarName, size_t aVarNameLength = 0, int *apInsertPos = NULL
, int aScope = FINDVAR_DEFAULT
, bool *apIsLocal = NULL);
Var *AddVar(LPTSTR aVarName, size_t aVarNameLength, int aInsertPos, int aScope);
static void *GetVarType(LPTSTR aVarName);
WinGroup *FindGroup(LPTSTR aGroupName, bool aCreateIfNotFound = false);
ResultType AddGroup(LPTSTR aGroupName);
Label *FindLabel(LPTSTR aLabelName);
ResultType DoRunAs(LPTSTR aCommandLine, LPTSTR aWorkingDir, bool aDisplayErrors, bool aUpdateLastError, WORD aShowWindow
, Var *aOutputVar, PROCESS_INFORMATION &aPI, bool &aSuccess, HANDLE &aNewProcess, LPTSTR aSystemErrorText);
ResultType ActionExec(LPTSTR aAction, LPTSTR aParams = NULL, LPTSTR aWorkingDir = NULL
, bool aDisplayErrors = true, LPTSTR aRunShowMode = NULL, HANDLE *aProcess = NULL
, bool aUpdateLastError = false, bool aUseRunAs = false, Var *aOutputVar = NULL);
#ifndef MINIDLL
LPTSTR ListVars(LPTSTR aBuf, int aBufSize);
LPTSTR ListKeyHistory(LPTSTR aBuf, int aBufSize);
ResultType PerformMenu(LPTSTR aMenu, LPTSTR aCommand, LPTSTR aParam3, LPTSTR aParam4, LPTSTR aOptions, LPTSTR aOptions2); // L17: Added aOptions2 for Icon sub-command (icon width). Arg was previously reserved/unused.
UserMenu *FindMenu(LPTSTR aMenuName);
UserMenu *AddMenu(LPTSTR aMenuName);
ResultType ScriptDeleteMenu(UserMenu *aMenu);
UserMenuItem *FindMenuItemByID(UINT aID)
{
UserMenuItem *mi;
for (UserMenu *m = mFirstMenu; m; m = m->mNextMenu)
for (mi = m->mFirstMenuItem; mi; mi = mi->mNextMenuItem)
if (mi->mMenuID == aID)
return mi;
return NULL;
}
UserMenuItem *FindMenuItemBySubmenu(HMENU aSubmenu) // L26: Used by WM_MEASUREITEM/WM_DRAWITEM to find the menu item with an associated submenu. Fixes icons on such items when owner-drawn menus are in use.
{
UserMenuItem *mi;
for (UserMenu *m = mFirstMenu; m; m = m->mNextMenu)
for (mi = m->mFirstMenuItem; mi; mi = mi->mNextMenuItem)
if (mi->mSubmenu && mi->mSubmenu->mMenu == aSubmenu)
return mi;
return NULL;
}
ResultType PerformGui(LPTSTR aBuf, LPTSTR aControlType, LPTSTR aOptions, LPTSTR aParam4);
static GuiType *ResolveGui(LPTSTR aBuf, LPTSTR &aCommand, LPTSTR *aName = NULL, size_t *aNameLength = NULL);
#endif
// Call this SciptError to avoid confusion with Line's error-displaying functions:
ResultType ScriptError(LPCTSTR aErrorText, LPCTSTR aExtraInfo = _T("")); // , ResultType aErrorType = FAIL);
void ScriptWarning(WarnMode warnMode, LPCTSTR aWarningText, LPCTSTR aExtraInfo = _T(""), Line *line = NULL);
void WarnUninitializedVar(Var *var);
void MaybeWarnLocalSameAsGlobal(Func &func, Var &var);
void PreprocessLocalVars(Func &aFunc, Var **aVarList, int &aVarCount);
static ResultType UnhandledException(ExprTokenType*& aToken, Line* aLine);
static ResultType SetErrorLevelOrThrow() { return SetErrorLevelOrThrowBool(true); }
static ResultType SetErrorLevelOrThrowBool(bool aError);
static ResultType SetErrorLevelOrThrowInt(int aErrorValue, LPCTSTR aWhat);
static ResultType SetErrorLevelOrThrowStr(LPCTSTR aErrorValue, LPCTSTR aWhat = NULL);
static ResultType ThrowRuntimeException(LPCTSTR aErrorText, LPCTSTR aWhat = NULL, LPCTSTR aExtraInfo = _T(""));
static void FreeExceptionToken(ExprTokenType*& aToken);
#define SOUNDPLAY_ALIAS _T("AHK_PlayMe") // Used by destructor and SoundPlay().
Script();
~Script();
// Note that the anchors to any linked lists will be lost when this
// object goes away, so for now, be sure the destructor is only called
// when the program is about to be exited, which will thereby reclaim
// the memory used by the abandoned linked lists (otherwise, a memory
// leak will result).
};
////////////////////////
// BUILT-IN VARIABLES //
////////////////////////
VarSizeType BIV_True_False_Null(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_MMM_DDD(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_DateTime(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_BatchLines(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_TitleMatchMode(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_TitleMatchModeSpeed(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_DetectHiddenWindows(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_DetectHiddenText(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_AutoTrim(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_StringCaseSense(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_FormatInteger(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_FormatFloat(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_KeyDelay(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_WinDelay(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ControlDelay(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_MouseDelay(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_DefaultMouseSpeed(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_IsPaused(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_IsCritical(LPTSTR aBuf, LPTSTR aVarName);
#ifndef MINIDLL
VarSizeType BIV_IsSuspended(LPTSTR aBuf, LPTSTR aVarName);
#endif
//#ifdef AUTOHOTKEYSC // A_IsCompiled is left blank/undefined in uncompiled scripts.
VarSizeType BIV_IsCompiled(LPTSTR aBuf, LPTSTR aVarName);
//#endif
VarSizeType BIV_IsUnicode(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_FileEncoding(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_RegView(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LastError(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_GlobalStruct(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ScriptStruct(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ModuleHandle(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_MemoryModule(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_IsDll(LPTSTR aBuf, LPTSTR aVarName);
+VarSizeType BIV_IsMini(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_CoordMode(LPTSTR aBuf, LPTSTR aVarName);
#ifndef MINIDLL
VarSizeType BIV_IconHidden(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_IconTip(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_IconFile(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_IconNumber(LPTSTR aBuf, LPTSTR aVarName);
#endif
VarSizeType BIV_ExitReason(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_Space_Tab(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_AhkVersion(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_AhkPath(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_AhkDir(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_DllPath(LPTSTR aBuf, LPTSTR aVarName); // HotKeyIt H1 path of loaded dll
VarSizeType BIV_DllDir(LPTSTR aBuf, LPTSTR aVarName); // HotKeyIt H1 path of loaded dll
VarSizeType BIV_TickCount(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_Now(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_OSType(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_OSVersion(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_Is64bitOS(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_Language(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_UserName_ComputerName(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_WorkingDir(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_WinDir(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_Temp(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ComSpec(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_SpecialFolderPath(LPTSTR aBuf, LPTSTR aVarName); // Handles various variables.
VarSizeType BIV_MyDocuments(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_Caret(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_Cursor(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ScreenWidth_Height(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ScriptName(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ScriptDir(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ScriptFullPath(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ScriptHwnd(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LineNumber(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LineFile(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopFileName(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopFileShortName(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopFileExt(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopFileDir(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopFileFullPath(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopFileLongPath(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopFileShortPath(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopFileTime(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopFileAttrib(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopFileSize(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopRegType(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopRegKey(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopRegSubKey(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopRegName(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopRegTimeModified(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopReadLine(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopField(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_LoopIndex(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ThisFunc(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ThisLabel(LPTSTR aBuf, LPTSTR aVarName);
#ifndef MINIDLL
VarSizeType BIV_ThisMenuItem(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ThisMenuItemPos(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ThisMenu(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ThisHotkey(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_PriorHotkey(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_TimeSinceThisHotkey(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_TimeSincePriorHotkey(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_EndChar(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_Gui(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_GuiControl(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_GuiEvent(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_PriorKey(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_ScreenDPI(LPTSTR aBuf, LPTSTR aVarName);
#endif
VarSizeType BIV_EventInfo(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_TimeIdle(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_TimeIdlePhysical(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_IPAddress(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_IsAdmin(LPTSTR aBuf, LPTSTR aVarName);
VarSizeType BIV_PtrSize(LPTSTR aBuf, LPTSTR aVarName);
////////////////////////
// BUILT-IN FUNCTIONS //
////////////////////////
// Caller has ensured that SYM_VAR's Type() is VAR_NORMAL and that it's either not an environment
// variable or the caller wants environment variables treated as having zero length.
#define EXPR_TOKEN_LENGTH(token_raw, token_as_string) \
( (token_raw->symbol == SYM_VAR && !token_raw->var->IsBinaryClip()) \
? token_raw->var->Length()\
: _tcslen(token_as_string) )
#ifdef ENABLE_DLLCALL
bool IsDllArgTypeName(LPTSTR name);
void *GetDllProcAddress(LPCTSTR aDllFileFunc, HMODULE *hmodule_to_free = NULL);
BIF_DECL(BIF_DllCall);
BIF_DECL(BIF_DllImport);
BIF_DECL(BIF_DynaCall);
#endif
BIF_DECL(BIF_Struct);
BIF_DECL(BIF_sizeof);
BIF_DECL(BIF_FindFunc);
BIF_DECL(BIF_FindLabel);
BIF_DECL(BIF_Getvar);
BIF_DECL(BIF_Alias);
BIF_DECL(BIF_UnZipRawMemory);
BIF_DECL(BIF_CacheEnable);
BIF_DECL(BIF_getTokenValue);
BIF_DECL(BIF_ResourceLoadLibrary);
BIF_DECL(BIF_MemoryLoadLibrary);
BIF_DECL(BIF_MemoryGetProcAddress);
BIF_DECL(BIF_MemoryFreeLibrary);
BIF_DECL(BIF_MemoryFindResource);
BIF_DECL(BIF_MemorySizeOfResource);
BIF_DECL(BIF_MemoryLoadResource);
BIF_DECL(BIF_MemoryLoadString);
BIF_DECL(BIF_Lock);
BIF_DECL(BIF_TryLock);
BIF_DECL(BIF_UnLock);
BIF_DECL(BIF_StrLen);
BIF_DECL(BIF_SubStr);
BIF_DECL(BIF_InStr);
BIF_DECL(BIF_StrSplit);
BIF_DECL(BIF_RegEx);
BIF_DECL(BIF_Asc);
BIF_DECL(BIF_Chr);
BIF_DECL(BIF_NumGet);
BIF_DECL(BIF_NumPut);
BIF_DECL(BIF_StrGetPut);
BIF_DECL(BIF_IsLabel);
BIF_DECL(BIF_IsFunc);
BIF_DECL(BIF_Func);
BIF_DECL(BIF_IsByRef);
BIF_DECL(BIF_GetKeyState);
BIF_DECL(BIF_GetKeyName);
BIF_DECL(BIF_VarSetCapacity);
BIF_DECL(BIF_FileExist);
BIF_DECL(BIF_WinExistActive);
BIF_DECL(BIF_Round);
BIF_DECL(BIF_FloorCeil);
BIF_DECL(BIF_Mod);
BIF_DECL(BIF_Abs);
BIF_DECL(BIF_Sin);
BIF_DECL(BIF_Cos);
BIF_DECL(BIF_Tan);
BIF_DECL(BIF_ASinACos);
BIF_DECL(BIF_ATan);
BIF_DECL(BIF_Exp);
BIF_DECL(BIF_SqrtLogLn);
BIF_DECL(BIF_OnMessage);
#ifdef ENABLE_REGISTERCALLBACK
BIF_DECL(BIF_RegisterCallback);
#endif
#ifndef MINIDLL
BIF_DECL(BIF_StatusBar);
BIF_DECL(BIF_LV_GetNextOrCount);
BIF_DECL(BIF_LV_GetText);
BIF_DECL(BIF_LV_AddInsertModify);
BIF_DECL(BIF_LV_Delete);
BIF_DECL(BIF_LV_InsertModifyDeleteCol);
BIF_DECL(BIF_LV_SetImageList);
BIF_DECL(BIF_TV_AddModifyDelete);
BIF_DECL(BIF_TV_GetRelatedItem);
BIF_DECL(BIF_TV_Get);
BIF_DECL(BIF_TV_SetImageList);
BIF_DECL(BIF_IL_Create);
BIF_DECL(BIF_IL_Destroy);
BIF_DECL(BIF_IL_Add);
#endif
BIF_DECL(BIF_Trim); // L31: Also handles LTrim and RTrim.
BIF_DECL(BIF_IsObject);
BIF_DECL(BIF_ObjCreate);
BIF_DECL(BIF_ObjArray);
BIF_DECL(BIF_CriticalObject);
BIF_DECL(BIF_sizeof);
BIF_DECL(BIF_Struct);
BIF_DECL(BIF_ObjInvoke); // Pseudo-operator. See script_object.cpp for comments.
BIF_DECL(BIF_ObjGetInPlace); // Pseudo-operator.
BIF_DECL(BIF_ObjNew); // Pseudo-operator.
BIF_DECL(BIF_ObjIncDec); // Pseudo-operator.
BIF_DECL(BIF_ObjAddRefRelease);
// Built-ins also available as methods -- these are available as functions for use primarily by overridden methods (i.e. where using the built-in methods isn't possible as they're no longer accessible).
BIF_DECL(BIF_ObjInsert);
BIF_DECL(BIF_ObjRemove);
BIF_DECL(BIF_ObjGetCapacity);
BIF_DECL(BIF_ObjSetCapacity);
BIF_DECL(BIF_ObjGetAddress);
BIF_DECL(BIF_ObjMaxIndex);
BIF_DECL(BIF_ObjMinIndex);
BIF_DECL(BIF_ObjCount);
BIF_DECL(BIF_ObjNewEnum);
BIF_DECL(BIF_ObjHasKey);
BIF_DECL(BIF_ObjClone);
// Advanced file IO interfaces
BIF_DECL(BIF_FileOpen);
BIF_DECL(BIF_ComObjActive);
BIF_DECL(BIF_ComObjCreate);
BIF_DECL(BIF_ComObjGet);
BIF_DECL(BIF_ComObjDll);
BIF_DECL(BIF_ComObjConnect);
BIF_DECL(BIF_ComObjError);
BIF_DECL(BIF_ComObjTypeOrValue);
BIF_DECL(BIF_ComObjFlags);
BIF_DECL(BIF_ComObjArray);
BIF_DECL(BIF_ComObjQuery);
BIF_DECL(BIF_Exception);
BOOL LegacyResultToBOOL(LPTSTR aResult);
BOOL LegacyVarToBOOL(Var &aVar);
BOOL TokenToBOOL(ExprTokenType &aToken, SymbolType aTokenIsNumber);
SymbolType TokenIsPureNumeric(ExprTokenType &aToken);
BOOL TokenIsEmptyString(ExprTokenType &aToken);
BOOL TokenIsEmptyString(ExprTokenType &aToken, BOOL aWarnUninitializedVar); // Same as TokenIsEmptyString but optionally warns if the token is an uninitialized var.
__int64 TokenToInt64(ExprTokenType &aToken, BOOL aIsPureInteger = FALSE);
double TokenToDouble(ExprTokenType &aToken, BOOL aCheckForHex = TRUE, BOOL aIsPureFloat = FALSE);
LPTSTR TokenToString(ExprTokenType &aToken, LPTSTR aBuf = NULL);
ResultType TokenToDoubleOrInt64(const ExprTokenType &aInput, ExprTokenType &aOutput);
IObject *TokenToObject(ExprTokenType &aToken); // L31
Func *TokenToFunc(ExprTokenType &aToken);
ResultType TokenSetResult(ExprTokenType &aResultToken, LPCTSTR aResult, size_t aResultLength = -1);
LPTSTR RegExMatch(LPTSTR aHaystack, LPTSTR aNeedleRegEx);
void SetWorkingDir(LPTSTR aNewDir);
int ConvertJoy(LPTSTR aBuf, int *aJoystickID = NULL, bool aAllowOnlyButtons = false);
bool ScriptGetKeyState(vk_type aVK, KeyStateTypes aKeyStateType);
double ScriptGetJoyState(JoyControls aJoy, int aJoystickID, ExprTokenType &aToken, bool aUseBoolForUpDown);
#endif
diff --git a/source/script2.cpp b/source/script2.cpp
index 6d7bd01..94f9597 100644
--- a/source/script2.cpp
+++ b/source/script2.cpp
@@ -10965,1024 +10965,1038 @@ bool Line::FileIsFilteredOut(WIN32_FIND_DATA &aCurrentFile, FileLoopModeType aFi
// cases to include such "faulty" data in the loop. Most scripts would want to skip them rather than
// seeing the truncated names. Furthermore, a truncated name might accidentally match the name
// of a legitimate non-truncated filename, which could cause such a name to get retrieved twice by
// the loop (or other undesirable side-effects).
return true;
//else no overflow is possible, so below can move things around inside the buffer without concern.
tmemmove(aCurrentFile.cFileName + aFilePathLength, aCurrentFile.cFileName, name_length + 1); // memmove() because source & dest might overlap. +1 to include the terminator.
tmemcpy(aCurrentFile.cFileName, aFilePath, aFilePathLength); // Prepend in the area liberated by the above. Don't include the terminator since this is a concat operation.
}
return false; // Indicate that this file is not to be filtered out.
}
Label *Line::GetJumpTarget(bool aIsDereferenced)
{
LPTSTR target_label = aIsDereferenced ? ARG1 : RAW_ARG1;
Label *label = g_script.FindLabel(target_label);
if (!label)
{
LineError(ERR_NO_LABEL, FAIL, target_label);
return NULL;
}
if (!aIsDereferenced)
mRelatedLine = (Line *)label; // The script loader has ensured that label->mJumpToLine isn't NULL.
// else don't update it, because that would permanently resolve the jump target, and we want it to stay dynamic.
// Seems best to do this even for GOSUBs even though it's a bit weird:
return IsJumpValid(*label);
// Any error msg was already displayed by the above call.
}
Label *Line::IsJumpValid(Label &aTargetLabel, bool aSilent)
// Returns aTargetLabel is the jump is valid, or NULL otherwise.
{
// aTargetLabel can be NULL if this Goto's target is the physical end of the script.
// And such a destination is always valid, regardless of where aOrigin is.
// UPDATE: It's no longer possible for the destination of a Goto or Gosub to be
// NULL because the script loader has ensured that the end of the script always has
// an extra ACT_EXIT that serves as an anchor for any final labels in the script:
//if (aTargetLabel == NULL)
// return OK;
// The above check is also necessary to avoid dereferencing a NULL pointer below.
Line *parent_line_of_label_line;
if ( !(parent_line_of_label_line = aTargetLabel.mJumpToLine->mParentLine) )
// A Goto/Gosub can always jump to a point anywhere in the outermost layer
// (i.e. outside all blocks) without restriction:
return &aTargetLabel; // Indicate success.
// So now we know this Goto/Gosub is attempting to jump into a block somewhere. Is that
// block a legal place to jump?:
for (Line *ancestor = mParentLine; ancestor != NULL; ancestor = ancestor->mParentLine)
if (parent_line_of_label_line == ancestor)
// Since aTargetLabel is in the same block as the Goto line itself (or a block
// that encloses that block), it's allowed:
return &aTargetLabel; // Indicate success.
// This can happen if the Goto's target is at a deeper level than it, or if the target
// is at a more shallow level but is in some block totally unrelated to it!
// Returns FAIL by default, which is what we want because that value is zero:
if (!aSilent)
LineError(_T("A Goto/Gosub must not jump into a block that doesn't enclose it.")); // Omit GroupActivate from the error msg since that is rare enough to justify the increase in common-case clarity.
return NULL;
}
BOOL Line::IsOutsideAnyFunctionBody() // v1.0.48.02
{
for (Line *ancestor = mParentLine; ancestor != NULL; ancestor = ancestor->mParentLine)
if (ancestor->mAttribute == ATTR_TRUE && ancestor->mActionType == ACT_BLOCK_BEGIN) // Ordered for short-circuit performance.
return FALSE; // ATTR_TRUE marks an open-brace as belonging to a function's body, so indicate this this line is inside a function.
return TRUE; // Indicate that this line is not inside any function body.
}
BOOL Line::CheckValidFinallyJump(Line* jumpTarget) // v1.1.14
{
Line* jumpParent = jumpTarget->mParentLine;
for (Line *ancestor = mParentLine; ancestor != NULL; ancestor = ancestor->mParentLine)
{
if (ancestor == jumpParent)
return TRUE; // We found the common ancestor.
if (ancestor->mActionType == ACT_FINALLY)
{
LineError(ERR_BAD_JUMP_INSIDE_FINALLY);
return FALSE; // The common ancestor is outside the FINALLY block and thus this jump is invalid.
}
}
return TRUE; // The common ancestor is the root of the script.
}
////////////////////////
// BUILT-IN VARIABLES //
////////////////////////
VarSizeType BIV_True_False_Null(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
*aBuf++ = (aVarName[2] == 'l' || aVarName[2] == 'L') ? '0': '1';
*aBuf = '\0';
}
return 1; // The length of the value.
}
VarSizeType BIV_MMM_DDD(LPTSTR aBuf, LPTSTR aVarName)
{
LPTSTR format_str;
switch(ctoupper(aVarName[2]))
{
// Use the case-sensitive formats required by GetDateFormat():
case 'M': format_str = (aVarName[5] ? _T("MMMM") : _T("MMM")); break;
case 'D': format_str = (aVarName[5] ? _T("dddd") : _T("ddd")); break;
}
// Confirmed: The below will automatically use the local time (not UTC) when 3rd param is NULL.
return (VarSizeType)(GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, format_str, aBuf, aBuf ? 999 : 0) - 1);
}
VarSizeType BIV_DateTime(LPTSTR aBuf, LPTSTR aVarName)
{
if (!aBuf)
return 6; // Since only an estimate is needed in this mode, return the maximum length of any item.
aVarName += 2; // Skip past the "A_".
// The current time is refreshed only if it's been a certain number of milliseconds since
// the last fetch of one of these built-in time variables. This keeps the variables in
// sync with one another when they are used consecutively such as this example:
// Var = %A_Hour%:%A_Min%:%A_Sec%
// Using GetTickCount() because it's very low overhead compared to the other time functions:
static DWORD sLastUpdate = 0; // Static should be thread + recursion safe in this case.
static SYSTEMTIME sST = {0}; // Init to detect when it's empty.
BOOL is_msec = !_tcsicmp(aVarName, _T("MSec")); // Always refresh if it's milliseconds, for better accuracy.
DWORD now_tick = GetTickCount();
if (is_msec || now_tick - sLastUpdate > 50 || !sST.wYear) // See comments above.
{
GetLocalTime(&sST);
sLastUpdate = now_tick;
}
if (is_msec)
return _stprintf(aBuf, _T("%03d"), sST.wMilliseconds);
TCHAR second_letter = ctoupper(aVarName[1]);
switch(ctoupper(aVarName[0]))
{
case 'Y':
switch(second_letter)
{
case 'D': // A_YDay
return _stprintf(aBuf, _T("%d"), GetYDay(sST.wMonth, sST.wDay, IS_LEAP_YEAR(sST.wYear)));
case 'W': // A_YWeek
return GetISOWeekNumber(aBuf, sST.wYear
, GetYDay(sST.wMonth, sST.wDay, IS_LEAP_YEAR(sST.wYear))
, sST.wDayOfWeek);
default: // A_Year/A_YYYY
return _stprintf(aBuf, _T("%d"), sST.wYear);
}
// No break because all cases above return:
//break;
case 'M':
switch(second_letter)
{
case 'D': // A_MDay (synonymous with A_DD)
return _stprintf(aBuf, _T("%02d"), sST.wDay);
case 'I': // A_Min
return _stprintf(aBuf, _T("%02d"), sST.wMinute);
default: // A_MM and A_Mon (A_MSec was already completely handled higher above).
return _stprintf(aBuf, _T("%02d"), sST.wMonth);
}
// No break because all cases above return:
//break;
case 'D': // A_DD (synonymous with A_MDay)
return _stprintf(aBuf, _T("%02d"), sST.wDay);
case 'W': // A_WDay
return _stprintf(aBuf, _T("%d"), sST.wDayOfWeek + 1);
case 'H': // A_Hour
return _stprintf(aBuf, _T("%02d"), sST.wHour);
case 'S': // A_Sec (A_MSec was already completely handled higher above).
return _stprintf(aBuf, _T("%02d"), sST.wSecond);
}
return 0; // Never reached, but avoids compiler warning.
}
VarSizeType BIV_BatchLines(LPTSTR aBuf, LPTSTR aVarName)
{
// The BatchLine value can be either a numerical string or a string that ends in "ms".
TCHAR buf[256];
LPTSTR target_buf = aBuf ? aBuf : buf;
if (g->IntervalBeforeRest > -1) // Have this new method take precedence, if it's in use by the script.
return _stprintf(target_buf, _T("%dms"), g->IntervalBeforeRest); // Not sntprintf().
// Otherwise:
ITOA64(g->LinesPerCycle, target_buf);
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_TitleMatchMode(LPTSTR aBuf, LPTSTR aVarName)
{
if (g->TitleMatchMode == FIND_REGEX) // v1.0.45.
{
if (aBuf) // For backward compatibility (due to StringCaseSense), never change the case used here:
_tcscpy(aBuf, _T("RegEx"));
return 5; // The length.
}
// Otherwise, it's a numerical mode:
// It's done this way in case it's ever allowed to go beyond a single-digit number.
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
_itot(g->TitleMatchMode, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence).
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_TitleMatchModeSpeed(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf) // For backward compatibility (due to StringCaseSense), never change the case used here:
_tcscpy(aBuf, g->TitleFindFast ? _T("Fast") : _T("Slow"));
return 4; // Always length 4
}
VarSizeType BIV_DetectHiddenWindows(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(_tcscpy(aBuf, g->DetectHiddenWindows ? _T("On") : _T("Off"))) // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required).
: 3; // Room for either On or Off (in the estimation phase).
}
VarSizeType BIV_DetectHiddenText(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(_tcscpy(aBuf, g->DetectHiddenText ? _T("On") : _T("Off"))) // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required).
: 3; // Room for either On or Off (in the estimation phase).
}
VarSizeType BIV_AutoTrim(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(_tcscpy(aBuf, g->AutoTrim ? _T("On") : _T("Off"))) // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required).
: 3; // Room for either On or Off (in the estimation phase).
}
VarSizeType BIV_StringCaseSense(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(_tcscpy(aBuf, g->StringCaseSense == SCS_INSENSITIVE ? _T("Off") // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required).
: (g->StringCaseSense == SCS_SENSITIVE ? _T("On") : _T("Locale"))))
: 6; // Room for On, Off, or Locale (in the estimation phase).
}
VarSizeType BIV_FormatInteger(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
*aBuf++ = g->FormatInt;
*aBuf = '\0';
}
return 1;
}
VarSizeType BIV_FormatFloat(LPTSTR aBuf, LPTSTR aVarName)
{
if (!aBuf)
return (VarSizeType)_tcslen(g->FormatFloat); // Include the extra chars since this is just an estimate.
LPTSTR str_with_leading_percent_omitted = g->FormatFloat + 1;
size_t length = _tcslen(str_with_leading_percent_omitted);
tcslcpy(aBuf, str_with_leading_percent_omitted
, length + !(length && str_with_leading_percent_omitted[length-1] == 'f')); // Omit the trailing character only if it's an 'f', not any other letter such as the 'e' in "%0.6e" (for backward compatibility).
return (VarSizeType)_tcslen(aBuf); // Must return exact length when aBuf isn't NULL.
}
VarSizeType BIV_KeyDelay(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
_itot(g->KeyDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence).
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_WinDelay(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
_itot(g->WinDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence).
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_ControlDelay(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
_itot(g->ControlDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence).
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_MouseDelay(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
_itot(g->MouseDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence).
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_DefaultMouseSpeed(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
_itot(g->DefaultMouseSpeed, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence).
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_IsPaused(LPTSTR aBuf, LPTSTR aVarName) // v1.0.48: Lexikos: Added BIV_IsPaused and BIV_IsCritical.
{
// Although A_IsPaused could indicate how many threads are paused beneath the current thread,
// that would be a problem because it would yield a non-zero value even when the underlying thread
// isn't paused (i.e. other threads below it are paused), which would defeat the original purpose.
// In addition, A_IsPaused probably won't be commonly used, so it seems best to keep it simple.
// NAMING: A_IsPaused seems to be a better name than A_Pause or A_Paused due to:
// Better readability.
// Consistent with A_IsSuspended, which is strongly related to pause/unpause.
// The fact that it wouldn't be likely for a function to turn off pause then turn it back on
// (or vice versa), which was the main reason for storing "Off" and "On" in things like
// A_DetectHiddenWindows.
if (aBuf)
{
// Checking g>g_array avoids any chance of underflow, which might otherwise happen if this is
// called by the AutoExec section or a threadless callback running in thread #0.
*aBuf++ = (g > g_array && g[-1].IsPaused) ? '1' : '0';
*aBuf = '\0';
}
return 1;
}
VarSizeType BIV_IsCritical(LPTSTR aBuf, LPTSTR aVarName) // v1.0.48: Lexikos: Added BIV_IsPaused and BIV_IsCritical.
{
if (!aBuf) // Return conservative estimate in case Critical status can ever change between the 1st and 2nd calls to this function.
return MAX_INTEGER_LENGTH;
// It seems more useful to return g->PeekFrequency than "On" or "Off" (ACT_CRITICAL ensures that
// g->PeekFrequency!=0 whenever g->ThreadIsCritical==true). Also, the word "Is" in "A_IsCritical"
// implies a value that can be used as a boolean such as "if A_IsCritical".
if (g->ThreadIsCritical)
return (VarSizeType)_tcslen(UTOA(g->PeekFrequency, aBuf)); // ACT_CRITICAL ensures that g->PeekFrequency > 0 when critical is on.
// Otherwise:
*aBuf++ = '0';
*aBuf = '\0';
return 1; // Caller might rely on receiving actual length when aBuf!=NULL.
}
#ifndef MINIDLL
VarSizeType BIV_IsSuspended(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
*aBuf++ = g_IsSuspended ? '1' : '0';
*aBuf = '\0';
}
return 1;
}
#endif
#ifdef AUTOHOTKEYSC // A_IsCompiled is left blank/undefined in uncompiled scripts.
VarSizeType BIV_IsCompiled(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
*aBuf++ = '1';
*aBuf = '\0';
}
return 1;
}
#else
VarSizeType BIV_IsCompiled(LPTSTR aBuf, LPTSTR aVarName)
{
if (!g_hResource)
{
if (aBuf)
*aBuf = '\0';
return 1;
}
else if (aBuf)
{
*aBuf++ = '1';
*aBuf = '\0';
}
return 1;
}
#endif
VarSizeType BIV_IsUnicode(LPTSTR aBuf, LPTSTR aVarName)
{
#ifdef UNICODE
if (aBuf)
{
*aBuf++ = '1';
*aBuf = '\0';
}
return 1;
#else
// v1.1.06: A_IsUnicode is defined so that it does not cause warnings with #Warn enabled,
// but left empty to encourage compatibility with older versions and AutoHotkey Basic.
// This prevents scripts from using expressions like A_IsUnicode+1, which would succeed
// if A_IsUnicode is 0 or 1 but fail if it is "". This change has side-effects similar
// to those described for A_IsCompiled above.
if (aBuf)
*aBuf = '\0';
return 0;
#endif
}
VarSizeType BIV_FileEncoding(LPTSTR aBuf, LPTSTR aVarName)
{
// A similar section may be found under "case Encoding:" in FileObject::Invoke. Maintain that with this:
switch (g->Encoding)
{
case CP_ACP:
if (aBuf)
*aBuf = '\0';
return 0;
#define FILEENCODING_CASE(n, s) \
case n: \
if (aBuf) \
_tcscpy(aBuf, _T(s)); \
return _countof(_T(s)) - 1;
// Returning readable strings for these seems more useful than returning their numeric values, especially with CP_AHKNOBOM:
FILEENCODING_CASE(CP_UTF8, "UTF-8")
FILEENCODING_CASE(CP_UTF8 | CP_AHKNOBOM, "UTF-8-RAW")
FILEENCODING_CASE(CP_UTF16, "UTF-16")
FILEENCODING_CASE(CP_UTF16 | CP_AHKNOBOM, "UTF-16-RAW")
#undef FILEENCODING_CASE
default:
{
TCHAR buf[MAX_INTEGER_SIZE + 2]; // + 2 for "CP"
LPTSTR target_buf = aBuf ? aBuf : buf;
target_buf[0] = _T('C');
target_buf[1] = _T('P');
_itot(g->Encoding, target_buf + 2, 10); // Always output as decimal since we aren't exactly returning a number.
return (VarSizeType)_tcslen(target_buf);
}
}
}
VarSizeType BIV_RegView(LPTSTR aBuf, LPTSTR aVarName)
{
LPCTSTR value;
switch (g->RegView)
{
case KEY_WOW64_32KEY: value = _T("32"); break;
case KEY_WOW64_64KEY: value = _T("64"); break;
default: value = _T("Default"); break;
}
if (aBuf)
_tcscpy(aBuf, value);
return (VarSizeType)_tcslen(value);
}
VarSizeType BIV_LastError(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
_itot(g->LastError, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence).
return (VarSizeType)_tcslen(target_buf);
}
VarSizeType BIV_GlobalStruct(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(ITOA64((LONGLONG)g, aBuf))
: MAX_INTEGER_LENGTH;
}
VarSizeType BIV_ScriptStruct(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(ITOA64((LONGLONG)&g_script, aBuf))
: MAX_INTEGER_LENGTH;
}
VarSizeType BIV_ModuleHandle(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(ITOA64((LONGLONG)g_hInstance, aBuf))
: MAX_INTEGER_LENGTH;
}
VarSizeType BIV_MemoryModule(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(ITOA64((LONGLONG)g_hMemoryModule, aBuf))
: MAX_INTEGER_LENGTH;
}
VarSizeType BIV_IsDll(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
*aBuf++ = (g_hInstance == GetModuleHandle(NULL)) ? '0' : '1';
*aBuf = '\0';
}
return 1;
}
+VarSizeType BIV_IsMini(LPTSTR aBuf, LPTSTR aVarName)
+{
+ if (aBuf)
+ {
+#ifdef MINIDLL
+ *aBuf++ = '1';
+#else
+ *aBuf++ = '0';
+#endif
+ *aBuf = '\0';
+ }
+ return 1;
+}
+
VarSizeType BIV_CoordMode(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(ITOA64(((g->CoordMode >> Line::ConvertCoordModeCmd(aVarName + 11)) & COORD_MODE_MASK), aBuf))
: MAX_INTEGER_LENGTH;
}
VarSizeType BIV_PtrSize(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
// Return size in bytes of a pointer in the current build.
*aBuf++ = '0' + sizeof(void *);
*aBuf = '\0';
}
return 1;
}
#ifndef MINIDLL
VarSizeType BIV_ScreenDPI(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
_itot(g_ScreenDPI, aBuf, 10);
return aBuf ? (VarSizeType)_tcslen(aBuf) : MAX_INTEGER_SIZE;
}
VarSizeType BIV_IconHidden(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
*aBuf++ = g_NoTrayIcon ? '1' : '0';
*aBuf = '\0';
}
return 1; // Length is always 1.
}
VarSizeType BIV_IconTip(LPTSTR aBuf, LPTSTR aVarName)
{
if (!aBuf)
return g_script.mTrayIconTip ? (VarSizeType)_tcslen(g_script.mTrayIconTip) : 0;
if (g_script.mTrayIconTip)
return (VarSizeType)_tcslen(_tcscpy(aBuf, g_script.mTrayIconTip));
else
{
*aBuf = '\0';
return 0;
}
}
VarSizeType BIV_IconFile(LPTSTR aBuf, LPTSTR aVarName)
{
if (!aBuf)
return g_script.mCustomIconFile ? (VarSizeType)_tcslen(g_script.mCustomIconFile) : 0;
if (g_script.mCustomIconFile)
return (VarSizeType)_tcslen(_tcscpy(aBuf, g_script.mCustomIconFile));
else
{
*aBuf = '\0';
return 0;
}
}
VarSizeType BIV_IconNumber(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_INTEGER_SIZE];
LPTSTR target_buf = aBuf ? aBuf : buf;
if (!g_script.mCustomIconNumber) // Yield an empty string rather than the digit "0".
{
*target_buf = '\0';
return 0;
}
return (VarSizeType)_tcslen(UTOA(g_script.mCustomIconNumber, target_buf));
}
VarSizeType BIV_PriorKey(LPTSTR aBuf, LPTSTR aVarName)
{
const int bufSize = 32;
if (!aBuf)
return bufSize;
*aBuf = '\0'; // Init for error & not-found cases
int validEventCount = 0;
// Start at the current event (offset 1)
for (int iOffset = 1; iOffset <= g_MaxHistoryKeys; ++iOffset)
{
// Get index for circular buffer
int i = (g_KeyHistoryNext + g_MaxHistoryKeys - iOffset) % g_MaxHistoryKeys;
// Keep looking until we hit the second valid event
if (g_KeyHistory[i].event_type != _T('i') && ++validEventCount > 1)
{
// Find the next most recent key-down
if (!g_KeyHistory[i].key_up)
{
GetKeyName(g_KeyHistory[i].vk, g_KeyHistory[i].sc, aBuf, bufSize);
break;
}
}
}
return (VarSizeType)_tcslen(aBuf);
}
#endif
VarSizeType BIV_ExitReason(LPTSTR aBuf, LPTSTR aVarName)
{
LPTSTR str;
switch(g_script.mExitReason)
{
case EXIT_LOGOFF: str = _T("Logoff"); break;
case EXIT_SHUTDOWN: str = _T("Shutdown"); break;
// Since the below are all relatively rare, except WM_CLOSE perhaps, they are all included
// as one word to cut down on the number of possible words (it's easier to write OnExit
// routines to cover all possibilities if there are fewer of them).
case EXIT_WM_QUIT:
case EXIT_CRITICAL:
case EXIT_DESTROY:
case EXIT_WM_CLOSE: str = _T("Close"); break;
case EXIT_ERROR: str = _T("Error"); break;
case EXIT_MENU: str = _T("Menu"); break; // Standard menu, not a user-defined menu.
case EXIT_EXIT: str = _T("Exit"); break; // ExitApp or Exit command.
case EXIT_RELOAD: str = _T("Reload"); break;
case EXIT_SINGLEINSTANCE: str = _T("Single"); break;
default: // EXIT_NONE or unknown value (unknown would be considered a bug if it ever happened).
str = _T("");
}
if (aBuf)
_tcscpy(aBuf, str);
return (VarSizeType)_tcslen(str);
}
VarSizeType BIV_Space_Tab(LPTSTR aBuf, LPTSTR aVarName)
{
// Really old comment:
// A_Space is a built-in variable rather than using an escape sequence such as `s, because the escape
// sequence method doesn't work (probably because `s resolves to a space and is trimmed at some point
// prior to when it can be used):
if (aBuf)
{
*aBuf++ = aVarName[5] ? ' ' : '\t'; // A_Tab[]
*aBuf = '\0';
}
return 1;
}
VarSizeType BIV_AhkVersion(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
_tcscpy(aBuf, T_AHK_VERSION);
return (VarSizeType)_tcslen(T_AHK_VERSION);
}
VarSizeType BIV_AhkPath(LPTSTR aBuf, LPTSTR aVarName) // v1.0.41.
{
#ifdef AUTOHOTKEYSC
if (aBuf)
{
size_t length;
if (length = GetAHKInstallDir(aBuf))
// Name "AutoHotkey.exe" is assumed for code size reduction and because it's not stored in the registry:
tcslcpy(aBuf + length, _T("\\AutoHotkey.exe"), MAX_PATH - length); // strlcpy() in case registry has a path that is too close to MAX_PATH to fit AutoHotkey.exe
//else leave it blank as documented.
return (VarSizeType)_tcslen(aBuf);
}
// Otherwise: Always return an estimate of MAX_PATH in case the registry entry changes between the
// first call and the second. This is also relied upon by strlcpy() above, which zero-fills the tail
// of the destination up through the limit of its capacity (due to calling strncpy, which does this).
return MAX_PATH;
#else
TCHAR buf[MAX_PATH];
VarSizeType length = (VarSizeType)GetModuleFileName(NULL, buf, MAX_PATH);
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like this one.
return length;
#endif
}
VarSizeType BIV_AhkDir(LPTSTR aBuf, LPTSTR aVarName) // v1.0.41.
{
#ifdef AUTOHOTKEYSC
if (aBuf)
{
GetAHKInstallDir(aBuf);
return (VarSizeType)_tcslen(aBuf);
}
// Otherwise: Always return an estimate of MAX_PATH in case the registry entry changes between the
// first call and the second. This is also relied upon by strlcpy() above, which zero-fills the tail
// of the destination up through the limit of its capacity (due to calling strncpy, which does this).
return MAX_PATH;
#else
TCHAR buf[MAX_PATH];
GetModuleFileName(NULL, buf, MAX_PATH);
VarSizeType length = (_tcsrchr(buf, L'\\') - buf);
if (aBuf)
{
_tcsncpy(aBuf, buf, length); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like this one.
*(aBuf + length) = L'\0';
}
return length;
#endif
}
VarSizeType BIV_DllPath(LPTSTR aBuf, LPTSTR aVarName) // HotKeyIt H1 path of loaded dll
{
TCHAR buf[MAX_PATH];
VarSizeType length = (VarSizeType)GetModuleFileName(g_hInstance, buf, _countof(buf));
if (length == 0)
VarSizeType length = (VarSizeType)GetModuleFileName(NULL, buf, _countof(buf));
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like this one.
return length;
}
VarSizeType BIV_DllDir(LPTSTR aBuf, LPTSTR aVarName) // HotKeyIt H1 path of loaded dll
{
TCHAR buf[MAX_PATH];
VarSizeType length = (VarSizeType)GetModuleFileName(g_hInstance, buf, _countof(buf));
if (length == 0)
GetModuleFileName(NULL, buf, _countof(buf));
length = _tcsrchr(buf, L'\\') - buf;
if (aBuf)
{
_tcsncpy(aBuf, buf, length); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like this one.
*(aBuf + length) = '\0';
}
return length;
}
VarSizeType BIV_TickCount(LPTSTR aBuf, LPTSTR aVarName)
{
return aBuf
? (VarSizeType)_tcslen(ITOA64(GetTickCount(), aBuf))
: MAX_INTEGER_LENGTH; // IMPORTANT: Conservative estimate because tick might change between 1st & 2nd calls.
}
VarSizeType BIV_Now(LPTSTR aBuf, LPTSTR aVarName)
{
if (!aBuf)
return DATE_FORMAT_LENGTH;
SYSTEMTIME st;
if (aVarName[5]) // A_Now[U]TC
GetSystemTime(&st);
else
GetLocalTime(&st);
SystemTimeToYYYYMMDD(aBuf, st);
return (VarSizeType)_tcslen(aBuf);
}
VarSizeType BIV_OSType(LPTSTR aBuf, LPTSTR aVarName)
{
LPTSTR type = g_os.IsWinNT() ? _T("WIN32_NT") : _T("WIN32_WINDOWS");
if (aBuf)
_tcscpy(aBuf, type);
return (VarSizeType)_tcslen(type); // Return length of type, not aBuf.
}
VarSizeType BIV_OSVersion(LPTSTR aBuf, LPTSTR aVarName)
{
LPCTSTR version = _T(""); // Init for maintainability.
if (g_os.IsWinNT()) // "NT" includes all NT-kernel OSes: NT4/2000/XP/2003/Vista/7/8/etc.
{
if (g_os.IsWinXP())
version = _T("WIN_XP");
else if (g_os.IsWin7())
version = _T("WIN_7");
else if (g_os.IsWin8_1())
version = _T("WIN_8.1");
else if (g_os.IsWin8())
version = _T("WIN_8");
else if (g_os.IsWinVista())
version = _T("WIN_VISTA");
else if (g_os.IsWin2003())
version = _T("WIN_2003");
else
{
if (g_os.IsWin2000())
version = _T("WIN_2000");
else if (g_os.IsWinNT4())
version = _T("WIN_NT4");
}
}
else
{
if (g_os.IsWin95())
version = _T("WIN_95");
else
{
if (g_os.IsWin98())
version = _T("WIN_98");
else
version = _T("WIN_ME");
}
}
if (aBuf)
_tcscpy(aBuf, version);
return (VarSizeType)_tcslen(version); // Always return the length of version, not aBuf.
}
VarSizeType BIV_Is64bitOS(LPTSTR aBuf, LPTSTR aVarName)
{
if (aBuf)
{
*aBuf++ = IsOS64Bit() ? '1' : '0';
*aBuf = '\0';
}
return 1;
}
VarSizeType BIV_Language(LPTSTR aBuf, LPTSTR aVarName)
// Registry locations from J-Paul Mesnage.
{
TCHAR buf[MAX_PATH];
VarSizeType length;
if (g_os.IsWinNT()) // NT/2k/XP+
length = g_os.IsWin2000orLater()
? ReadRegString(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\Nls\\Language"), _T("InstallLanguage"), buf, MAX_PATH)
: ReadRegString(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\Nls\\Language"), _T("Default"), buf, MAX_PATH); // NT4
else // Win9x
{
length = ReadRegString(HKEY_USERS, _T(".DEFAULT\\Control Panel\\Desktop\\ResourceLocale"), _T(""), buf, MAX_PATH);
if (length > 3)
{
length -= 4;
memmove(buf, buf + 4, length + 1); // +1 to include the zero terminator.
}
}
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string).
return length;
}
VarSizeType BIV_UserName_ComputerName(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_PATH]; // Doesn't use MAX_COMPUTERNAME_LENGTH + 1 in case longer names are allowed in the future.
DWORD buf_size = MAX_PATH; // Below: A_Computer[N]ame (N is the 11th char, index 10, which if present at all distinguishes between the two).
if ( !(aVarName[10] ? GetComputerName(buf, &buf_size) : GetUserName(buf, &buf_size)) )
*buf = '\0';
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the ones here.
return (VarSizeType)_tcslen(buf); // I seem to remember that the lengths returned from the above API calls aren't consistent in these cases.
}
VarSizeType BIV_WorkingDir(LPTSTR aBuf, LPTSTR aVarName)
{
// Use GetCurrentDirectory() vs. g_WorkingDir because any in-progress FileSelectFile()
// dialog is able to keep functioning even when it's quasi-thread is suspended. The
// dialog can thus change the current directory as seen by the active quasi-thread even
// though g_WorkingDir hasn't been updated. It might also be possible for the working
// directory to change in unusual circumstances such as a network drive being lost).
//
// Fix for v1.0.43.11: Changed size below from 9999 to MAX_PATH, otherwise it fails sometimes on Win9x.
// Testing shows that the failure is not caused by GetCurrentDirectory() writing to the unused part of the
// buffer, such as zeroing it (which is good because that would require this part to be redesigned to pass
// the actual buffer size or use a temp buffer). So there's something else going on to explain why the
// problem only occurs in longer scripts on Win98se, not in trivial ones such as Var=%A_WorkingDir%.
// Nor did the problem affect expression assignments such as Var:=A_WorkingDir.
TCHAR buf[MAX_PATH];
VarSizeType length = GetCurrentDirectory(MAX_PATH, buf);
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here.
return length;
// Formerly the following, but I don't think it's as reliable/future-proof given the 1.0.47 comment above:
//return aBuf
// ? GetCurrentDirectory(MAX_PATH, aBuf)
// : GetCurrentDirectory(0, NULL); // MSDN says that this is a valid way to call it on all OSes, and testing shows that it works on WinXP and 98se.
// Above avoids subtracting 1 to be conservative and to reduce code size (due to the need to otherwise check for zero and avoid subtracting 1 in that case).
}
VarSizeType BIV_WinDir(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_PATH];
VarSizeType length = GetWindowsDirectory(buf, MAX_PATH);
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here.
return length;
// Formerly the following, but I don't think it's as reliable/future-proof given the 1.0.47 comment above:
//TCHAR buf_temp[1]; // Just a fake buffer to pass to some API functions in lieu of a NULL, to avoid any chance of misbehavior. Keep the size at 1 so that API functions will always fail to copy to buf.
//// Sizes/lengths/-1/return-values/etc. have been verified correct.
//return aBuf
// ? GetWindowsDirectory(aBuf, MAX_PATH) // MAX_PATH is kept in case it's needed on Win9x for reasons similar to those in GetEnvironmentVarWin9x().
// : GetWindowsDirectory(buf_temp, 0);
// Above avoids subtracting 1 to be conservative and to reduce code size (due to the need to otherwise check for zero and avoid subtracting 1 in that case).
}
VarSizeType BIV_Temp(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_PATH];
VarSizeType length = GetTempPath(MAX_PATH, buf);
if (aBuf)
{
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here.
if (length)
{
aBuf += length - 1;
if (*aBuf == '\\') // For some reason, it typically yields a trailing backslash, so omit it to improve friendliness/consistency.
{
*aBuf = '\0';
--length;
}
}
}
return length;
}
VarSizeType BIV_ComSpec(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf_temp[1]; // Just a fake buffer to pass to some API functions in lieu of a NULL, to avoid any chance of misbehavior. Keep the size at 1 so that API functions will always fail to copy to buf.
// Sizes/lengths/-1/return-values/etc. have been verified correct.
return aBuf ? GetEnvVarReliable(_T("comspec"), aBuf) // v1.0.46.08: GetEnvVarReliable() fixes %Comspec% on Windows 9x.
: GetEnvironmentVariable(_T("comspec"), buf_temp, 0); // Avoids subtracting 1 to be conservative and to reduce code size (due to the need to otherwise check for zero and avoid subtracting 1 in that case).
}
VarSizeType BIV_SpecialFolderPath(LPTSTR aBuf, LPTSTR aVarName)
{
TCHAR buf[MAX_PATH]; // One caller relies on this being explicitly limited to MAX_PATH.
int aFolder;
switch (ctoupper(aVarName[2]))
{
case 'P': // A_[P]rogram...
case 'O': // Pr[o]gramFiles
if (ctoupper(aVarName[9]) == 'S') // A_Programs(Common)
aFolder = aVarName[10] ? CSIDL_COMMON_PROGRAMS : CSIDL_PROGRAMS;
else // A_Program[F]iles or ProgramFi[L]es
aFolder = CSIDL_PROGRAM_FILES;
break;
case 'A': // A_AppData(Common)
aFolder = aVarName[9] ? CSIDL_COMMON_APPDATA : CSIDL_APPDATA;
break;
case 'D': // A_Desktop(Common)
aFolder = aVarName[9] ? CSIDL_COMMON_DESKTOPDIRECTORY : CSIDL_DESKTOPDIRECTORY;
break;
case 'S':
if (ctoupper(aVarName[7]) == 'M') // A_Start[M]enu(Common)
aFolder = aVarName[11] ? CSIDL_COMMON_STARTMENU : CSIDL_STARTMENU;
else // A_Startup(Common)
aFolder = aVarName[9] ? CSIDL_COMMON_STARTUP : CSIDL_STARTUP;
break;
#ifdef _DEBUG
default:
MsgBox(_T("DEBUG: Unhandled SpecialFolderPath variable."));
#endif
}
if (SHGetFolderPath(NULL, aFolder, NULL, SHGFP_TYPE_CURRENT, buf) != S_OK)
*buf = '\0';
if (aBuf)
_tcscpy(aBuf, buf); // Must be done as a separate copy because SHGetFolderPath requires a buffer of length MAX_PATH, and aBuf is usually smaller.
return _tcslen(buf);
}
VarSizeType BIV_MyDocuments(LPTSTR aBuf, LPTSTR aVarName) // Called by multiple callers.
{
TCHAR buf[MAX_PATH];
if (SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, buf) != S_OK)
*buf = '\0';
// Since it is common (such as in networked environments) to have My Documents on the root of a drive
// (such as a mapped drive letter), remove the backslash from something like M:\ because M: is more
// appropriate for most uses:
VarSizeType length = (VarSizeType)strip_trailing_backslash(buf);
if (aBuf)
_tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string).
return length;
}
VarSizeType BIV_Caret(LPTSTR aBuf, LPTSTR aVarName)
{
if (!aBuf)
return MAX_INTEGER_LENGTH; // Conservative, both for performance and in case the value changes between first and second call.
// These static variables are used to keep the X and Y coordinates in sync with each other, as a snapshot
// of where the caret was at one precise instant in time. This is because the X and Y vars are resolved
// separately by the script, and due to split second timing, they might otherwise not be accurate with
// respect to each other. This method also helps performance since it avoids unnecessary calls to
// ATTACH_THREAD_INPUT.
static HWND sForeWinPrev = NULL;
static DWORD sTimestamp = GetTickCount();
static POINT sPoint;
static BOOL sResult;
// I believe only the foreground window can have a caret position due to relationship with focused control.
HWND target_window = GetForegroundWindow(); // Variable must be named target_window for ATTACH_THREAD_INPUT.
if (!target_window) // No window is in the foreground, report blank coordinate.
{
*aBuf = '\0';
return 0;
}
DWORD now_tick = GetTickCount();
if (target_window != sForeWinPrev || now_tick - sTimestamp > 5) // Different window or too much time has passed.
{
// Otherwise:
ATTACH_THREAD_INPUT
sResult = GetCaretPos(&sPoint);
HWND focused_control = GetFocus(); // Also relies on threads being attached.
DETACH_THREAD_INPUT
if (!sResult)
{
*aBuf = '\0';
return 0;
}
// Unconditionally convert to screen coordinates, for simplicity.
|
tinku99/ahkdll
|
284ea15e1184d405345cea45b8532d44b53ffbaa
|
Bug fix in Struct
|
diff --git a/source/script_struct.cpp b/source/script_struct.cpp
index e620c0e..16427e3 100644
--- a/source/script_struct.cpp
+++ b/source/script_struct.cpp
@@ -1,879 +1,886 @@
#include "stdafx.h" // pre-compiled headers
#include "defines.h"
#include "application.h"
#include "globaldata.h"
#include "script.h"
#include "TextIO.h"
#include "script_object.h"
//
// Struct::Create - Called by BIF_ObjCreate to create a new object, optionally passing key/value pairs to set.
//
Struct *Struct::Create(ExprTokenType *aParam[], int aParamCount)
// This code is very similar to BIF_sizeof so should be maintained together
{
int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system
int offset = 0; // also used to calculate total size of structure
int arraydef = 0; // count arraysize to update offset
int unionoffset[100]; // backup offset before we enter union or structure
int unionsize[100]; // calculate unionsize
bool unionisstruct[100]; // updated to move offset for structure in structure
int totalunionsize = 0; // total size of all unions and structures in structure
int uniondepth = 0; // count how deep we are in union/structure
int ispointer = NULL; // identify pointer and how deep it goes
int aligntotal = 0; // pointer alignment for total structure
int thissize; // used to check if type was found in above array.
// following are used to find variable and also get size of a structure defined in variable
// this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit
ResultType Result = OK;
ExprTokenType ResultToken;
ExprTokenType Var1,Var2,Var3;
ExprTokenType *param[] = {&Var1,&Var2,&Var3};
Var1.symbol = SYM_VAR;
Var2.symbol = SYM_INTEGER;
Var3.symbol = SYM_INTEGER;
// will hold pointer to structure definition string while we parse trough it
TCHAR *buf;
size_t buf_size;
// Use enough buffer to accept any definition in a field.
TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment
// definition and field name are same max size as variables
// also add enough room to store pointers (**) and arrays [1000]
// give more room to use local or static variable Function(variable)
// Parameter passed to IsDefaultType needs to be ' Definition '
// this is because spaces are used as delimiters ( see IsDefaultType function )
TCHAR defbuf[MAX_VAR_NAME_LENGTH * 2 + 40] = _T(" UInt "); // Set default UInt definition
TCHAR keybuf[MAX_VAR_NAME_LENGTH + 40];
// buffer for arraysize + 2 for bracket ] and terminating character
TCHAR intbuf[MAX_INTEGER_LENGTH + 2];
FieldType *field; // used to define a field
// Structure object is saved in fixed order
// insert_pos is simply increased each time
// for loop will enumerate items in same order as it was created
IndexType insert_pos = 0;
// the new structure object
Struct *obj = new Struct();
if (TokenToObject(*aParam[0]))
{
obj->Release();
obj = ((Struct *)TokenToObject(*aParam[0]))->Clone();
if (aParamCount > 2)
{
obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]);
obj->ObjectToStruct(TokenToObject(*aParam[2]));
}
else if (aParamCount > 1)
{
if (TokenToObject(*aParam[1]))
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,offset);
obj->ObjectToStruct(TokenToObject(*aParam[1]));
}
else
obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]);
}
else
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
}
return obj;
}
// Set initial capacity to avoid multiple expansions.
// For simplicity, failure is handled by the loop below.
obj->SetInternalCapacity(aParamCount >> 1);
// Set buf to beginning of structure definition
buf = TokenToString(*aParam[0]);
// continue as long as we did not reach end of string / structure definition
while (*buf)
{
if (!_tcsncmp(buf,_T("//"),2)) // exclude comments
{
buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf));
if (!*buf)
break; // end of definition reached
}
if (buf == StrChrAny(buf,_T("\n\r\t ")))
{ // Ignore spaces, tabs and new lines before field definition
buf++;
continue;
}
else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,"))))
{ // union or structure in structure definition
if (!uniondepth++)
totalunionsize = 0; // done here to reduce code
if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{'))
unionisstruct[uniondepth] = true; // mark that union is a structure
else
unionisstruct[uniondepth] = false;
// backup offset because we need to set it back after this union / struct was parsed
// unionsize is initialized to 0 and buffer moved to next character
unionoffset[uniondepth] = offset; // backup offset
unionsize[uniondepth] = 0;
// ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union
buf = _tcschr(buf,'{') + 1;
continue;
}
else if (*buf == '}')
{ // update union
// restore offset even if we had a structure in structure
if (unionsize[uniondepth]>totalunionsize)
totalunionsize = unionsize[uniondepth];
// last item in union or structure, update offset now if not struct, for struct offset is up to date
if (--uniondepth == 0)
{
// end of structure, align it
if (totalunionsize % aligntotal)
totalunionsize += aligntotal - (totalunionsize % aligntotal);
if (!unionisstruct[uniondepth + 1]) // because it was decreased above
offset += totalunionsize;
else if (offset % aligntotal)
offset += aligntotal - (offset % aligntotal);
}
else
offset = unionoffset[uniondepth];
buf++;
if (buf == StrChrAny(buf,_T(";,")))
buf++;
continue;
}
// set defaults
ispointer = false;
arraydef = 0;
// copy current definition field to temporary buffer
if (StrChrAny(buf, _T("};,")))
{
if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1)
{
obj->Release();
return NULL;
}
_tcsncpy(tempbuf,buf,buf_size);
tempbuf[buf_size] = '\0';
}
else if (_tcslen(buf) > LINE_SIZE - 1)
{
obj->Release();
return NULL;
}
else
_tcscpy(tempbuf,buf);
// Trim trailing spaces
rtrim(tempbuf);
// Pointer
if (_tcschr(tempbuf, '*'))
ispointer = StrReplace(tempbuf, _T("*"), _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
// Array
if (_tcschr(tempbuf,'['))
{
_tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH);
intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0';
arraydef = (int)ATOI64(intbuf + 1);
// remove array definition from temp buffer to identify key easier
StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
// Trim trailing spaces in case we had a definition like UInt [10]
rtrim(tempbuf);
}
// copy type
// if offset is 0 and there are no };, characters, it means we have a pure definition
if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset))
{
if ((buf_size = _tcscspn(tempbuf,_T("\t "))) > MAX_VAR_NAME_LENGTH*2 + 30)
{
obj->Release();
return NULL;
}
_tcsncpy(defbuf + 1,tempbuf,buf_size);
//_tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t ")),_T(" "));
defbuf[1 + buf_size] = ' ';
defbuf[2 + buf_size] = '\0';
if (StrChrAny(tempbuf, _T(" \t")))
{
if (_tcslen(StrChrAny(tempbuf, _T(" \t"))) > MAX_VAR_NAME_LENGTH + 30)
{
obj->Release();
return NULL;
}
_tcscpy(keybuf,StrChrAny(tempbuf, _T(" \t")) + 1);
ltrim(keybuf);
}
else
keybuf[0] = '\0';
}
else // Not 'TypeOnly' definition because there are more than one fields in array so use previous type
{
// Commented following line to keep previous definition like in c++, e.g. "Int x,y,Char a,b",
// Note: separator , or ; can be still used but
// _tcscpy(defbuf,_T(" UInt "));
_tcscpy(keybuf,tempbuf);
}
// Now find size in default types array and create new field
// If Type not found, resolve type to variable and get size of struct defined in it
if ((thissize = IsDefaultType(defbuf)))
{
if (!_tcscmp(defbuf,_T(" bool ")))
thissize = 1;
// align offset
if (ispointer)
{
if (offset % ptrsize)
offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1);
if (ptrsize > aligntotal)
aligntotal = ptrsize;
}
else
{
if (offset % thissize)
offset += thissize - (offset % thissize);
if (thissize > aligntotal)
aligntotal = thissize > ptrsize ? ptrsize : thissize;
}
if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,NULL,thissize
,ispointer ? true : !tcscasestr(_T(" FLOAT DOUBLE PFLOAT PDOUBLE "),defbuf)
,!tcscasestr(_T(" PTR SHORT INT INT64 CHAR VOID HALF_PTR BOOL INT32 LONG LONG32 LONGLONG LONG64 USN INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM __int64 "),defbuf)
,tcscasestr(_T(" TCHAR LPTSTR LPCTSTR LPWSTR LPCWSTR WCHAR "),defbuf) ? 1200 : tcscasestr(_T(" CHAR LPSTR LPCSTR LPSTR UCHAR "),defbuf) ? 0 : -1)))
{ // Out of memory.
obj->Release();
return NULL;
}
offset += (ispointer ? ptrsize : thissize) * (arraydef ? arraydef : 1);
}
else // type was not found, check for user defined type in variables
{
Var1.var = NULL; // init to not found
Func *bkpfunc = NULL;
// check if we have a local/static declaration and resolve to function
// For example Struct("*MyFunc(mystruct) mystr")
if (_tcschr(defbuf,'('))
{
bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later
g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1);
if (g->CurrentFunc) // break if not found to identify error
{
_tcscpy(tempbuf,defbuf + 1);
_tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'('));
_tcscpy(_tcschr(defbuf,')'),_T(" \0"));
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL);
g->CurrentFunc = bkpfunc;
}
else // release object and return
{
g->CurrentFunc = bkpfunc;
obj->Release();
return NULL;
}
}
else if (g->CurrentFunc) // try to find local variable first
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL);
// try to find global variable if local was not found or we are not in func
if (Var1.var == NULL)
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL);
// variable found
if (Var1.var != NULL)
{
if (!ispointer && !_tcsncmp(tempbuf,buf,_tcslen(buf)) && !*keybuf)
{ // Whole definition is not a pointer and no key was given so create Structure from variable
obj->Release();
if (aParamCount == 1)
{
if (TokenToObject(*param[0]))
{ // assume variable is a structure object
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
return obj;
}
// else create structure from string definition
return Struct::Create(param,1);
}
else if (aParamCount > 1)
{ // more than one parameter was given, copy aParam to param
param[1]->symbol = aParam[1]->symbol;
param[1]->object = aParam[1]->object;
param[1]->value_int64 = aParam[1]->value_int64;
param[1]->var = aParam[1]->var;
}
if (aParamCount > 2)
{ // more than 2 parameters were given, copy aParam to param
param[2]->symbol = aParam[2]->symbol;
param[2]->object = aParam[2]->object;
param[2]->var = aParam[2]->var;
// definition variable is a structure object, clone it, assign memory and init object
if (TokenToObject(*param[0]))
{
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
obj->mMemAllocated = 0;
obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64;
obj->ObjectToStruct(TokenToObject(*aParam[2]));
return obj;
}
return Struct::Create(param,3);
}
else if (TokenToObject(*param[0]))
{ // definition variable is a structure object, clone it and assign memory or init object
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
if (TokenToObject(*aParam[1]))
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
obj->ObjectToStruct(TokenToObject(*aParam[1]));
}
else
obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64;
return obj;
}
// else simply create structure from variable and given memory/initobject
return Struct::Create(param,2);
}
// Call BIF_sizeof passing offset in second parameter to align offset if necessary
// if field is a pointer we will need its size only
if (!ispointer)
{
param[1]->value_int64 = (__int64)ispointer ? 0 : offset;
param[2]->value_int64 = (__int64)&aligntotal;
BIF_sizeof(Result,ResultToken,param,ispointer ? 1 : 3);
if (ResultToken.symbol != SYM_INTEGER)
{ // could not resolve structure
obj->Release();
return NULL;
}
}
else
{
+ param[1]->value_int64 = (__int64)0;
+ BIF_sizeof(Result,ResultToken, param, 1);
+ if (ResultToken.symbol != SYM_INTEGER)
+ { // could not resolve structure
+ obj->Release();
+ return NULL;
+ }
if (offset % ptrsize)
offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1);
if (ptrsize > aligntotal)
aligntotal = ptrsize;
}
// Insert new field in our structure
if (!(field = obj->Insert(keybuf, insert_pos++, ispointer, offset, arraydef, Var1.var, (int)ResultToken.value_int64,1,1,-1)))
{ // Out of memory.
obj->Release();
return NULL;
}
if (ispointer)
offset += (int)ptrsize * (arraydef ? arraydef : 1);
else
// sizeof was given an offset that it applied and aligned if necessary, so set offset = and not +=
offset = (int)ResultToken.value_int64 + (arraydef ? ((arraydef - 1) * ((int)ResultToken.value_int64 - offset)) : 0);
}
else // No variable was found and it is not default type so we can't determine size.
{
obj->Release();
return NULL;
}
}
// update union size
if (uniondepth)
{
if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth])
unionsize[uniondepth] = offset - unionoffset[uniondepth];
// reset offset if in union and union is not a structure
if (!unionisstruct[uniondepth])
offset = unionoffset[uniondepth];
}
// Move buffer pointer now
if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,"))))
buf += _tcscspn(buf,_T("}")); // keep } character to update union
else if (StrChrAny(buf, _T(";,")))
buf += _tcscspn(buf,_T(";,")) + 1;
else
{
// identify that structure object has no fields
if (!*keybuf)
obj->mTypeOnly = true;
buf += _tcslen(buf);
}
}
// align total structure if necessary
if (aligntotal && offset % aligntotal)
offset += aligntotal - (offset % aligntotal);
if (!offset) // structure could not be build
{
obj->Release();
return NULL;
}
obj->mSize = offset;
if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1]))
{ // second parameter exist and it is digit assumme this is new pointer for our structure
obj->mStructMem = (UINT_PTR *)TokenToInt64(*aParam[1]);
obj->mMemAllocated = 0;
}
else // no pointer given so allocate memory and fill memory with 0
{ // setting the memory after parsing definition saves a call to BIF_sizeof
obj->mStructMem = (UINT_PTR *)malloc(offset);
obj->mMemAllocated = offset;
memset(obj->mStructMem,NULL,offset);
}
// an object was passed to initialize fields
// enumerate trough object and assign values
if ((aParamCount > 1 && !TokenIsPureNumeric(*aParam[1])) || aParamCount > 2 )
obj->ObjectToStruct(TokenToObject(*aParam[aParamCount - 1]));
return obj;
}
//
// Struct::ObjectToStruct - Initialize structure from array, object or structure.
//
void Struct::ObjectToStruct(IObject *objfrom)
{
ExprTokenType ResultToken, this_token,enum_token,param_tokens[3];
ExprTokenType *params[] = { param_tokens, param_tokens+1, param_tokens+2 };
TCHAR defbuf[MAX_PATH],buf[MAX_PATH];
int param_count = 3;
// Set up enum_token the way Invoke expects:
enum_token.symbol = SYM_STRING;
enum_token.marker = _T("");
enum_token.mem_to_free = NULL;
enum_token.buf = defbuf;
// Prepare to call object._NewEnum():
param_tokens[0].symbol = SYM_STRING;
param_tokens[0].marker = _T("_NewEnum");
objfrom->Invoke(enum_token, ResultToken, IT_CALL, params, 1);
if (enum_token.mem_to_free)
// Invoke returned memory for us to free.
free(enum_token.mem_to_free);
// Check if object returned an enumerator, otherwise return
if (enum_token.symbol != SYM_OBJECT)
return;
// create variables to use in for loop / for enumeration
// these will be deleted afterwards
Var *var1 = (Var*)alloca(sizeof(Var));
Var *var2 = (Var*)alloca(sizeof(Var));
var1->mType = var2->mType = VAR_NORMAL;
var1->mAttrib = var2->mAttrib = 0;
var1->mByteCapacity = var2->mByteCapacity = 0;
var1->mHowAllocated = var2->mHowAllocated = ALLOC_MALLOC;
// Prepare parameters for the loop below: enum.Next(var1 [, var2])
param_tokens[0].marker = _T("Next");
param_tokens[1].symbol = SYM_VAR;
param_tokens[1].var = var1;
param_tokens[1].mem_to_free = 0;
param_tokens[2].symbol = SYM_VAR;
param_tokens[2].var = var2;
param_tokens[2].mem_to_free = 0;
ExprTokenType result_token;
IObject &enumerator = *enum_token.object; // Might perform better as a reference?
this_token.symbol = SYM_OBJECT;
this_token.object = this;
for (;;)
{
// Set up result_token the way Invoke expects; each Invoke() will change some or all of these:
result_token.symbol = SYM_STRING;
result_token.marker = _T("");
result_token.mem_to_free = NULL;
result_token.buf = buf;
// Call enumerator.Next(var1, var2)
enumerator.Invoke(result_token,enum_token,IT_CALL, params, param_count);
bool next_returned_true = TokenToBOOL(result_token, TokenIsPureNumeric(result_token));
if (!next_returned_true)
break;
this->Invoke(ResultToken,this_token,IT_SET,params+1,2);
// release object if it was assigned prevoiously when calling enum.Next
if (var1->IsObject())
var1->ReleaseObject();
if (var2->IsObject())
var2->ReleaseObject();
// Free any memory or object which may have been returned by Invoke:
if (result_token.mem_to_free)
free(result_token.mem_to_free);
if (result_token.symbol == SYM_OBJECT)
result_token.object->Release();
}
// release enumerator and free vars
enumerator.Release();
var1->Free();
var2->Free();
}
//
// Struct::Delete - Called immediately before the object is deleted.
// Returns false if object should not be deleted yet.
//
bool Struct::Delete()
{
return ObjectBase::Delete();
}
Struct::~Struct()
{
if (mMemAllocated > 0)
free(mStructMem);
if (mFields)
{
if (mFieldCount)
{
IndexType i = mFieldCount - 1;
// Free keys
for ( ; i >= 0 ; --i)
{
if (mFields[i].mMemAllocated > 0)
free(mFields[i].mStructMem);
free(mFields[i].key);
}
}
// Free fields array.
free(mFields);
}
}
//
// Struct::SetPointer - used to set pointer for a field or array item
//
UINT_PTR Struct::SetPointer(UINT_PTR aPointer,int aArrayItem)
{
if (mIsPointer)
*((UINT_PTR*)(*mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer;
else
*((UINT_PTR*)((UINT_PTR)mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer;
return aPointer;
}
//
// Struct::FieldType::Clone - used to clone a field to structure.
//
Struct *Struct::CloneField(FieldType *field,bool aIsDynamic)
// Creates an object and copies to it the fields at and after the given offset.
{
Struct *objptr = new Struct();
if (!objptr)
return objptr;
Struct &obj = *objptr;
// if field is an array, set correct size
if (obj.mArraySize = field->mArraySize)
obj.mSize = field->mSize*obj.mArraySize;
else
obj.mSize = field->mSize;
obj.mIsInteger = field->mIsInteger;
obj.mIsPointer = field->mIsPointer;
obj.mEncoding = field->mEncoding;
obj.mIsUnsigned = field->mIsUnsigned;
obj.mVarRef = field->mVarRef;
obj.mTypeOnly = 1;
obj.mMemAllocated = aIsDynamic ? -1 : 0;
return objptr;
}
//
// Struct::Clone - used for cloning structures.
//
Struct *Struct::Clone(bool aIsDynamic)
// Creates an object and copies to it the fields at and after the given offset.
{
Struct *objptr = new Struct();
if (!objptr)
return objptr;
Struct &obj = *objptr;
obj.mArraySize = mArraySize;
obj.mIsInteger = mIsInteger;
obj.mIsPointer = mIsPointer;
obj.mEncoding = mEncoding;
obj.mIsUnsigned = mIsUnsigned;
obj.mSize = mSize;
obj.mVarRef = mVarRef;
obj.mTypeOnly = mTypeOnly;
// -1 will identify a dynamic structure, no memory can be allocated to such
obj.mMemAllocated = aIsDynamic ? -1 : 0;
// Allocate space in destination object.
if (!obj.SetInternalCapacity(mFieldCount))
{
obj.Release();
return NULL;
}
FieldType *fields = obj.mFields; // Newly allocated by above.
int failure_count = 0; // See comment below.
IndexType i;
obj.mFieldCount = mFieldCount;
for (i = 0; i < mFieldCount; ++i)
{
FieldType &dst = fields[i];
FieldType &src = mFields[i];
if ( !(dst.key = _tcsdup(src.key)) )
{
// Key allocation failed.
// Rather than trying to set up the object so that what we have
// so far is valid in order to break out of the loop, continue,
// make all fields valid and then allow them to be freed.
++failure_count;
}
dst.mArraySize = src.mArraySize;
dst.mIsInteger = src.mIsInteger;
dst.mIsPointer = src.mIsPointer;
dst.mEncoding = src.mEncoding;
dst.mIsUnsigned = src.mIsUnsigned;
dst.mOffset = src.mOffset;
dst.mSize = src.mSize;
dst.mVarRef = src.mVarRef;
dst.mMemAllocated = aIsDynamic ? -1 : 0;
}
if (failure_count)
{
// One or more memory allocations failed. It seems best to return a clear failure
// indication rather than an incomplete copy. Now that the loop above has finished,
// the object's contents are at least valid and it is safe to free the object:
obj.Release();
return NULL;
}
return &obj;
}
//
// Struct::Invoke - Called by BIF_ObjInvoke when script explicitly interacts with an object.
//
ResultType STDMETHODCALLTYPE Struct::Invoke(
ExprTokenType &aResultToken,
ExprTokenType &aThisToken,
int aFlags,
ExprTokenType *aParam[],
int aParamCount
)
// L40: Revised base mechanism for flexibility and to simplify some aspects.
// obj[] -> obj.base.__Get -> obj.base[] -> obj.base.__Get etc.
{
int ptrsize = sizeof(UINT_PTR);
FieldType *field = NULL; // init to NULL to use in IS_INVOKE_CALL
ResultType Result = OK;
// Used to resolve dynamic structures
ExprTokenType Var1,Var2;
Var1.symbol = SYM_VAR;
Var2.symbol = SYM_INTEGER;
ExprTokenType *param[] = {&Var1,&Var2},ResultToken;
// used to clone a dynamic field or structure
Struct *objclone = NULL;
// used for StrGet/StrPut
LPCVOID source_string;
int source_length;
DWORD flags = WC_NO_BEST_FIT_CHARS;
int length = -1;
int char_count;
// Identify that we need to release/delete field or structure object
bool deletefield = false;
bool releaseobj = false;
int param_count_excluding_rvalue = aParamCount;
// target may be altered here to resolve dynamic structure so hold it separately
UINT_PTR *target = mStructMem;
if (IS_INVOKE_SET)
{
// Prior validation of ObjSet() param count ensures the result won't be negative:
--param_count_excluding_rvalue;
// Since defining base[key] prevents base.base.__Get and __Call from being invoked, it seems best
// to have it also block __Set. The code below is disabled to achieve this, with a slight cost to
// performance when assigning to a new key in any object which has a base object. (The cost may
// depend on how many key-value pairs each base object has.) Note that this doesn't affect meta-
// functions defined in *this* base object, since they were already invoked if present.
//if (IS_INVOKE_META)
//{
// if (param_count_excluding_rvalue == 1)
// // Prevent below from unnecessarily searching for a field, since it won't actually be assigned to.
// // Relies on mBase->Invoke recursion using aParamCount and not param_count_excluding_rvalue.
// param_count_excluding_rvalue = 0;
// //else: Allow SET to operate on a field of an object stored in the target's base.
// // For instance, x[y,z]:=w may operate on x[y][z], x.base[y][z], x[y].base[z], etc.
//}
}
if (!param_count_excluding_rvalue || (param_count_excluding_rvalue == 1 && TokenIsEmptyString(*aParam[0])))
{ // for struct[] and struct[""...] / struct[] := ptr and struct[""...] := ptr
if (IS_INVOKE_SET)
{
if (TokenToObject(*aParam[param_count_excluding_rvalue]))
{ // Initialize structure using an object. e.g. struct[]:={x:1,y:2}
this->ObjectToStruct(TokenToObject(*aParam[param_count_excluding_rvalue]));
// return struct object
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = this;
this->AddRef();
return OK;
}
if (mMemAllocated > 0) // free allocated memory because we will assign a custom pointer
{
free(mStructMem);
mMemAllocated = 0;
}
// assign new pointer to structure
// releasing/deleting structure will not free that memory
mStructMem = (UINT_PTR *)TokenToInt64(*aParam[param_count_excluding_rvalue]);
}
// Return new structure address
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = (__int64)mStructMem;
return OK;
}
else
{
// Array access, struct.1 or struct[1] or struct[1].x ...
if (TokenIsPureNumeric(*aParam[0]))
{
if (param_count_excluding_rvalue > 1 && TokenIsEmptyString(*aParam[1]))
{ // caller wants set/get pointer. E.g. struct.2[""] or struct.2[""] := ptr
if (IS_INVOKE_SET)
{
if (param_count_excluding_rvalue < 3) // simply set pointer
aResultToken.value_int64 = SetPointer((UINT_PTR)TokenToInt64(*aParam[2]),(int)TokenToInt64(*aParam[0]));
else
{ // resolve pointer to pointer and set it
UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + (TokenToInt64(*aParam[0])-1)*(mSize/(mArraySize ? mArraySize : 1))));
for (int i = param_count_excluding_rvalue - 2;i && aDeepPointer;i--)
aDeepPointer = (UINT_PTR*)*aDeepPointer;
*aDeepPointer = (UINT_PTR)TokenToInt64(*aParam[aParamCount]);
aResultToken.value_int64 = *aDeepPointer;
}
}
else // GET pointer
{
if (param_count_excluding_rvalue < 3)
aResultToken.value_int64 = ((mIsPointer ? *target : (UINT_PTR)target) + (TokenToInt64(*aParam[0])-1)*(mSize / (mArraySize ? mArraySize : 1)));
else
{ // resolve pointer to pointer
UINT_PTR *aDeepPointer = ((UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mSize/(mArraySize ? mArraySize : 1))));
for (int i = param_count_excluding_rvalue - 2;i && *aDeepPointer;i--)
aDeepPointer = (UINT_PTR*)*aDeepPointer;
aResultToken.value_int64 = (__int64)aDeepPointer;
}
}
aResultToken.symbol = SYM_INTEGER;
return OK;
}
// Structure is a reference to variable and not a pointer, get size of structure
if (mVarRef) // && !mIsPointer)
{
Var2.symbol = SYM_VAR;
Var2.var = mVarRef;
// Variable is a structure object, copy size
if (TokenToObject(Var2))
ResultToken.value_int64 = ((Struct *)TokenToObject(Var2))->mSize;
else
{ // use sizeof to find out the size of structure
param[0]->symbol = SYM_STRING;
Var1.marker = TokenToString(*param[1]);
BIF_sizeof(Result,ResultToken,param,1);
}
}
// Check if we have an array, if structure is not array and not pointer, assume array
if (mIsPointer) // resolve pointer
target = (UINT_PTR*)(*target + (TokenToInt64(*aParam[0]) - 1)*(mIsPointer>1 ? ptrsize : (mVarRef ? ResultToken.value_int64 : mSize / (mArraySize ? mArraySize : 1))));
else // amend target to memory of field, if it is not an array and not a pointer assume array
target = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0]) - 1)*(mVarRef ? ResultToken.value_int64 : mSize / (mArraySize ? mArraySize : 1)));
// Structure has a variable reference and might be a pointer but not pointer to pointer
if (mVarRef && mIsPointer < 2)
{
Var2.symbol = SYM_VAR;
Var2.var = mVarRef;
// variable is a structure object, clone it
if (TokenToObject(Var2))
{
objclone = ((Struct *)TokenToObject(Var2))->Clone(true);
objclone->mStructMem = target;
if (mArraySize)
{
objclone->mArraySize = 0;
objclone->mSize = mSize / mArraySize;
}
// Object to Structure
if (IS_INVOKE_SET && TokenToObject(*aParam[1]))
{
objclone->ObjectToStruct(TokenToObject(*aParam[1]));
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = objclone;
return OK;
}
// MULTIPARAM
if (param_count_excluding_rvalue > 1)
{
objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1);
objclone->Release();
return OK;
}
aResultToken.object = objclone;
aResultToken.symbol = SYM_OBJECT;
return OK;
}
else
{
Var1.symbol = SYM_STRING;
Var1.marker = TokenToString(Var2);
Var2.symbol = SYM_INTEGER;
Var2.value_int64 = (UINT_PTR)target;
if (objclone = Struct::Create(param,2))
{
Struct *tempobj = objclone;
objclone = objclone->Clone(true);
objclone->mStructMem = tempobj->mStructMem;
/*
if (mArraySize)
{
objclone->mArraySize = 0;
objclone->mSize = mSize / mArraySize;
|
tinku99/ahkdll
|
fc8f9d39f624e8aeb87237ef85b3e38c27362646
|
Apply previous type for Struct "LPTSTR a,b"
|
diff --git a/source/script_struct.cpp b/source/script_struct.cpp
index 6549e9b..e620c0e 100644
--- a/source/script_struct.cpp
+++ b/source/script_struct.cpp
@@ -1,743 +1,744 @@
#include "stdafx.h" // pre-compiled headers
#include "defines.h"
#include "application.h"
#include "globaldata.h"
#include "script.h"
#include "TextIO.h"
#include "script_object.h"
//
// Struct::Create - Called by BIF_ObjCreate to create a new object, optionally passing key/value pairs to set.
//
Struct *Struct::Create(ExprTokenType *aParam[], int aParamCount)
// This code is very similar to BIF_sizeof so should be maintained together
{
int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system
int offset = 0; // also used to calculate total size of structure
int arraydef = 0; // count arraysize to update offset
int unionoffset[100]; // backup offset before we enter union or structure
int unionsize[100]; // calculate unionsize
bool unionisstruct[100]; // updated to move offset for structure in structure
int totalunionsize = 0; // total size of all unions and structures in structure
int uniondepth = 0; // count how deep we are in union/structure
int ispointer = NULL; // identify pointer and how deep it goes
int aligntotal = 0; // pointer alignment for total structure
int thissize; // used to check if type was found in above array.
// following are used to find variable and also get size of a structure defined in variable
// this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit
ResultType Result = OK;
ExprTokenType ResultToken;
ExprTokenType Var1,Var2,Var3;
ExprTokenType *param[] = {&Var1,&Var2,&Var3};
Var1.symbol = SYM_VAR;
Var2.symbol = SYM_INTEGER;
Var3.symbol = SYM_INTEGER;
// will hold pointer to structure definition string while we parse trough it
TCHAR *buf;
size_t buf_size;
// Use enough buffer to accept any definition in a field.
TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment
// definition and field name are same max size as variables
// also add enough room to store pointers (**) and arrays [1000]
- TCHAR defbuf[MAX_VAR_NAME_LENGTH*2 + 40]; // give more room to use local or static variable Function(variable)
+ // give more room to use local or static variable Function(variable)
+ // Parameter passed to IsDefaultType needs to be ' Definition '
+ // this is because spaces are used as delimiters ( see IsDefaultType function )
+ TCHAR defbuf[MAX_VAR_NAME_LENGTH * 2 + 40] = _T(" UInt "); // Set default UInt definition
+
TCHAR keybuf[MAX_VAR_NAME_LENGTH + 40];
// buffer for arraysize + 2 for bracket ] and terminating character
TCHAR intbuf[MAX_INTEGER_LENGTH + 2];
FieldType *field; // used to define a field
// Structure object is saved in fixed order
// insert_pos is simply increased each time
// for loop will enumerate items in same order as it was created
IndexType insert_pos = 0;
// the new structure object
Struct *obj = new Struct();
-
- // Parameter passed to IsDefaultType needs to be ' Definition '
- // this is because spaces are used as delimiters ( see IsDefaultType function )
- // So first character will be always a space
- defbuf[0] = ' ';
-
if (TokenToObject(*aParam[0]))
{
obj->Release();
obj = ((Struct *)TokenToObject(*aParam[0]))->Clone();
if (aParamCount > 2)
{
obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]);
obj->ObjectToStruct(TokenToObject(*aParam[2]));
}
else if (aParamCount > 1)
{
if (TokenToObject(*aParam[1]))
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,offset);
obj->ObjectToStruct(TokenToObject(*aParam[1]));
}
else
obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]);
}
else
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
}
return obj;
}
// Set initial capacity to avoid multiple expansions.
// For simplicity, failure is handled by the loop below.
obj->SetInternalCapacity(aParamCount >> 1);
// Set buf to beginning of structure definition
buf = TokenToString(*aParam[0]);
// continue as long as we did not reach end of string / structure definition
while (*buf)
{
if (!_tcsncmp(buf,_T("//"),2)) // exclude comments
{
buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf));
if (!*buf)
break; // end of definition reached
}
if (buf == StrChrAny(buf,_T("\n\r\t ")))
{ // Ignore spaces, tabs and new lines before field definition
buf++;
continue;
}
else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,"))))
{ // union or structure in structure definition
if (!uniondepth++)
totalunionsize = 0; // done here to reduce code
if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{'))
unionisstruct[uniondepth] = true; // mark that union is a structure
else
unionisstruct[uniondepth] = false;
// backup offset because we need to set it back after this union / struct was parsed
// unionsize is initialized to 0 and buffer moved to next character
unionoffset[uniondepth] = offset; // backup offset
unionsize[uniondepth] = 0;
// ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union
buf = _tcschr(buf,'{') + 1;
continue;
}
else if (*buf == '}')
{ // update union
// restore offset even if we had a structure in structure
if (unionsize[uniondepth]>totalunionsize)
totalunionsize = unionsize[uniondepth];
// last item in union or structure, update offset now if not struct, for struct offset is up to date
if (--uniondepth == 0)
{
// end of structure, align it
if (totalunionsize % aligntotal)
totalunionsize += aligntotal - (totalunionsize % aligntotal);
if (!unionisstruct[uniondepth + 1]) // because it was decreased above
offset += totalunionsize;
else if (offset % aligntotal)
offset += aligntotal - (offset % aligntotal);
}
else
offset = unionoffset[uniondepth];
buf++;
if (buf == StrChrAny(buf,_T(";,")))
buf++;
continue;
}
// set defaults
ispointer = false;
arraydef = 0;
// copy current definition field to temporary buffer
if (StrChrAny(buf, _T("};,")))
{
if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1)
{
obj->Release();
return NULL;
}
_tcsncpy(tempbuf,buf,buf_size);
tempbuf[buf_size] = '\0';
}
else if (_tcslen(buf) > LINE_SIZE - 1)
{
obj->Release();
return NULL;
}
else
_tcscpy(tempbuf,buf);
// Trim trailing spaces
rtrim(tempbuf);
-
+
// Pointer
- if (_tcschr(tempbuf,'*'))
+ if (_tcschr(tempbuf, '*'))
ispointer = StrReplace(tempbuf, _T("*"), _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
// Array
if (_tcschr(tempbuf,'['))
{
_tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH);
intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0';
arraydef = (int)ATOI64(intbuf + 1);
// remove array definition from temp buffer to identify key easier
StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
// Trim trailing spaces in case we had a definition like UInt [10]
rtrim(tempbuf);
}
// copy type
// if offset is 0 and there are no };, characters, it means we have a pure definition
if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset))
{
if ((buf_size = _tcscspn(tempbuf,_T("\t "))) > MAX_VAR_NAME_LENGTH*2 + 30)
{
obj->Release();
return NULL;
}
_tcsncpy(defbuf + 1,tempbuf,buf_size);
//_tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t ")),_T(" "));
defbuf[1 + buf_size] = ' ';
defbuf[2 + buf_size] = '\0';
if (StrChrAny(tempbuf, _T(" \t")))
{
if (_tcslen(StrChrAny(tempbuf, _T(" \t"))) > MAX_VAR_NAME_LENGTH + 30)
{
obj->Release();
return NULL;
}
_tcscpy(keybuf,StrChrAny(tempbuf, _T(" \t")) + 1);
ltrim(keybuf);
}
else
keybuf[0] = '\0';
}
- else // Not 'TypeOnly' definition because there are more than one fields in array so use default type UInt
+ else // Not 'TypeOnly' definition because there are more than one fields in array so use previous type
{
- _tcscpy(defbuf,_T(" UInt "));
+ // Commented following line to keep previous definition like in c++, e.g. "Int x,y,Char a,b",
+ // Note: separator , or ; can be still used but
+ // _tcscpy(defbuf,_T(" UInt "));
_tcscpy(keybuf,tempbuf);
}
+
// Now find size in default types array and create new field
// If Type not found, resolve type to variable and get size of struct defined in it
if ((thissize = IsDefaultType(defbuf)))
{
if (!_tcscmp(defbuf,_T(" bool ")))
thissize = 1;
// align offset
if (ispointer)
{
if (offset % ptrsize)
offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1);
if (ptrsize > aligntotal)
aligntotal = ptrsize;
}
else
{
if (offset % thissize)
offset += thissize - (offset % thissize);
if (thissize > aligntotal)
aligntotal = thissize > ptrsize ? ptrsize : thissize;
}
if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,NULL,thissize
,ispointer ? true : !tcscasestr(_T(" FLOAT DOUBLE PFLOAT PDOUBLE "),defbuf)
,!tcscasestr(_T(" PTR SHORT INT INT64 CHAR VOID HALF_PTR BOOL INT32 LONG LONG32 LONGLONG LONG64 USN INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM __int64 "),defbuf)
,tcscasestr(_T(" TCHAR LPTSTR LPCTSTR LPWSTR LPCWSTR WCHAR "),defbuf) ? 1200 : tcscasestr(_T(" CHAR LPSTR LPCSTR LPSTR UCHAR "),defbuf) ? 0 : -1)))
{ // Out of memory.
obj->Release();
return NULL;
}
offset += (ispointer ? ptrsize : thissize) * (arraydef ? arraydef : 1);
}
else // type was not found, check for user defined type in variables
{
Var1.var = NULL; // init to not found
Func *bkpfunc = NULL;
// check if we have a local/static declaration and resolve to function
// For example Struct("*MyFunc(mystruct) mystr")
if (_tcschr(defbuf,'('))
{
bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later
g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1);
if (g->CurrentFunc) // break if not found to identify error
{
_tcscpy(tempbuf,defbuf + 1);
_tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'('));
_tcscpy(_tcschr(defbuf,')'),_T(" \0"));
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL);
g->CurrentFunc = bkpfunc;
}
else // release object and return
{
g->CurrentFunc = bkpfunc;
obj->Release();
return NULL;
}
}
else if (g->CurrentFunc) // try to find local variable first
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL);
// try to find global variable if local was not found or we are not in func
if (Var1.var == NULL)
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL);
// variable found
if (Var1.var != NULL)
{
if (!ispointer && !_tcsncmp(tempbuf,buf,_tcslen(buf)) && !*keybuf)
{ // Whole definition is not a pointer and no key was given so create Structure from variable
obj->Release();
if (aParamCount == 1)
{
if (TokenToObject(*param[0]))
{ // assume variable is a structure object
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
return obj;
}
// else create structure from string definition
return Struct::Create(param,1);
}
else if (aParamCount > 1)
{ // more than one parameter was given, copy aParam to param
param[1]->symbol = aParam[1]->symbol;
param[1]->object = aParam[1]->object;
param[1]->value_int64 = aParam[1]->value_int64;
param[1]->var = aParam[1]->var;
}
if (aParamCount > 2)
{ // more than 2 parameters were given, copy aParam to param
param[2]->symbol = aParam[2]->symbol;
param[2]->object = aParam[2]->object;
param[2]->var = aParam[2]->var;
// definition variable is a structure object, clone it, assign memory and init object
if (TokenToObject(*param[0]))
{
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
obj->mMemAllocated = 0;
obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64;
obj->ObjectToStruct(TokenToObject(*aParam[2]));
return obj;
}
return Struct::Create(param,3);
}
else if (TokenToObject(*param[0]))
{ // definition variable is a structure object, clone it and assign memory or init object
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
if (TokenToObject(*aParam[1]))
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
obj->ObjectToStruct(TokenToObject(*aParam[1]));
}
else
obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64;
return obj;
}
// else simply create structure from variable and given memory/initobject
return Struct::Create(param,2);
}
// Call BIF_sizeof passing offset in second parameter to align offset if necessary
// if field is a pointer we will need its size only
if (!ispointer)
{
param[1]->value_int64 = (__int64)ispointer ? 0 : offset;
param[2]->value_int64 = (__int64)&aligntotal;
BIF_sizeof(Result,ResultToken,param,ispointer ? 1 : 3);
if (ResultToken.symbol != SYM_INTEGER)
{ // could not resolve structure
obj->Release();
return NULL;
}
}
else
{
if (offset % ptrsize)
offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1);
if (ptrsize > aligntotal)
aligntotal = ptrsize;
}
// Insert new field in our structure
if (!(field = obj->Insert(keybuf, insert_pos++, ispointer, offset, arraydef, Var1.var, (int)ResultToken.value_int64,1,1,-1)))
{ // Out of memory.
obj->Release();
return NULL;
}
if (ispointer)
offset += (int)ptrsize * (arraydef ? arraydef : 1);
else
// sizeof was given an offset that it applied and aligned if necessary, so set offset = and not +=
offset = (int)ResultToken.value_int64 + (arraydef ? ((arraydef - 1) * ((int)ResultToken.value_int64 - offset)) : 0);
}
else // No variable was found and it is not default type so we can't determine size.
{
obj->Release();
return NULL;
}
}
// update union size
if (uniondepth)
{
if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth])
unionsize[uniondepth] = offset - unionoffset[uniondepth];
// reset offset if in union and union is not a structure
if (!unionisstruct[uniondepth])
offset = unionoffset[uniondepth];
}
// Move buffer pointer now
if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,"))))
buf += _tcscspn(buf,_T("}")); // keep } character to update union
else if (StrChrAny(buf, _T(";,")))
buf += _tcscspn(buf,_T(";,")) + 1;
else
{
// identify that structure object has no fields
if (!*keybuf)
obj->mTypeOnly = true;
buf += _tcslen(buf);
}
}
// align total structure if necessary
if (aligntotal && offset % aligntotal)
offset += aligntotal - (offset % aligntotal);
if (!offset) // structure could not be build
{
obj->Release();
return NULL;
}
obj->mSize = offset;
if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1]))
{ // second parameter exist and it is digit assumme this is new pointer for our structure
obj->mStructMem = (UINT_PTR *)TokenToInt64(*aParam[1]);
obj->mMemAllocated = 0;
}
else // no pointer given so allocate memory and fill memory with 0
{ // setting the memory after parsing definition saves a call to BIF_sizeof
obj->mStructMem = (UINT_PTR *)malloc(offset);
obj->mMemAllocated = offset;
memset(obj->mStructMem,NULL,offset);
}
// an object was passed to initialize fields
// enumerate trough object and assign values
if ((aParamCount > 1 && !TokenIsPureNumeric(*aParam[1])) || aParamCount > 2 )
obj->ObjectToStruct(TokenToObject(*aParam[aParamCount - 1]));
return obj;
}
//
// Struct::ObjectToStruct - Initialize structure from array, object or structure.
//
void Struct::ObjectToStruct(IObject *objfrom)
{
ExprTokenType ResultToken, this_token,enum_token,param_tokens[3];
ExprTokenType *params[] = { param_tokens, param_tokens+1, param_tokens+2 };
TCHAR defbuf[MAX_PATH],buf[MAX_PATH];
int param_count = 3;
// Set up enum_token the way Invoke expects:
enum_token.symbol = SYM_STRING;
enum_token.marker = _T("");
enum_token.mem_to_free = NULL;
enum_token.buf = defbuf;
// Prepare to call object._NewEnum():
param_tokens[0].symbol = SYM_STRING;
param_tokens[0].marker = _T("_NewEnum");
objfrom->Invoke(enum_token, ResultToken, IT_CALL, params, 1);
if (enum_token.mem_to_free)
// Invoke returned memory for us to free.
free(enum_token.mem_to_free);
// Check if object returned an enumerator, otherwise return
if (enum_token.symbol != SYM_OBJECT)
return;
// create variables to use in for loop / for enumeration
// these will be deleted afterwards
Var *var1 = (Var*)alloca(sizeof(Var));
Var *var2 = (Var*)alloca(sizeof(Var));
var1->mType = var2->mType = VAR_NORMAL;
var1->mAttrib = var2->mAttrib = 0;
var1->mByteCapacity = var2->mByteCapacity = 0;
var1->mHowAllocated = var2->mHowAllocated = ALLOC_MALLOC;
// Prepare parameters for the loop below: enum.Next(var1 [, var2])
param_tokens[0].marker = _T("Next");
param_tokens[1].symbol = SYM_VAR;
param_tokens[1].var = var1;
param_tokens[1].mem_to_free = 0;
param_tokens[2].symbol = SYM_VAR;
param_tokens[2].var = var2;
param_tokens[2].mem_to_free = 0;
ExprTokenType result_token;
IObject &enumerator = *enum_token.object; // Might perform better as a reference?
this_token.symbol = SYM_OBJECT;
this_token.object = this;
for (;;)
{
// Set up result_token the way Invoke expects; each Invoke() will change some or all of these:
result_token.symbol = SYM_STRING;
result_token.marker = _T("");
result_token.mem_to_free = NULL;
result_token.buf = buf;
// Call enumerator.Next(var1, var2)
enumerator.Invoke(result_token,enum_token,IT_CALL, params, param_count);
bool next_returned_true = TokenToBOOL(result_token, TokenIsPureNumeric(result_token));
if (!next_returned_true)
break;
this->Invoke(ResultToken,this_token,IT_SET,params+1,2);
// release object if it was assigned prevoiously when calling enum.Next
if (var1->IsObject())
var1->ReleaseObject();
if (var2->IsObject())
var2->ReleaseObject();
// Free any memory or object which may have been returned by Invoke:
if (result_token.mem_to_free)
free(result_token.mem_to_free);
if (result_token.symbol == SYM_OBJECT)
result_token.object->Release();
}
// release enumerator and free vars
enumerator.Release();
var1->Free();
var2->Free();
}
//
// Struct::Delete - Called immediately before the object is deleted.
// Returns false if object should not be deleted yet.
//
bool Struct::Delete()
{
return ObjectBase::Delete();
}
Struct::~Struct()
{
if (mMemAllocated > 0)
free(mStructMem);
if (mFields)
{
if (mFieldCount)
{
IndexType i = mFieldCount - 1;
// Free keys
for ( ; i >= 0 ; --i)
{
if (mFields[i].mMemAllocated > 0)
free(mFields[i].mStructMem);
free(mFields[i].key);
}
}
// Free fields array.
free(mFields);
}
}
//
// Struct::SetPointer - used to set pointer for a field or array item
//
UINT_PTR Struct::SetPointer(UINT_PTR aPointer,int aArrayItem)
{
if (mIsPointer)
*((UINT_PTR*)(*mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer;
else
*((UINT_PTR*)((UINT_PTR)mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer;
return aPointer;
}
//
// Struct::FieldType::Clone - used to clone a field to structure.
//
Struct *Struct::CloneField(FieldType *field,bool aIsDynamic)
// Creates an object and copies to it the fields at and after the given offset.
{
Struct *objptr = new Struct();
if (!objptr)
return objptr;
Struct &obj = *objptr;
// if field is an array, set correct size
if (obj.mArraySize = field->mArraySize)
obj.mSize = field->mSize*obj.mArraySize;
else
obj.mSize = field->mSize;
obj.mIsInteger = field->mIsInteger;
obj.mIsPointer = field->mIsPointer;
obj.mEncoding = field->mEncoding;
obj.mIsUnsigned = field->mIsUnsigned;
obj.mVarRef = field->mVarRef;
obj.mTypeOnly = 1;
obj.mMemAllocated = aIsDynamic ? -1 : 0;
return objptr;
}
//
// Struct::Clone - used for cloning structures.
//
Struct *Struct::Clone(bool aIsDynamic)
// Creates an object and copies to it the fields at and after the given offset.
{
Struct *objptr = new Struct();
if (!objptr)
return objptr;
Struct &obj = *objptr;
obj.mArraySize = mArraySize;
obj.mIsInteger = mIsInteger;
obj.mIsPointer = mIsPointer;
obj.mEncoding = mEncoding;
obj.mIsUnsigned = mIsUnsigned;
obj.mSize = mSize;
obj.mVarRef = mVarRef;
obj.mTypeOnly = mTypeOnly;
// -1 will identify a dynamic structure, no memory can be allocated to such
obj.mMemAllocated = aIsDynamic ? -1 : 0;
// Allocate space in destination object.
if (!obj.SetInternalCapacity(mFieldCount))
{
obj.Release();
return NULL;
}
FieldType *fields = obj.mFields; // Newly allocated by above.
int failure_count = 0; // See comment below.
IndexType i;
obj.mFieldCount = mFieldCount;
for (i = 0; i < mFieldCount; ++i)
{
FieldType &dst = fields[i];
FieldType &src = mFields[i];
if ( !(dst.key = _tcsdup(src.key)) )
{
// Key allocation failed.
// Rather than trying to set up the object so that what we have
// so far is valid in order to break out of the loop, continue,
// make all fields valid and then allow them to be freed.
++failure_count;
}
dst.mArraySize = src.mArraySize;
dst.mIsInteger = src.mIsInteger;
dst.mIsPointer = src.mIsPointer;
dst.mEncoding = src.mEncoding;
dst.mIsUnsigned = src.mIsUnsigned;
dst.mOffset = src.mOffset;
dst.mSize = src.mSize;
dst.mVarRef = src.mVarRef;
dst.mMemAllocated = aIsDynamic ? -1 : 0;
}
if (failure_count)
{
// One or more memory allocations failed. It seems best to return a clear failure
// indication rather than an incomplete copy. Now that the loop above has finished,
// the object's contents are at least valid and it is safe to free the object:
obj.Release();
return NULL;
}
return &obj;
}
//
// Struct::Invoke - Called by BIF_ObjInvoke when script explicitly interacts with an object.
//
ResultType STDMETHODCALLTYPE Struct::Invoke(
ExprTokenType &aResultToken,
ExprTokenType &aThisToken,
int aFlags,
ExprTokenType *aParam[],
int aParamCount
)
// L40: Revised base mechanism for flexibility and to simplify some aspects.
// obj[] -> obj.base.__Get -> obj.base[] -> obj.base.__Get etc.
{
int ptrsize = sizeof(UINT_PTR);
FieldType *field = NULL; // init to NULL to use in IS_INVOKE_CALL
ResultType Result = OK;
// Used to resolve dynamic structures
ExprTokenType Var1,Var2;
Var1.symbol = SYM_VAR;
Var2.symbol = SYM_INTEGER;
ExprTokenType *param[] = {&Var1,&Var2},ResultToken;
// used to clone a dynamic field or structure
Struct *objclone = NULL;
// used for StrGet/StrPut
LPCVOID source_string;
int source_length;
DWORD flags = WC_NO_BEST_FIT_CHARS;
int length = -1;
int char_count;
// Identify that we need to release/delete field or structure object
bool deletefield = false;
bool releaseobj = false;
int param_count_excluding_rvalue = aParamCount;
// target may be altered here to resolve dynamic structure so hold it separately
UINT_PTR *target = mStructMem;
if (IS_INVOKE_SET)
{
// Prior validation of ObjSet() param count ensures the result won't be negative:
--param_count_excluding_rvalue;
// Since defining base[key] prevents base.base.__Get and __Call from being invoked, it seems best
// to have it also block __Set. The code below is disabled to achieve this, with a slight cost to
// performance when assigning to a new key in any object which has a base object. (The cost may
// depend on how many key-value pairs each base object has.) Note that this doesn't affect meta-
// functions defined in *this* base object, since they were already invoked if present.
//if (IS_INVOKE_META)
//{
// if (param_count_excluding_rvalue == 1)
// // Prevent below from unnecessarily searching for a field, since it won't actually be assigned to.
// // Relies on mBase->Invoke recursion using aParamCount and not param_count_excluding_rvalue.
// param_count_excluding_rvalue = 0;
// //else: Allow SET to operate on a field of an object stored in the target's base.
// // For instance, x[y,z]:=w may operate on x[y][z], x.base[y][z], x[y].base[z], etc.
//}
}
|
tinku99/ahkdll
|
739e4152f161cc8bbd91d45bf8d210843adf6a34
|
Revert "Bug fix pointers in Struct "*UInt int1,int2""
|
diff --git a/source/script_struct.cpp b/source/script_struct.cpp
index d079742..6549e9b 100644
--- a/source/script_struct.cpp
+++ b/source/script_struct.cpp
@@ -1,746 +1,743 @@
#include "stdafx.h" // pre-compiled headers
#include "defines.h"
#include "application.h"
#include "globaldata.h"
#include "script.h"
#include "TextIO.h"
#include "script_object.h"
//
// Struct::Create - Called by BIF_ObjCreate to create a new object, optionally passing key/value pairs to set.
//
Struct *Struct::Create(ExprTokenType *aParam[], int aParamCount)
// This code is very similar to BIF_sizeof so should be maintained together
{
int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system
int offset = 0; // also used to calculate total size of structure
int arraydef = 0; // count arraysize to update offset
int unionoffset[100]; // backup offset before we enter union or structure
int unionsize[100]; // calculate unionsize
bool unionisstruct[100]; // updated to move offset for structure in structure
int totalunionsize = 0; // total size of all unions and structures in structure
int uniondepth = 0; // count how deep we are in union/structure
int ispointer = NULL; // identify pointer and how deep it goes
int aligntotal = 0; // pointer alignment for total structure
int thissize; // used to check if type was found in above array.
// following are used to find variable and also get size of a structure defined in variable
// this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit
ResultType Result = OK;
ExprTokenType ResultToken;
ExprTokenType Var1,Var2,Var3;
ExprTokenType *param[] = {&Var1,&Var2,&Var3};
Var1.symbol = SYM_VAR;
Var2.symbol = SYM_INTEGER;
Var3.symbol = SYM_INTEGER;
// will hold pointer to structure definition string while we parse trough it
TCHAR *buf;
size_t buf_size;
// Use enough buffer to accept any definition in a field.
TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment
// definition and field name are same max size as variables
// also add enough room to store pointers (**) and arrays [1000]
TCHAR defbuf[MAX_VAR_NAME_LENGTH*2 + 40]; // give more room to use local or static variable Function(variable)
TCHAR keybuf[MAX_VAR_NAME_LENGTH + 40];
// buffer for arraysize + 2 for bracket ] and terminating character
TCHAR intbuf[MAX_INTEGER_LENGTH + 2];
FieldType *field; // used to define a field
// Structure object is saved in fixed order
// insert_pos is simply increased each time
// for loop will enumerate items in same order as it was created
IndexType insert_pos = 0;
// the new structure object
Struct *obj = new Struct();
// Parameter passed to IsDefaultType needs to be ' Definition '
// this is because spaces are used as delimiters ( see IsDefaultType function )
// So first character will be always a space
defbuf[0] = ' ';
if (TokenToObject(*aParam[0]))
{
obj->Release();
obj = ((Struct *)TokenToObject(*aParam[0]))->Clone();
if (aParamCount > 2)
{
obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]);
obj->ObjectToStruct(TokenToObject(*aParam[2]));
}
else if (aParamCount > 1)
{
if (TokenToObject(*aParam[1]))
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,offset);
obj->ObjectToStruct(TokenToObject(*aParam[1]));
}
else
obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]);
}
else
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
}
return obj;
}
// Set initial capacity to avoid multiple expansions.
// For simplicity, failure is handled by the loop below.
obj->SetInternalCapacity(aParamCount >> 1);
// Set buf to beginning of structure definition
buf = TokenToString(*aParam[0]);
// continue as long as we did not reach end of string / structure definition
while (*buf)
{
if (!_tcsncmp(buf,_T("//"),2)) // exclude comments
{
buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf));
if (!*buf)
break; // end of definition reached
}
if (buf == StrChrAny(buf,_T("\n\r\t ")))
{ // Ignore spaces, tabs and new lines before field definition
buf++;
continue;
}
else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,"))))
{ // union or structure in structure definition
if (!uniondepth++)
totalunionsize = 0; // done here to reduce code
if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{'))
unionisstruct[uniondepth] = true; // mark that union is a structure
else
unionisstruct[uniondepth] = false;
// backup offset because we need to set it back after this union / struct was parsed
// unionsize is initialized to 0 and buffer moved to next character
unionoffset[uniondepth] = offset; // backup offset
unionsize[uniondepth] = 0;
// ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union
buf = _tcschr(buf,'{') + 1;
continue;
}
else if (*buf == '}')
{ // update union
// restore offset even if we had a structure in structure
if (unionsize[uniondepth]>totalunionsize)
totalunionsize = unionsize[uniondepth];
// last item in union or structure, update offset now if not struct, for struct offset is up to date
if (--uniondepth == 0)
{
// end of structure, align it
if (totalunionsize % aligntotal)
totalunionsize += aligntotal - (totalunionsize % aligntotal);
if (!unionisstruct[uniondepth + 1]) // because it was decreased above
offset += totalunionsize;
else if (offset % aligntotal)
offset += aligntotal - (offset % aligntotal);
}
else
offset = unionoffset[uniondepth];
buf++;
if (buf == StrChrAny(buf,_T(";,")))
buf++;
continue;
}
// set defaults
ispointer = false;
arraydef = 0;
// copy current definition field to temporary buffer
if (StrChrAny(buf, _T("};,")))
{
if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1)
{
obj->Release();
return NULL;
}
_tcsncpy(tempbuf,buf,buf_size);
tempbuf[buf_size] = '\0';
}
else if (_tcslen(buf) > LINE_SIZE - 1)
{
obj->Release();
return NULL;
}
else
_tcscpy(tempbuf,buf);
// Trim trailing spaces
rtrim(tempbuf);
+ // Pointer
+ if (_tcschr(tempbuf,'*'))
+ ispointer = StrReplace(tempbuf, _T("*"), _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
+
// Array
if (_tcschr(tempbuf,'['))
{
_tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH);
intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0';
arraydef = (int)ATOI64(intbuf + 1);
// remove array definition from temp buffer to identify key easier
StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
// Trim trailing spaces in case we had a definition like UInt [10]
rtrim(tempbuf);
}
// copy type
// if offset is 0 and there are no };, characters, it means we have a pure definition
if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset))
{
if ((buf_size = _tcscspn(tempbuf,_T("\t "))) > MAX_VAR_NAME_LENGTH*2 + 30)
{
obj->Release();
return NULL;
}
_tcsncpy(defbuf + 1,tempbuf,buf_size);
//_tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t ")),_T(" "));
defbuf[1 + buf_size] = ' ';
defbuf[2 + buf_size] = '\0';
if (StrChrAny(tempbuf, _T(" \t")))
{
if (_tcslen(StrChrAny(tempbuf, _T(" \t"))) > MAX_VAR_NAME_LENGTH + 30)
{
obj->Release();
return NULL;
}
_tcscpy(keybuf,StrChrAny(tempbuf, _T(" \t")) + 1);
ltrim(keybuf);
}
else
keybuf[0] = '\0';
}
else // Not 'TypeOnly' definition because there are more than one fields in array so use default type UInt
{
_tcscpy(defbuf,_T(" UInt "));
_tcscpy(keybuf,tempbuf);
}
-
- // Pointer
- if (_tcschr(defbuf, '*'))
- ispointer += StrReplace(defbuf, _T("*"), _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
- if (_tcschr(keybuf, '*'))
- ispointer += StrReplace(keybuf, _T("*"), _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
-
// Now find size in default types array and create new field
// If Type not found, resolve type to variable and get size of struct defined in it
if ((thissize = IsDefaultType(defbuf)))
{
if (!_tcscmp(defbuf,_T(" bool ")))
thissize = 1;
// align offset
if (ispointer)
{
if (offset % ptrsize)
offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1);
if (ptrsize > aligntotal)
aligntotal = ptrsize;
}
else
{
if (offset % thissize)
offset += thissize - (offset % thissize);
if (thissize > aligntotal)
aligntotal = thissize > ptrsize ? ptrsize : thissize;
}
if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,NULL,thissize
,ispointer ? true : !tcscasestr(_T(" FLOAT DOUBLE PFLOAT PDOUBLE "),defbuf)
,!tcscasestr(_T(" PTR SHORT INT INT64 CHAR VOID HALF_PTR BOOL INT32 LONG LONG32 LONGLONG LONG64 USN INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM __int64 "),defbuf)
,tcscasestr(_T(" TCHAR LPTSTR LPCTSTR LPWSTR LPCWSTR WCHAR "),defbuf) ? 1200 : tcscasestr(_T(" CHAR LPSTR LPCSTR LPSTR UCHAR "),defbuf) ? 0 : -1)))
{ // Out of memory.
obj->Release();
return NULL;
}
offset += (ispointer ? ptrsize : thissize) * (arraydef ? arraydef : 1);
}
else // type was not found, check for user defined type in variables
{
Var1.var = NULL; // init to not found
Func *bkpfunc = NULL;
// check if we have a local/static declaration and resolve to function
// For example Struct("*MyFunc(mystruct) mystr")
if (_tcschr(defbuf,'('))
{
bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later
g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1);
if (g->CurrentFunc) // break if not found to identify error
{
_tcscpy(tempbuf,defbuf + 1);
_tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'('));
_tcscpy(_tcschr(defbuf,')'),_T(" \0"));
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL);
g->CurrentFunc = bkpfunc;
}
else // release object and return
{
g->CurrentFunc = bkpfunc;
obj->Release();
return NULL;
}
}
else if (g->CurrentFunc) // try to find local variable first
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL);
// try to find global variable if local was not found or we are not in func
if (Var1.var == NULL)
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL);
// variable found
if (Var1.var != NULL)
{
if (!ispointer && !_tcsncmp(tempbuf,buf,_tcslen(buf)) && !*keybuf)
{ // Whole definition is not a pointer and no key was given so create Structure from variable
obj->Release();
if (aParamCount == 1)
{
if (TokenToObject(*param[0]))
{ // assume variable is a structure object
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
return obj;
}
// else create structure from string definition
return Struct::Create(param,1);
}
else if (aParamCount > 1)
{ // more than one parameter was given, copy aParam to param
param[1]->symbol = aParam[1]->symbol;
param[1]->object = aParam[1]->object;
param[1]->value_int64 = aParam[1]->value_int64;
param[1]->var = aParam[1]->var;
}
if (aParamCount > 2)
{ // more than 2 parameters were given, copy aParam to param
param[2]->symbol = aParam[2]->symbol;
param[2]->object = aParam[2]->object;
param[2]->var = aParam[2]->var;
// definition variable is a structure object, clone it, assign memory and init object
if (TokenToObject(*param[0]))
{
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
obj->mMemAllocated = 0;
obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64;
obj->ObjectToStruct(TokenToObject(*aParam[2]));
return obj;
}
return Struct::Create(param,3);
}
else if (TokenToObject(*param[0]))
{ // definition variable is a structure object, clone it and assign memory or init object
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
if (TokenToObject(*aParam[1]))
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
obj->ObjectToStruct(TokenToObject(*aParam[1]));
}
else
obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64;
return obj;
}
// else simply create structure from variable and given memory/initobject
return Struct::Create(param,2);
}
// Call BIF_sizeof passing offset in second parameter to align offset if necessary
// if field is a pointer we will need its size only
if (!ispointer)
{
param[1]->value_int64 = (__int64)ispointer ? 0 : offset;
param[2]->value_int64 = (__int64)&aligntotal;
BIF_sizeof(Result,ResultToken,param,ispointer ? 1 : 3);
if (ResultToken.symbol != SYM_INTEGER)
{ // could not resolve structure
obj->Release();
return NULL;
}
}
else
{
if (offset % ptrsize)
offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1);
if (ptrsize > aligntotal)
aligntotal = ptrsize;
}
// Insert new field in our structure
if (!(field = obj->Insert(keybuf, insert_pos++, ispointer, offset, arraydef, Var1.var, (int)ResultToken.value_int64,1,1,-1)))
{ // Out of memory.
obj->Release();
return NULL;
}
if (ispointer)
offset += (int)ptrsize * (arraydef ? arraydef : 1);
else
// sizeof was given an offset that it applied and aligned if necessary, so set offset = and not +=
offset = (int)ResultToken.value_int64 + (arraydef ? ((arraydef - 1) * ((int)ResultToken.value_int64 - offset)) : 0);
}
else // No variable was found and it is not default type so we can't determine size.
{
obj->Release();
return NULL;
}
}
// update union size
if (uniondepth)
{
if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth])
unionsize[uniondepth] = offset - unionoffset[uniondepth];
// reset offset if in union and union is not a structure
if (!unionisstruct[uniondepth])
offset = unionoffset[uniondepth];
}
// Move buffer pointer now
if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,"))))
buf += _tcscspn(buf,_T("}")); // keep } character to update union
else if (StrChrAny(buf, _T(";,")))
buf += _tcscspn(buf,_T(";,")) + 1;
else
{
// identify that structure object has no fields
if (!*keybuf)
obj->mTypeOnly = true;
buf += _tcslen(buf);
}
}
// align total structure if necessary
if (aligntotal && offset % aligntotal)
offset += aligntotal - (offset % aligntotal);
if (!offset) // structure could not be build
{
obj->Release();
return NULL;
}
obj->mSize = offset;
if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1]))
{ // second parameter exist and it is digit assumme this is new pointer for our structure
obj->mStructMem = (UINT_PTR *)TokenToInt64(*aParam[1]);
obj->mMemAllocated = 0;
}
else // no pointer given so allocate memory and fill memory with 0
{ // setting the memory after parsing definition saves a call to BIF_sizeof
obj->mStructMem = (UINT_PTR *)malloc(offset);
obj->mMemAllocated = offset;
memset(obj->mStructMem,NULL,offset);
}
// an object was passed to initialize fields
// enumerate trough object and assign values
if ((aParamCount > 1 && !TokenIsPureNumeric(*aParam[1])) || aParamCount > 2 )
obj->ObjectToStruct(TokenToObject(*aParam[aParamCount - 1]));
return obj;
}
//
// Struct::ObjectToStruct - Initialize structure from array, object or structure.
//
void Struct::ObjectToStruct(IObject *objfrom)
{
ExprTokenType ResultToken, this_token,enum_token,param_tokens[3];
ExprTokenType *params[] = { param_tokens, param_tokens+1, param_tokens+2 };
TCHAR defbuf[MAX_PATH],buf[MAX_PATH];
int param_count = 3;
// Set up enum_token the way Invoke expects:
enum_token.symbol = SYM_STRING;
enum_token.marker = _T("");
enum_token.mem_to_free = NULL;
enum_token.buf = defbuf;
// Prepare to call object._NewEnum():
param_tokens[0].symbol = SYM_STRING;
param_tokens[0].marker = _T("_NewEnum");
objfrom->Invoke(enum_token, ResultToken, IT_CALL, params, 1);
if (enum_token.mem_to_free)
// Invoke returned memory for us to free.
free(enum_token.mem_to_free);
// Check if object returned an enumerator, otherwise return
if (enum_token.symbol != SYM_OBJECT)
return;
// create variables to use in for loop / for enumeration
// these will be deleted afterwards
Var *var1 = (Var*)alloca(sizeof(Var));
Var *var2 = (Var*)alloca(sizeof(Var));
var1->mType = var2->mType = VAR_NORMAL;
var1->mAttrib = var2->mAttrib = 0;
var1->mByteCapacity = var2->mByteCapacity = 0;
var1->mHowAllocated = var2->mHowAllocated = ALLOC_MALLOC;
// Prepare parameters for the loop below: enum.Next(var1 [, var2])
param_tokens[0].marker = _T("Next");
param_tokens[1].symbol = SYM_VAR;
param_tokens[1].var = var1;
param_tokens[1].mem_to_free = 0;
param_tokens[2].symbol = SYM_VAR;
param_tokens[2].var = var2;
param_tokens[2].mem_to_free = 0;
ExprTokenType result_token;
IObject &enumerator = *enum_token.object; // Might perform better as a reference?
this_token.symbol = SYM_OBJECT;
this_token.object = this;
for (;;)
{
// Set up result_token the way Invoke expects; each Invoke() will change some or all of these:
result_token.symbol = SYM_STRING;
result_token.marker = _T("");
result_token.mem_to_free = NULL;
result_token.buf = buf;
// Call enumerator.Next(var1, var2)
enumerator.Invoke(result_token,enum_token,IT_CALL, params, param_count);
bool next_returned_true = TokenToBOOL(result_token, TokenIsPureNumeric(result_token));
if (!next_returned_true)
break;
this->Invoke(ResultToken,this_token,IT_SET,params+1,2);
// release object if it was assigned prevoiously when calling enum.Next
if (var1->IsObject())
var1->ReleaseObject();
if (var2->IsObject())
var2->ReleaseObject();
// Free any memory or object which may have been returned by Invoke:
if (result_token.mem_to_free)
free(result_token.mem_to_free);
if (result_token.symbol == SYM_OBJECT)
result_token.object->Release();
}
// release enumerator and free vars
enumerator.Release();
var1->Free();
var2->Free();
}
//
// Struct::Delete - Called immediately before the object is deleted.
// Returns false if object should not be deleted yet.
//
bool Struct::Delete()
{
return ObjectBase::Delete();
}
Struct::~Struct()
{
if (mMemAllocated > 0)
free(mStructMem);
if (mFields)
{
if (mFieldCount)
{
IndexType i = mFieldCount - 1;
// Free keys
for ( ; i >= 0 ; --i)
{
if (mFields[i].mMemAllocated > 0)
free(mFields[i].mStructMem);
free(mFields[i].key);
}
}
// Free fields array.
free(mFields);
}
}
//
// Struct::SetPointer - used to set pointer for a field or array item
//
UINT_PTR Struct::SetPointer(UINT_PTR aPointer,int aArrayItem)
{
if (mIsPointer)
*((UINT_PTR*)(*mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer;
else
*((UINT_PTR*)((UINT_PTR)mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer;
return aPointer;
}
//
// Struct::FieldType::Clone - used to clone a field to structure.
//
Struct *Struct::CloneField(FieldType *field,bool aIsDynamic)
// Creates an object and copies to it the fields at and after the given offset.
{
Struct *objptr = new Struct();
if (!objptr)
return objptr;
Struct &obj = *objptr;
// if field is an array, set correct size
if (obj.mArraySize = field->mArraySize)
obj.mSize = field->mSize*obj.mArraySize;
else
obj.mSize = field->mSize;
obj.mIsInteger = field->mIsInteger;
obj.mIsPointer = field->mIsPointer;
obj.mEncoding = field->mEncoding;
obj.mIsUnsigned = field->mIsUnsigned;
obj.mVarRef = field->mVarRef;
obj.mTypeOnly = 1;
obj.mMemAllocated = aIsDynamic ? -1 : 0;
return objptr;
}
//
// Struct::Clone - used for cloning structures.
//
Struct *Struct::Clone(bool aIsDynamic)
// Creates an object and copies to it the fields at and after the given offset.
{
Struct *objptr = new Struct();
if (!objptr)
return objptr;
Struct &obj = *objptr;
obj.mArraySize = mArraySize;
obj.mIsInteger = mIsInteger;
obj.mIsPointer = mIsPointer;
obj.mEncoding = mEncoding;
obj.mIsUnsigned = mIsUnsigned;
obj.mSize = mSize;
obj.mVarRef = mVarRef;
obj.mTypeOnly = mTypeOnly;
// -1 will identify a dynamic structure, no memory can be allocated to such
obj.mMemAllocated = aIsDynamic ? -1 : 0;
// Allocate space in destination object.
if (!obj.SetInternalCapacity(mFieldCount))
{
obj.Release();
return NULL;
}
FieldType *fields = obj.mFields; // Newly allocated by above.
int failure_count = 0; // See comment below.
IndexType i;
obj.mFieldCount = mFieldCount;
for (i = 0; i < mFieldCount; ++i)
{
FieldType &dst = fields[i];
FieldType &src = mFields[i];
if ( !(dst.key = _tcsdup(src.key)) )
{
// Key allocation failed.
// Rather than trying to set up the object so that what we have
// so far is valid in order to break out of the loop, continue,
// make all fields valid and then allow them to be freed.
++failure_count;
}
dst.mArraySize = src.mArraySize;
dst.mIsInteger = src.mIsInteger;
dst.mIsPointer = src.mIsPointer;
dst.mEncoding = src.mEncoding;
dst.mIsUnsigned = src.mIsUnsigned;
dst.mOffset = src.mOffset;
dst.mSize = src.mSize;
dst.mVarRef = src.mVarRef;
dst.mMemAllocated = aIsDynamic ? -1 : 0;
}
if (failure_count)
{
// One or more memory allocations failed. It seems best to return a clear failure
// indication rather than an incomplete copy. Now that the loop above has finished,
// the object's contents are at least valid and it is safe to free the object:
obj.Release();
return NULL;
}
return &obj;
}
//
// Struct::Invoke - Called by BIF_ObjInvoke when script explicitly interacts with an object.
//
ResultType STDMETHODCALLTYPE Struct::Invoke(
ExprTokenType &aResultToken,
ExprTokenType &aThisToken,
int aFlags,
ExprTokenType *aParam[],
int aParamCount
)
// L40: Revised base mechanism for flexibility and to simplify some aspects.
// obj[] -> obj.base.__Get -> obj.base[] -> obj.base.__Get etc.
{
int ptrsize = sizeof(UINT_PTR);
FieldType *field = NULL; // init to NULL to use in IS_INVOKE_CALL
ResultType Result = OK;
// Used to resolve dynamic structures
ExprTokenType Var1,Var2;
Var1.symbol = SYM_VAR;
Var2.symbol = SYM_INTEGER;
ExprTokenType *param[] = {&Var1,&Var2},ResultToken;
// used to clone a dynamic field or structure
Struct *objclone = NULL;
// used for StrGet/StrPut
LPCVOID source_string;
int source_length;
DWORD flags = WC_NO_BEST_FIT_CHARS;
int length = -1;
int char_count;
// Identify that we need to release/delete field or structure object
bool deletefield = false;
bool releaseobj = false;
int param_count_excluding_rvalue = aParamCount;
// target may be altered here to resolve dynamic structure so hold it separately
UINT_PTR *target = mStructMem;
if (IS_INVOKE_SET)
{
// Prior validation of ObjSet() param count ensures the result won't be negative:
--param_count_excluding_rvalue;
// Since defining base[key] prevents base.base.__Get and __Call from being invoked, it seems best
// to have it also block __Set. The code below is disabled to achieve this, with a slight cost to
// performance when assigning to a new key in any object which has a base object. (The cost may
// depend on how many key-value pairs each base object has.) Note that this doesn't affect meta-
// functions defined in *this* base object, since they were already invoked if present.
//if (IS_INVOKE_META)
//{
// if (param_count_excluding_rvalue == 1)
// // Prevent below from unnecessarily searching for a field, since it won't actually be assigned to.
// // Relies on mBase->Invoke recursion using aParamCount and not param_count_excluding_rvalue.
// param_count_excluding_rvalue = 0;
// //else: Allow SET to operate on a field of an object stored in the target's base.
// // For instance, x[y,z]:=w may operate on x[y][z], x.base[y][z], x[y].base[z], etc.
//}
}
|
tinku99/ahkdll
|
6b6e56ab7d9f86725a8721b28153c05af5639cda
|
Bug fix pointers in Struct "*UInt int1,int2"
|
diff --git a/source/script_struct.cpp b/source/script_struct.cpp
index 6549e9b..d079742 100644
--- a/source/script_struct.cpp
+++ b/source/script_struct.cpp
@@ -1,743 +1,746 @@
#include "stdafx.h" // pre-compiled headers
#include "defines.h"
#include "application.h"
#include "globaldata.h"
#include "script.h"
#include "TextIO.h"
#include "script_object.h"
//
// Struct::Create - Called by BIF_ObjCreate to create a new object, optionally passing key/value pairs to set.
//
Struct *Struct::Create(ExprTokenType *aParam[], int aParamCount)
// This code is very similar to BIF_sizeof so should be maintained together
{
int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system
int offset = 0; // also used to calculate total size of structure
int arraydef = 0; // count arraysize to update offset
int unionoffset[100]; // backup offset before we enter union or structure
int unionsize[100]; // calculate unionsize
bool unionisstruct[100]; // updated to move offset for structure in structure
int totalunionsize = 0; // total size of all unions and structures in structure
int uniondepth = 0; // count how deep we are in union/structure
int ispointer = NULL; // identify pointer and how deep it goes
int aligntotal = 0; // pointer alignment for total structure
int thissize; // used to check if type was found in above array.
// following are used to find variable and also get size of a structure defined in variable
// this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit
ResultType Result = OK;
ExprTokenType ResultToken;
ExprTokenType Var1,Var2,Var3;
ExprTokenType *param[] = {&Var1,&Var2,&Var3};
Var1.symbol = SYM_VAR;
Var2.symbol = SYM_INTEGER;
Var3.symbol = SYM_INTEGER;
// will hold pointer to structure definition string while we parse trough it
TCHAR *buf;
size_t buf_size;
// Use enough buffer to accept any definition in a field.
TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment
// definition and field name are same max size as variables
// also add enough room to store pointers (**) and arrays [1000]
TCHAR defbuf[MAX_VAR_NAME_LENGTH*2 + 40]; // give more room to use local or static variable Function(variable)
TCHAR keybuf[MAX_VAR_NAME_LENGTH + 40];
// buffer for arraysize + 2 for bracket ] and terminating character
TCHAR intbuf[MAX_INTEGER_LENGTH + 2];
FieldType *field; // used to define a field
// Structure object is saved in fixed order
// insert_pos is simply increased each time
// for loop will enumerate items in same order as it was created
IndexType insert_pos = 0;
// the new structure object
Struct *obj = new Struct();
// Parameter passed to IsDefaultType needs to be ' Definition '
// this is because spaces are used as delimiters ( see IsDefaultType function )
// So first character will be always a space
defbuf[0] = ' ';
if (TokenToObject(*aParam[0]))
{
obj->Release();
obj = ((Struct *)TokenToObject(*aParam[0]))->Clone();
if (aParamCount > 2)
{
obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]);
obj->ObjectToStruct(TokenToObject(*aParam[2]));
}
else if (aParamCount > 1)
{
if (TokenToObject(*aParam[1]))
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,offset);
obj->ObjectToStruct(TokenToObject(*aParam[1]));
}
else
obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]);
}
else
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
}
return obj;
}
// Set initial capacity to avoid multiple expansions.
// For simplicity, failure is handled by the loop below.
obj->SetInternalCapacity(aParamCount >> 1);
// Set buf to beginning of structure definition
buf = TokenToString(*aParam[0]);
// continue as long as we did not reach end of string / structure definition
while (*buf)
{
if (!_tcsncmp(buf,_T("//"),2)) // exclude comments
{
buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf));
if (!*buf)
break; // end of definition reached
}
if (buf == StrChrAny(buf,_T("\n\r\t ")))
{ // Ignore spaces, tabs and new lines before field definition
buf++;
continue;
}
else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,"))))
{ // union or structure in structure definition
if (!uniondepth++)
totalunionsize = 0; // done here to reduce code
if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{'))
unionisstruct[uniondepth] = true; // mark that union is a structure
else
unionisstruct[uniondepth] = false;
// backup offset because we need to set it back after this union / struct was parsed
// unionsize is initialized to 0 and buffer moved to next character
unionoffset[uniondepth] = offset; // backup offset
unionsize[uniondepth] = 0;
// ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union
buf = _tcschr(buf,'{') + 1;
continue;
}
else if (*buf == '}')
{ // update union
// restore offset even if we had a structure in structure
if (unionsize[uniondepth]>totalunionsize)
totalunionsize = unionsize[uniondepth];
// last item in union or structure, update offset now if not struct, for struct offset is up to date
if (--uniondepth == 0)
{
// end of structure, align it
if (totalunionsize % aligntotal)
totalunionsize += aligntotal - (totalunionsize % aligntotal);
if (!unionisstruct[uniondepth + 1]) // because it was decreased above
offset += totalunionsize;
else if (offset % aligntotal)
offset += aligntotal - (offset % aligntotal);
}
else
offset = unionoffset[uniondepth];
buf++;
if (buf == StrChrAny(buf,_T(";,")))
buf++;
continue;
}
// set defaults
ispointer = false;
arraydef = 0;
// copy current definition field to temporary buffer
if (StrChrAny(buf, _T("};,")))
{
if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1)
{
obj->Release();
return NULL;
}
_tcsncpy(tempbuf,buf,buf_size);
tempbuf[buf_size] = '\0';
}
else if (_tcslen(buf) > LINE_SIZE - 1)
{
obj->Release();
return NULL;
}
else
_tcscpy(tempbuf,buf);
// Trim trailing spaces
rtrim(tempbuf);
- // Pointer
- if (_tcschr(tempbuf,'*'))
- ispointer = StrReplace(tempbuf, _T("*"), _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
-
// Array
if (_tcschr(tempbuf,'['))
{
_tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH);
intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0';
arraydef = (int)ATOI64(intbuf + 1);
// remove array definition from temp buffer to identify key easier
StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
// Trim trailing spaces in case we had a definition like UInt [10]
rtrim(tempbuf);
}
// copy type
// if offset is 0 and there are no };, characters, it means we have a pure definition
if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset))
{
if ((buf_size = _tcscspn(tempbuf,_T("\t "))) > MAX_VAR_NAME_LENGTH*2 + 30)
{
obj->Release();
return NULL;
}
_tcsncpy(defbuf + 1,tempbuf,buf_size);
//_tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t ")),_T(" "));
defbuf[1 + buf_size] = ' ';
defbuf[2 + buf_size] = '\0';
if (StrChrAny(tempbuf, _T(" \t")))
{
if (_tcslen(StrChrAny(tempbuf, _T(" \t"))) > MAX_VAR_NAME_LENGTH + 30)
{
obj->Release();
return NULL;
}
_tcscpy(keybuf,StrChrAny(tempbuf, _T(" \t")) + 1);
ltrim(keybuf);
}
else
keybuf[0] = '\0';
}
else // Not 'TypeOnly' definition because there are more than one fields in array so use default type UInt
{
_tcscpy(defbuf,_T(" UInt "));
_tcscpy(keybuf,tempbuf);
}
+
+ // Pointer
+ if (_tcschr(defbuf, '*'))
+ ispointer += StrReplace(defbuf, _T("*"), _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
+ if (_tcschr(keybuf, '*'))
+ ispointer += StrReplace(keybuf, _T("*"), _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
+
// Now find size in default types array and create new field
// If Type not found, resolve type to variable and get size of struct defined in it
if ((thissize = IsDefaultType(defbuf)))
{
if (!_tcscmp(defbuf,_T(" bool ")))
thissize = 1;
// align offset
if (ispointer)
{
if (offset % ptrsize)
offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1);
if (ptrsize > aligntotal)
aligntotal = ptrsize;
}
else
{
if (offset % thissize)
offset += thissize - (offset % thissize);
if (thissize > aligntotal)
aligntotal = thissize > ptrsize ? ptrsize : thissize;
}
if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,NULL,thissize
,ispointer ? true : !tcscasestr(_T(" FLOAT DOUBLE PFLOAT PDOUBLE "),defbuf)
,!tcscasestr(_T(" PTR SHORT INT INT64 CHAR VOID HALF_PTR BOOL INT32 LONG LONG32 LONGLONG LONG64 USN INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM __int64 "),defbuf)
,tcscasestr(_T(" TCHAR LPTSTR LPCTSTR LPWSTR LPCWSTR WCHAR "),defbuf) ? 1200 : tcscasestr(_T(" CHAR LPSTR LPCSTR LPSTR UCHAR "),defbuf) ? 0 : -1)))
{ // Out of memory.
obj->Release();
return NULL;
}
offset += (ispointer ? ptrsize : thissize) * (arraydef ? arraydef : 1);
}
else // type was not found, check for user defined type in variables
{
Var1.var = NULL; // init to not found
Func *bkpfunc = NULL;
// check if we have a local/static declaration and resolve to function
// For example Struct("*MyFunc(mystruct) mystr")
if (_tcschr(defbuf,'('))
{
bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later
g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1);
if (g->CurrentFunc) // break if not found to identify error
{
_tcscpy(tempbuf,defbuf + 1);
_tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'('));
_tcscpy(_tcschr(defbuf,')'),_T(" \0"));
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL);
g->CurrentFunc = bkpfunc;
}
else // release object and return
{
g->CurrentFunc = bkpfunc;
obj->Release();
return NULL;
}
}
else if (g->CurrentFunc) // try to find local variable first
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL);
// try to find global variable if local was not found or we are not in func
if (Var1.var == NULL)
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL);
// variable found
if (Var1.var != NULL)
{
if (!ispointer && !_tcsncmp(tempbuf,buf,_tcslen(buf)) && !*keybuf)
{ // Whole definition is not a pointer and no key was given so create Structure from variable
obj->Release();
if (aParamCount == 1)
{
if (TokenToObject(*param[0]))
{ // assume variable is a structure object
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
return obj;
}
// else create structure from string definition
return Struct::Create(param,1);
}
else if (aParamCount > 1)
{ // more than one parameter was given, copy aParam to param
param[1]->symbol = aParam[1]->symbol;
param[1]->object = aParam[1]->object;
param[1]->value_int64 = aParam[1]->value_int64;
param[1]->var = aParam[1]->var;
}
if (aParamCount > 2)
{ // more than 2 parameters were given, copy aParam to param
param[2]->symbol = aParam[2]->symbol;
param[2]->object = aParam[2]->object;
param[2]->var = aParam[2]->var;
// definition variable is a structure object, clone it, assign memory and init object
if (TokenToObject(*param[0]))
{
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
obj->mMemAllocated = 0;
obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64;
obj->ObjectToStruct(TokenToObject(*aParam[2]));
return obj;
}
return Struct::Create(param,3);
}
else if (TokenToObject(*param[0]))
{ // definition variable is a structure object, clone it and assign memory or init object
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
if (TokenToObject(*aParam[1]))
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
obj->ObjectToStruct(TokenToObject(*aParam[1]));
}
else
obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64;
return obj;
}
// else simply create structure from variable and given memory/initobject
return Struct::Create(param,2);
}
// Call BIF_sizeof passing offset in second parameter to align offset if necessary
// if field is a pointer we will need its size only
if (!ispointer)
{
param[1]->value_int64 = (__int64)ispointer ? 0 : offset;
param[2]->value_int64 = (__int64)&aligntotal;
BIF_sizeof(Result,ResultToken,param,ispointer ? 1 : 3);
if (ResultToken.symbol != SYM_INTEGER)
{ // could not resolve structure
obj->Release();
return NULL;
}
}
else
{
if (offset % ptrsize)
offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1);
if (ptrsize > aligntotal)
aligntotal = ptrsize;
}
// Insert new field in our structure
if (!(field = obj->Insert(keybuf, insert_pos++, ispointer, offset, arraydef, Var1.var, (int)ResultToken.value_int64,1,1,-1)))
{ // Out of memory.
obj->Release();
return NULL;
}
if (ispointer)
offset += (int)ptrsize * (arraydef ? arraydef : 1);
else
// sizeof was given an offset that it applied and aligned if necessary, so set offset = and not +=
offset = (int)ResultToken.value_int64 + (arraydef ? ((arraydef - 1) * ((int)ResultToken.value_int64 - offset)) : 0);
}
else // No variable was found and it is not default type so we can't determine size.
{
obj->Release();
return NULL;
}
}
// update union size
if (uniondepth)
{
if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth])
unionsize[uniondepth] = offset - unionoffset[uniondepth];
// reset offset if in union and union is not a structure
if (!unionisstruct[uniondepth])
offset = unionoffset[uniondepth];
}
// Move buffer pointer now
if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,"))))
buf += _tcscspn(buf,_T("}")); // keep } character to update union
else if (StrChrAny(buf, _T(";,")))
buf += _tcscspn(buf,_T(";,")) + 1;
else
{
// identify that structure object has no fields
if (!*keybuf)
obj->mTypeOnly = true;
buf += _tcslen(buf);
}
}
// align total structure if necessary
if (aligntotal && offset % aligntotal)
offset += aligntotal - (offset % aligntotal);
if (!offset) // structure could not be build
{
obj->Release();
return NULL;
}
obj->mSize = offset;
if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1]))
{ // second parameter exist and it is digit assumme this is new pointer for our structure
obj->mStructMem = (UINT_PTR *)TokenToInt64(*aParam[1]);
obj->mMemAllocated = 0;
}
else // no pointer given so allocate memory and fill memory with 0
{ // setting the memory after parsing definition saves a call to BIF_sizeof
obj->mStructMem = (UINT_PTR *)malloc(offset);
obj->mMemAllocated = offset;
memset(obj->mStructMem,NULL,offset);
}
// an object was passed to initialize fields
// enumerate trough object and assign values
if ((aParamCount > 1 && !TokenIsPureNumeric(*aParam[1])) || aParamCount > 2 )
obj->ObjectToStruct(TokenToObject(*aParam[aParamCount - 1]));
return obj;
}
//
// Struct::ObjectToStruct - Initialize structure from array, object or structure.
//
void Struct::ObjectToStruct(IObject *objfrom)
{
ExprTokenType ResultToken, this_token,enum_token,param_tokens[3];
ExprTokenType *params[] = { param_tokens, param_tokens+1, param_tokens+2 };
TCHAR defbuf[MAX_PATH],buf[MAX_PATH];
int param_count = 3;
// Set up enum_token the way Invoke expects:
enum_token.symbol = SYM_STRING;
enum_token.marker = _T("");
enum_token.mem_to_free = NULL;
enum_token.buf = defbuf;
// Prepare to call object._NewEnum():
param_tokens[0].symbol = SYM_STRING;
param_tokens[0].marker = _T("_NewEnum");
objfrom->Invoke(enum_token, ResultToken, IT_CALL, params, 1);
if (enum_token.mem_to_free)
// Invoke returned memory for us to free.
free(enum_token.mem_to_free);
// Check if object returned an enumerator, otherwise return
if (enum_token.symbol != SYM_OBJECT)
return;
// create variables to use in for loop / for enumeration
// these will be deleted afterwards
Var *var1 = (Var*)alloca(sizeof(Var));
Var *var2 = (Var*)alloca(sizeof(Var));
var1->mType = var2->mType = VAR_NORMAL;
var1->mAttrib = var2->mAttrib = 0;
var1->mByteCapacity = var2->mByteCapacity = 0;
var1->mHowAllocated = var2->mHowAllocated = ALLOC_MALLOC;
// Prepare parameters for the loop below: enum.Next(var1 [, var2])
param_tokens[0].marker = _T("Next");
param_tokens[1].symbol = SYM_VAR;
param_tokens[1].var = var1;
param_tokens[1].mem_to_free = 0;
param_tokens[2].symbol = SYM_VAR;
param_tokens[2].var = var2;
param_tokens[2].mem_to_free = 0;
ExprTokenType result_token;
IObject &enumerator = *enum_token.object; // Might perform better as a reference?
this_token.symbol = SYM_OBJECT;
this_token.object = this;
for (;;)
{
// Set up result_token the way Invoke expects; each Invoke() will change some or all of these:
result_token.symbol = SYM_STRING;
result_token.marker = _T("");
result_token.mem_to_free = NULL;
result_token.buf = buf;
// Call enumerator.Next(var1, var2)
enumerator.Invoke(result_token,enum_token,IT_CALL, params, param_count);
bool next_returned_true = TokenToBOOL(result_token, TokenIsPureNumeric(result_token));
if (!next_returned_true)
break;
this->Invoke(ResultToken,this_token,IT_SET,params+1,2);
// release object if it was assigned prevoiously when calling enum.Next
if (var1->IsObject())
var1->ReleaseObject();
if (var2->IsObject())
var2->ReleaseObject();
// Free any memory or object which may have been returned by Invoke:
if (result_token.mem_to_free)
free(result_token.mem_to_free);
if (result_token.symbol == SYM_OBJECT)
result_token.object->Release();
}
// release enumerator and free vars
enumerator.Release();
var1->Free();
var2->Free();
}
//
// Struct::Delete - Called immediately before the object is deleted.
// Returns false if object should not be deleted yet.
//
bool Struct::Delete()
{
return ObjectBase::Delete();
}
Struct::~Struct()
{
if (mMemAllocated > 0)
free(mStructMem);
if (mFields)
{
if (mFieldCount)
{
IndexType i = mFieldCount - 1;
// Free keys
for ( ; i >= 0 ; --i)
{
if (mFields[i].mMemAllocated > 0)
free(mFields[i].mStructMem);
free(mFields[i].key);
}
}
// Free fields array.
free(mFields);
}
}
//
// Struct::SetPointer - used to set pointer for a field or array item
//
UINT_PTR Struct::SetPointer(UINT_PTR aPointer,int aArrayItem)
{
if (mIsPointer)
*((UINT_PTR*)(*mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer;
else
*((UINT_PTR*)((UINT_PTR)mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer;
return aPointer;
}
//
// Struct::FieldType::Clone - used to clone a field to structure.
//
Struct *Struct::CloneField(FieldType *field,bool aIsDynamic)
// Creates an object and copies to it the fields at and after the given offset.
{
Struct *objptr = new Struct();
if (!objptr)
return objptr;
Struct &obj = *objptr;
// if field is an array, set correct size
if (obj.mArraySize = field->mArraySize)
obj.mSize = field->mSize*obj.mArraySize;
else
obj.mSize = field->mSize;
obj.mIsInteger = field->mIsInteger;
obj.mIsPointer = field->mIsPointer;
obj.mEncoding = field->mEncoding;
obj.mIsUnsigned = field->mIsUnsigned;
obj.mVarRef = field->mVarRef;
obj.mTypeOnly = 1;
obj.mMemAllocated = aIsDynamic ? -1 : 0;
return objptr;
}
//
// Struct::Clone - used for cloning structures.
//
Struct *Struct::Clone(bool aIsDynamic)
// Creates an object and copies to it the fields at and after the given offset.
{
Struct *objptr = new Struct();
if (!objptr)
return objptr;
Struct &obj = *objptr;
obj.mArraySize = mArraySize;
obj.mIsInteger = mIsInteger;
obj.mIsPointer = mIsPointer;
obj.mEncoding = mEncoding;
obj.mIsUnsigned = mIsUnsigned;
obj.mSize = mSize;
obj.mVarRef = mVarRef;
obj.mTypeOnly = mTypeOnly;
// -1 will identify a dynamic structure, no memory can be allocated to such
obj.mMemAllocated = aIsDynamic ? -1 : 0;
// Allocate space in destination object.
if (!obj.SetInternalCapacity(mFieldCount))
{
obj.Release();
return NULL;
}
FieldType *fields = obj.mFields; // Newly allocated by above.
int failure_count = 0; // See comment below.
IndexType i;
obj.mFieldCount = mFieldCount;
for (i = 0; i < mFieldCount; ++i)
{
FieldType &dst = fields[i];
FieldType &src = mFields[i];
if ( !(dst.key = _tcsdup(src.key)) )
{
// Key allocation failed.
// Rather than trying to set up the object so that what we have
// so far is valid in order to break out of the loop, continue,
// make all fields valid and then allow them to be freed.
++failure_count;
}
dst.mArraySize = src.mArraySize;
dst.mIsInteger = src.mIsInteger;
dst.mIsPointer = src.mIsPointer;
dst.mEncoding = src.mEncoding;
dst.mIsUnsigned = src.mIsUnsigned;
dst.mOffset = src.mOffset;
dst.mSize = src.mSize;
dst.mVarRef = src.mVarRef;
dst.mMemAllocated = aIsDynamic ? -1 : 0;
}
if (failure_count)
{
// One or more memory allocations failed. It seems best to return a clear failure
// indication rather than an incomplete copy. Now that the loop above has finished,
// the object's contents are at least valid and it is safe to free the object:
obj.Release();
return NULL;
}
return &obj;
}
//
// Struct::Invoke - Called by BIF_ObjInvoke when script explicitly interacts with an object.
//
ResultType STDMETHODCALLTYPE Struct::Invoke(
ExprTokenType &aResultToken,
ExprTokenType &aThisToken,
int aFlags,
ExprTokenType *aParam[],
int aParamCount
)
// L40: Revised base mechanism for flexibility and to simplify some aspects.
// obj[] -> obj.base.__Get -> obj.base[] -> obj.base.__Get etc.
{
int ptrsize = sizeof(UINT_PTR);
FieldType *field = NULL; // init to NULL to use in IS_INVOKE_CALL
ResultType Result = OK;
// Used to resolve dynamic structures
ExprTokenType Var1,Var2;
Var1.symbol = SYM_VAR;
Var2.symbol = SYM_INTEGER;
ExprTokenType *param[] = {&Var1,&Var2},ResultToken;
// used to clone a dynamic field or structure
Struct *objclone = NULL;
// used for StrGet/StrPut
LPCVOID source_string;
int source_length;
DWORD flags = WC_NO_BEST_FIT_CHARS;
int length = -1;
int char_count;
// Identify that we need to release/delete field or structure object
bool deletefield = false;
bool releaseobj = false;
int param_count_excluding_rvalue = aParamCount;
// target may be altered here to resolve dynamic structure so hold it separately
UINT_PTR *target = mStructMem;
if (IS_INVOKE_SET)
{
// Prior validation of ObjSet() param count ensures the result won't be negative:
--param_count_excluding_rvalue;
// Since defining base[key] prevents base.base.__Get and __Call from being invoked, it seems best
// to have it also block __Set. The code below is disabled to achieve this, with a slight cost to
// performance when assigning to a new key in any object which has a base object. (The cost may
// depend on how many key-value pairs each base object has.) Note that this doesn't affect meta-
// functions defined in *this* base object, since they were already invoked if present.
//if (IS_INVOKE_META)
//{
// if (param_count_excluding_rvalue == 1)
// // Prevent below from unnecessarily searching for a field, since it won't actually be assigned to.
// // Relies on mBase->Invoke recursion using aParamCount and not param_count_excluding_rvalue.
// param_count_excluding_rvalue = 0;
// //else: Allow SET to operate on a field of an object stored in the target's base.
// // For instance, x[y,z]:=w may operate on x[y][z], x.base[y][z], x[y].base[z], etc.
//}
}
|
tinku99/ahkdll
|
d3b619be37ecd1105d30a541eec17a5ffea83167
|
Fixed using pointers in Struct and small Fix for Sort
|
diff --git a/source/script2.cpp b/source/script2.cpp
index 98a9904..6d7bd01 100644
--- a/source/script2.cpp
+++ b/source/script2.cpp
@@ -7496,1026 +7496,1034 @@ ResultType Line::SplitPath(LPTSTR aFileSpec)
if (!ext_dot)
output_var_ext->Assign();
else
if (!output_var_ext->Assign(ext_dot + 1)) // Can be empty string if filename ends in just a dot.
return FAIL;
}
if (output_var_name_no_ext && !output_var_name_no_ext->Assign(name, (VarSizeType)(ext_dot ? ext_dot - name : _tcslen(name))))
return FAIL;
if (output_var_drive && !output_var_drive->Assign(drive, (VarSizeType)(drive_end - drive)))
return FAIL;
return OK;
}
int SortWithOptions(const void *a1, const void *a2)
// Decided to just have one sort function since there are so many permutations. The performance
// will be a little bit worse, but it seems simpler to implement and maintain.
// This function's input parameters are pointers to the elements of the array. Since those elements
// are themselves pointers, the input parameters are therefore pointers to pointers (handles).
{
LPTSTR sort_item1 = *(LPTSTR *)a1;
LPTSTR sort_item2 = *(LPTSTR *)a2;
if (g_SortColumnOffset > 0)
{
// Adjust each string (even for numerical sort) to be the right column position,
// or the position of its zero terminator if the column offset goes beyond its length:
size_t length = _tcslen(sort_item1);
sort_item1 += (size_t)g_SortColumnOffset > length ? length : g_SortColumnOffset;
length = _tcslen(sort_item2);
sort_item2 += (size_t)g_SortColumnOffset > length ? length : g_SortColumnOffset;
}
if (g_SortNumeric) // Takes precedence over g_SortCaseSensitive
{
// For now, assume both are numbers. If one of them isn't, it will be sorted as a zero.
// Thus, all non-numeric items should wind up in a sequential, unsorted group.
// Resolve only once since parts of the ATOF() macro are inline:
double item1_minus_2 = ATOF(sort_item1) - ATOF(sort_item2);
if (!item1_minus_2) // Exactly equal.
return 0;
// Otherwise, it's either greater or less than zero:
int result = (item1_minus_2 > 0.0) ? 1 : -1;
return g_SortReverse ? -result : result;
}
// Otherwise, it's a non-numeric sort.
// v1.0.43.03: Added support the new locale-insensitive mode.
int result = tcscmp2(sort_item1, sort_item2, g_SortCaseSensitive); // Resolve large macro only once for code size reduction.
return g_SortReverse ? -result : result;
}
int SortByNakedFilename(const void *a1, const void *a2)
// See comments in prior function for details.
{
LPTSTR sort_item1 = *(LPTSTR *)a1;
LPTSTR sort_item2 = *(LPTSTR *)a2;
LPTSTR cp;
if (cp = _tcsrchr(sort_item1, '\\')) // Assign
sort_item1 = cp + 1;
if (cp = _tcsrchr(sort_item2, '\\')) // Assign
sort_item2 = cp + 1;
// v1.0.43.03: Added support the new locale-insensitive mode.
int result = tcscmp2(sort_item1, sort_item2, g_SortCaseSensitive); // Resolve large macro only once for code size reduction.
return g_SortReverse ? -result : result;
}
struct sort_rand_type
{
LPTSTR cp; // This must be the first member of the struct, otherwise the array trickery in PerformSort will fail.
union
{
// This must be the same size in bytes as the above, which is why it's maintained as a union with
// a char* rather than a plain int.
LPTSTR unused;
int rand;
};
};
int SortRandom(const void *a1, const void *a2)
// See comments in prior functions for details.
{
return ((sort_rand_type *)a1)->rand - ((sort_rand_type *)a2)->rand;
}
int SortUDF(const void *a1, const void *a2)
// See comments in prior function for details.
{
// Need to check if backup of function's variables is needed in case:
// 1) The UDF is assigned to more than one callback, in which case the UDF could be running more than one
// simultaneously.
// 2) The callback is intended to be reentrant (e.g. a subclass/WindowProc that doesn't Critical).
// 3) Script explicitly calls the UDF in addition to using it as a callback.
//
// See ExpandExpression() for detailed comments about the following section.
VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects.
int var_backup_count; // The number of items in the above array.
if (g_SortFunc->mInstances > 0) // Backup is needed.
if (!Var::BackupFunctionVars(*g_SortFunc, var_backup, var_backup_count)) // Out of memory.
return 0; // Since out-of-memory is so rare, it seems justifiable not to have any error reporting and instead just say "these items are equal".
// The following isn't necessary because by definition, the current thread isn't paused because it's the
// thing that called the sort in the first place.
//g_script.UpdateTrayIcon();
ExprTokenType result_token; // L31
g_SortFunc->mParam[0].var->Assign(*(LPTSTR *)a1); // For simplicity and due to extreme rarity, parameters beyond
g_SortFunc->mParam[1].var->Assign(*(LPTSTR *)a2); // the first 2 aren't populated even if they have default values.
if (g_SortFunc->mParamCount > 2)
g_SortFunc->mParam[2].var->Assign((__int64)(*(LPTSTR *)a2 - *(LPTSTR *)a1)); // __int64 to allow for a list greater than 2 GB, though that is currently impossible.
g_SortFunc->Call(&result_token); // Call the UDF.
// MUST handle return_value BEFORE calling FreeAndRestoreFunctionVars() because return_value might be
// the contents of one of the function's local variables (which are about to be free'd).
int returned_int;
if (!TokenIsEmptyString(result_token)) // No need to check the following because they're implied for *return_value!=0: result != EARLY_EXIT && result != FAIL;
{
// Using float vs. int makes sort up to 46% slower, so decided to use int. Must use ATOI64 vs. ATOI
// because otherwise a negative might overflow/wrap into a positive (at least with the MSVC++
// implementation of ATOI).
// ATOI64()'s implementation (and probably any/all others?) truncates any decimal portion;
// e.g. 0.8 and 0.3 both yield 0.
__int64 i64 = TokenToInt64(result_token);
if (i64 > 0) // Maybe there's a faster/better way to do these checks. Can't simply typecast to an int because some large positives wrap into negative, maybe vice versa.
returned_int = 1;
else if (i64 < 0)
returned_int = -1;
else
returned_int = 0;
if (result_token.symbol == SYM_OBJECT) // L31
result_token.object->Release();
}
else
returned_int = 0;
Var::FreeAndRestoreFunctionVars(*g_SortFunc, var_backup, var_backup_count);
return returned_int;
}
ResultType Line::PerformSort(LPTSTR aContents, LPTSTR aOptions)
// Caller must ensure that aContents is modifiable (ArgMustBeDereferenced() currently ensures this) because
// not only does this function modify it, it also needs to store its result back into output_var in a way
// that requires that output_var not be at the same address as the contents that were sorted.
// It seems best to treat ACT_SORT's var to be an input vs. output var because if
// it's an environment variable or the clipboard, the input variable handler will
// automatically resolve it to be ARG1 (i.e. put its contents into the deref buf).
// This is especially necessary if the clipboard contains files, in which case
// output_var->Get(), not Contents(), must be used to resolve the filenames into text.
// And on average, using the deref buffer for this operation will not be wasteful in
// terms of expanding it unnecessarily, because usually the contents will have been
// already (or will soon be) in the deref buffer as a result of commands before
// or after the Sort command in the script.
{
// Set defaults in case of early goto:
LPTSTR mem_to_free = NULL;
Func *sort_func_orig = g_SortFunc; // Because UDFs can be interrupted by other threads -- and because UDFs can themselves call Sort with some other UDF (unlikely to be sure) -- backup & restore original g_SortFunc so that the "collapsing in reverse order" behavior will automatically ensure proper operation.
g_SortFunc = NULL; // Now that original has been saved above, reset to detect whether THIS sort uses a UDF.
ResultType result_to_return = OK;
DWORD ErrorLevel = -1; // Use -1 to mean "don't change/set ErrorLevel".
// Resolve options. First set defaults for options:
TCHAR delimiter = '\n';
g_SortCaseSensitive = SCS_INSENSITIVE;
g_SortNumeric = false;
g_SortReverse = false;
g_SortColumnOffset = 0;
bool trailing_delimiter_indicates_trailing_blank_item = false, terminate_last_item_with_delimiter = false
, trailing_crlf_added_temporarily = false, sort_by_naked_filename = false, sort_random = false
, omit_dupes = false;
LPTSTR cp, cp_end;
for (cp = aOptions; *cp; ++cp)
{
switch(_totupper(*cp))
{
case 'C':
if (ctoupper(cp[1]) == 'L') // v1.0.43.03: Locale-insensitive mode, which probably performs considerably worse.
{
++cp;
g_SortCaseSensitive = SCS_INSENSITIVE_LOCALE;
}
else
g_SortCaseSensitive = SCS_SENSITIVE;
break;
case 'D':
if (!cp[1]) // Avoids out-of-bounds when the loop's own ++cp is done.
break;
++cp;
if (*cp)
delimiter = *cp;
break;
case 'F': // v1.0.47: Support a callback function to extend flexibility.
// Decided not to set ErrorLevel here because omit-dupes already uses it, and the code/docs
// complexity of having one take precedence over the other didn't seem worth it given rarity
// of errors and rarity of UDF use.
cp = omit_leading_whitespace(cp + 1); // Point it to the function's name.
if ( !(cp_end = StrChrAny(cp, _T(" \t"))) ) // Find space or tab, if any.
cp_end = cp + _tcslen(cp); // Point it to the terminator instead.
if ( !(g_SortFunc = g_script.FindFunc(cp, cp_end - cp)) )
goto end; // For simplicity, just abort the sort.
// To improve callback performance, ensure there are no ByRef parameters (for simplicity:
// not even ones that have default values) among the first two parameters. This avoids the
// need to ensure formal parameters are non-aliases each time the callback is called.
if (g_SortFunc->mIsBuiltIn || g_SortFunc->mParamCount < 2 // This validation is relied upon at a later stage.
|| g_SortFunc->mParamCount > 3 // Reserve 4-or-more parameters for possible future use (to avoid breaking existing scripts if such features are ever added).
|| g_SortFunc->mParam[0].is_byref || g_SortFunc->mParam[1].is_byref) // Relies on short-circuit boolean order.
goto end; // For simplicity, just abort the sort.
// Otherwise, the function meets the minimum constraints (though for simplicity, optional parameters
// (default values), if any, aren't populated).
// Fix for v1.0.47.05: The following line now subtracts 1 in case *cp_end=='\0'; otherwise the
// loop's ++cp would go beyond the terminator when there are no more options.
cp = cp_end - 1; // In the next iteration (which also does a ++cp), resume looking for options after the function's name.
break;
case 'N':
g_SortNumeric = true;
break;
case 'P':
// Use atoi() vs. ATOI() to avoid interpreting something like 0x01C as hex
// when in fact the C was meant to be an option letter:
g_SortColumnOffset = _ttoi(cp + 1);
if (g_SortColumnOffset < 1)
g_SortColumnOffset = 1;
--g_SortColumnOffset; // Convert to zero-based.
break;
case 'R':
if (!_tcsnicmp(cp, _T("Random"), 6))
{
sort_random = true;
cp += 5; // Point it to the last char so that the loop's ++cp will point to the character after it.
}
else
g_SortReverse = true;
break;
case 'U': // Unique.
omit_dupes = true;
ErrorLevel = 0; // Set default dupe-count to 0 in case of early return.
break;
case 'Z':
// By setting this to true, the final item in the list, if it ends in a delimiter,
// is considered to be followed by a blank item:
trailing_delimiter_indicates_trailing_blank_item = true;
break;
case '\\':
sort_by_naked_filename = true;
}
}
// Check for early return only after parsing options in case an option that sets ErrorLevel is present:
if (!*aContents) // Variable is empty, nothing to sort.
goto end;
Var &output_var = *OUTPUT_VAR; // The input var (ARG1) is also the output var in this case.
// Do nothing for reserved variables, since most of them are read-only and besides, none
// of them (realistically) should ever need sorting:
if (VAR_IS_READONLY(output_var)) // output_var can be a reserved variable because it's not marked as an output-var by ArgIsVar() [since it has a dual purpose as an input-var].
goto end;
// size_t helps performance and should be plenty of capacity for many years of advancement.
// In addition, things like realloc() can't accept anything larger than size_t anyway,
// so there's no point making this 64-bit until size_t itself becomes 64-bit (it already is on some compilers?).
size_t item_count;
// Explicitly calculate the length in case it's the clipboard or an environment var.
// (in which case Length() does not contain the current length). While calculating
// the length, also check how many delimiters are present:
for (item_count = 1, cp = aContents; *cp; ++cp) // Start at 1 since item_count is delimiter_count+1
if (*cp == delimiter)
++item_count;
size_t aContents_length = cp - aContents;
// If the last character in the unsorted list is a delimiter then technically the final item
// in the list is a blank item. However, if the options specify not to allow that, don't count that
// blank item as an actual item (i.e. omit it from the list):
if (!trailing_delimiter_indicates_trailing_blank_item && cp > aContents && cp[-1] == delimiter)
{
terminate_last_item_with_delimiter = true; // Have a later stage add the delimiter to the end of the sorted list so that the length and format of the sorted list is the same as the unsorted list.
--item_count; // Indicate that the blank item at the end of the list isn't being counted as an item.
}
else // The final character isn't a delimiter or it is but there's a blank item to its right. Either way, the following is necessary (verified correct).
{
if (delimiter == '\n')
{
LPTSTR first_delimiter = _tcschr(aContents, delimiter);
if (first_delimiter && first_delimiter > aContents && first_delimiter[-1] == '\r')
{
// v1.0.47.05:
// Here the delimiter is effectively CRLF vs. LF. Therefore, signal a later section to append
// an extra CRLF to simplify the code and fix bugs that existed prior to v1.0.47.05.
// One such bug is that sorting "x`r`nx" in unique mode would previously produce two
// x's rather than one because the first x is seen to have a `r to its right but the
// second lacks it (due to the CRLF delimiter being simulated via LF-only).
//
// OLD/OBSOLETE comment from a section that was removed because it's now handled by this section:
// Check if special handling is needed due to the following situation:
// Delimiter is LF but the contents are lines delimited by CRLF, not just LF
// and the original/unsorted list's last item was not terminated by an
// "allowed delimiter". The symptoms of this are that after the sort, the
// last item will end in \r when it should end in no delimiter at all.
// This happens pretty often, such as when the clipboard contains files.
// In the future, an option letter can be added to turn off this workaround,
// but it seems unlikely that anyone would ever want to.
trailing_crlf_added_temporarily = true;
terminate_last_item_with_delimiter = true; // This is done to "fool" later sections into thinking the list ends in a CRLF that doesn't have a blank item to the right, which in turn simplifies the logic and/or makes it more understandable.
}
}
}
if (item_count == 1) // 1 item is already sorted, and no dupes are possible.
{
// Put the exact contents back into the output_var, which is necessary in case
// the variable was an environment variable or the clipboard-containing-files,
// since in those cases we want the behavior to be consistent regardless of
// whether there's only 1 item or more than one:
// Clipboard-contains-files: The single file should be translated into its
// text equivalent. Var was an environment variable: the corresponding script
// variable should be assigned the contents, so it will basically "take over"
// for the environment variable.
result_to_return = output_var.Assign(aContents, (VarSizeType)aContents_length);
goto end;
}
// v1.0.47.05: It simplifies the code a lot to allocate and/or improves understandability to allocate
// memory for trailing_crlf_added_temporarily even though technically it's done only to make room to
// append the extra CRLF at the end.
if (g_SortFunc || trailing_crlf_added_temporarily) // Do this here rather than earlier with the options parsing in case the function-option is present twice (unlikely, but it would be a memory leak due to strdup below). Doing it here also avoids allocating if it isn't necessary.
{
// When g_SortFunc!=NULL, the copy of the string is needed because an earlier stage has ensured that
// aContents is in the deref buffer, but that deref buffer is about to be overwritten by the
// execution of the script's UDF body.
if ( !(mem_to_free = tmalloc(aContents_length + 3)) ) // +1 for terminator and +2 in case of trailing_crlf_added_temporarily.
{
result_to_return = LineError(ERR_OUTOFMEM); // Short msg. since so rare.
goto end;
}
tmemcpy(mem_to_free, aContents, aContents_length + 1); // memcpy() usually benches a little faster than _tcscpy().
aContents = mem_to_free;
if (trailing_crlf_added_temporarily)
{
// Must be added early so that the next stage will terminate at the \n, leaving the \r as
// the ending character in this item.
_tcscpy(aContents + aContents_length, _T("\r\n"));
aContents_length += 2;
}
}
// Create the array of pointers that points into aContents to each delimited item.
// Use item_count + 1 to allow space for the last (blank) item in case
// trailing_delimiter_indicates_trailing_blank_item is false:
int unit_size = sort_random ? 2 : 1;
size_t item_size = unit_size * sizeof(LPTSTR);
LPTSTR *item = (LPTSTR *)malloc((item_count + 1) * item_size);
if (!item)
{
result_to_return = LineError(ERR_OUTOFMEM); // Short msg. since so rare.
goto end;
}
// If sort_random is in effect, the above has created an array twice the normal size.
// This allows the random numbers to be interleaved inside the array as though it
// were an array consisting of sort_rand_type (which it actually is when viewed that way).
// Because of this, the array should be accessed through pointer addition rather than
// indexing via [].
// Scan aContents and do the following:
// 1) Replace each delimiter with a terminator so that the individual items can be seen
// as real strings by the SortWithOptions() and when copying the sorted results back
// into output_vav. It is safe to change aContents in this way because
// ArgMustBeDereferenced() has ensured that those contents are in the deref buffer.
// 2) Store a marker/pointer to each item (string) in aContents so that we know where
// each item begins for sorting and recopying purposes.
LPTSTR *item_curr = item; // i.e. Don't use [] indexing for the reason in the paragraph previous to above.
for (item_count = 0, cp = *item_curr = aContents; *cp; ++cp)
{
if (*cp == delimiter) // Each delimiter char becomes the terminator of the previous key phrase.
{
*cp = '\0'; // Terminate the item that appears before this delimiter.
++item_count;
if (sort_random)
*(item_curr + 1) = (LPTSTR)(size_t)genrand_int31(); // i.e. the randoms are in the odd fields, the pointers in the even.
// For the above:
// I don't know the exact reasons, but using genrand_int31() is much more random than
// using genrand_int32() in this case. Perhaps it is some kind of statistical/cyclical
// anomaly in the random number generator. Or perhaps it's something to do with integer
// underflow/overflow in SortRandom(). In any case, the problem can be proven via the
// following script, which shows a sharply non-random distribution when genrand_int32()
// is used:
//count = 0
//Loop 10000
//{
// var = 1`n2`n3`n4`n5`n
// Sort, Var, Random
// StringLeft, Var1, Var, 1
// if Var1 = 5 ; Change this value to 1 to see the opposite problem.
// count += 1
//}
//Msgbox %count%
//
// I e-mailed the author about this sometime around/prior to 12/1/04 but never got a response.
item_curr += unit_size; // i.e. Don't use [] indexing for the reason described above.
*item_curr = cp + 1; // Make a pointer to the next item's place in aContents.
}
}
// The above reset the count to 0 and recounted it. So now re-add the last item to the count unless it was
// disqualified earlier. Verified correct:
if (!terminate_last_item_with_delimiter) // i.e. either trailing_delimiter_indicates_trailing_blank_item==true OR the final character isn't a delimiter. Either way the final item needs to be added.
{
++item_count;
if (sort_random) // Provide a random number for the last item.
*(item_curr + 1) = (LPTSTR)(size_t)genrand_int31(); // i.e. the randoms are in the odd fields, the pointers in the even.
}
else // Since the final item is not included in the count, point item_curr to the one before the last, for use below.
item_curr -= unit_size;
// Now aContents has been divided up based on delimiter. Sort the array of pointers
// so that they indicate the correct ordering to copy aContents into output_var:
if (g_SortFunc) // Takes precedence other sorting methods.
qsort((void *)item, item_count, item_size, SortUDF);
else if (sort_random) // Takes precedence over all remaining options.
qsort((void *)item, item_count, item_size, SortRandom);
else
qsort((void *)item, item_count, item_size, sort_by_naked_filename ? SortByNakedFilename : SortWithOptions);
// Copy the sorted pointers back into output_var, which might not already be sized correctly
// if it's the clipboard or it was an environment variable when it came in as the input.
// If output_var is the clipboard, this call will set up the clipboard for writing:
if (output_var.AssignString(NULL, aContents_length) != OK) // Might fail due to clipboard problem.
{
result_to_return = FAIL;
goto end;
}
// Set default in case original last item is still the last item, or if last item was omitted due to being a dupe:
size_t i, item_count_minus_1 = item_count - 1;
DWORD omit_dupe_count = 0;
bool keep_this_item;
LPTSTR source, dest;
LPTSTR item_prev = NULL;
// Copy the sorted result back into output_var. Do all except the last item, since the last
// item gets special treatment depending on the options that were specified. The call to
// output_var->Contents() below should never fail due to the above having prepped it:
item_curr = item; // i.e. Don't use [] indexing for the reason described higher above (same applies to item += unit_size below).
for (dest = output_var.Contents(), i = 0; i < item_count; ++i, item_curr += unit_size)
{
keep_this_item = true; // Set default.
if (omit_dupes && item_prev)
{
// Update to the comment below: Exact dupes will still be removed when sort_by_naked_filename
// or g_SortColumnOffset is in effect because duplicate lines would still be adjacent to
// each other even in these modes. There doesn't appear to be any exceptions, even if
// some items in the list are sorted as blanks due to being shorter than the specified
// g_SortColumnOffset.
// As documented, special dupe-checking modes are not offered when sort_by_naked_filename
// is in effect, or g_SortColumnOffset is greater than 1. That's because the need for such
// a thing seems too rare (and the result too strange) to justify the extra code size.
// However, adjacent dupes are still removed when any of the above modes are in effect,
// or when the "random" mode is in effect. This might have some usefulness; for example,
// if a list of songs is sorted in random order, but it contains "favorite" songs listed twice,
// the dupe-removal feature would remove duplicate songs if they happen to be sorted
// to lie adjacent to each other, which would be useful to prevent the same song from
// playing twice in a row.
if (g_SortNumeric && !g_SortColumnOffset)
// if g_SortColumnOffset is zero, fall back to the normal dupe checking in case its
// ever useful to anyone. This is done because numbers in an offset column are not supported
// since the extra code size doensn't seem justified given the rarity of the need.
keep_this_item = (ATOF(*item_curr) != ATOF(item_prev)); // ATOF() ignores any trailing \r in CRLF mode, so no extra logic is needed for that.
else
keep_this_item = tcscmp2(*item_curr, item_prev, g_SortCaseSensitive); // v1.0.43.03: Added support for locale-insensitive mode.
// Permutations of sorting case sensitive vs. eliminating duplicates based on case sensitivity:
// 1) Sort is not case sens, but dupes are: Won't work because sort didn't necessarily put
// same-case dupes adjacent to each other.
// 2) Converse: probably not reliable because there could be unrelated items in between
// two strings that are duplicates but weren't sorted adjacently due to their case.
// 3) Both are case sensitive: seems okay
// 4) Both are not case sensitive: seems okay
//
// In light of the above, using the g_SortCaseSensitive flag to control the behavior of
// both sorting and dupe-removal seems best.
}
if (keep_this_item)
{
for (source = *item_curr; *source;)
*dest++ = *source++;
// If we're at the last item and the original list's last item had a terminating delimiter
// and the specified options said to treat it not as a delimiter but as a final char of sorts,
// include it after the item that is now last so that the overall layout is the same:
if (i < item_count_minus_1 || terminate_last_item_with_delimiter)
*dest++ = delimiter; // Put each item's delimiter back in so that format is the same as the original.
item_prev = *item_curr; // Since the item just processed above isn't a dupe, save this item to compare against the next item.
}
else // This item is a duplicate of the previous item.
{
++omit_dupe_count; // But don't change the value of item_prev.
// v1.0.47.05: The following section fixes the fact that the "unique" option would sometimes leave
// a trailing delimiter at the end of the sorted list. For example, sorting "x|x" in unique mode
// would formerly produce "x|":
if (i == item_count_minus_1 && !terminate_last_item_with_delimiter) // This is the last item and its being omitted, so remove the previous item's trailing delimiter (unless a trailing delimiter is mandatory).
--dest; // Remove the previous item's trailing delimiter there's nothing for it to delimit due to omission of this duplicate.
}
} // for()
free(item); // Free the index/pointer list used for the sort.
// Terminate the variable's contents.
if (trailing_crlf_added_temporarily) // Remove the CRLF only after its presence was used above to simplify the code by reducing the number of types/cases.
{
- dest[-2] = '\0';
- output_var.ByteLength() -= 2 * sizeof(TCHAR);
+ if (dest[-2] == '\r') // ends with CRLF
+ {
+ dest[-2] = '\0';
+ output_var.ByteLength() -= 2 * sizeof(TCHAR);
+ }
+ else // ens with LF
+ {
+ dest[-1] = '\0';
+ output_var.ByteLength() -= sizeof(TCHAR);
+ }
}
else
*dest = '\0';
if (omit_dupes)
{
if (omit_dupe_count) // Update the length to actual whenever at least one dupe was omitted.
{
output_var.SetCharLength((VarSizeType)_tcslen(output_var.Contents()));
ErrorLevel = omit_dupe_count; // Override the 0 set earlier.
}
}
//else it is not necessary to set output_var.Length() here because its length hasn't changed
// since it was originally set by the above call "output_var.AssignString(NULL..."
result_to_return = output_var.Close(); // Must be called after Assign(NULL, ...) or when Contents() has been altered because it updates the variable's attributes and properly handles VAR_CLIPBOARD.
end:
if (ErrorLevel != -1) // A change to ErrorLevel is desired. Compare directly to -1 due to unsigned.
g_ErrorLevel->Assign(ErrorLevel); // ErrorLevel is set only when dupe-mode is in effect.
if (mem_to_free)
free(mem_to_free);
g_SortFunc = sort_func_orig;
return result_to_return;
}
ResultType Line::GetKeyJoyState(LPTSTR aKeyName, LPTSTR aOption)
// Keep this in sync with FUNC_GETKEYSTATE.
{
Var &output_var = *OUTPUT_VAR;
JoyControls joy;
int joystick_id;
vk_type vk = TextToVK(aKeyName);
if (!vk)
{
if ( !(joy = (JoyControls)ConvertJoy(aKeyName, &joystick_id)) )
return output_var.Assign(_T(""));
// Since the above didn't return, joy contains a valid joystick button/control ID.
// Caller needs a token with a buffer of at least this size:
TCHAR buf[MAX_NUMBER_SIZE];
ExprTokenType token;
token.symbol = SYM_STRING; // These must be set as defaults for ScriptGetJoyState().
token.marker = buf; //
ScriptGetJoyState(joy, joystick_id, token, false);
// Above: ScriptGetJoyState() returns FAIL and sets output_var to be blank if the result is
// indeterminate or there was a problem reading the joystick. But we don't want such a failure
// to be considered a "critical failure" that will exit the current quasi-thread, so its result
// is discarded.
return output_var.Assign(token); // Write the result based on whether the token is a string or number.
}
// Otherwise: There is a virtual key (not a joystick control).
KeyStateTypes key_state_type;
switch (ctoupper(*aOption))
{
case 'T': key_state_type = KEYSTATE_TOGGLE; break; // Whether a toggleable key such as CapsLock is currently turned on.
case 'P': key_state_type = KEYSTATE_PHYSICAL; break; // Physical state of key.
default: key_state_type = KEYSTATE_LOGICAL;
}
return output_var.Assign(ScriptGetKeyState(vk, key_state_type) ? _T("D") : _T("U"));
}
ResultType Line::DriveSpace(LPTSTR aPath, bool aGetFreeSpace)
// Because of NTFS's ability to mount volumes into a directory, a path might not necessarily
// have the same amount of free space as its root drive. However, I'm not sure if this
// method here actually takes that into account.
{
OUTPUT_VAR->Assign(); // Init to empty string regardless of whether we succeed here.
if (!aPath || !*aPath) goto error; // Below relies on this check.
TCHAR buf[MAX_PATH + 1]; // +1 to allow appending of backslash.
tcslcpy(buf, aPath, _countof(buf));
size_t length = _tcslen(buf);
if (buf[length - 1] != '\\') // Trailing backslash is present, which some of the API calls below don't like.
{
if (length + 1 >= _countof(buf)) // No room to fix it.
goto error;
buf[length++] = '\\';
buf[length] = '\0';
}
SetErrorMode(SEM_FAILCRITICALERRORS); // If target drive is a floppy, this avoids a dialog prompting to insert a disk.
// The program won't launch at all on Win95a (original Win95) unless the function address is resolved
// at runtime:
typedef BOOL (WINAPI *GetDiskFreeSpaceExType)(LPCTSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
static GetDiskFreeSpaceExType MyGetDiskFreeSpaceEx =
(GetDiskFreeSpaceExType)GetProcAddress(GetModuleHandle(_T("kernel32")), "GetDiskFreeSpaceEx" WINAPI_SUFFIX);
// MSDN: "The GetDiskFreeSpaceEx function returns correct values for all volumes, including those
// that are greater than 2 gigabytes."
__int64 free_space;
if (MyGetDiskFreeSpaceEx) // Function is available (unpatched Win95 and WinNT might not have it).
{
ULARGE_INTEGER total, free, used;
if (!MyGetDiskFreeSpaceEx(buf, &free, &total, &used))
goto error;
// Casting this way allows sizes of up to 2,097,152 gigabytes:
free_space = (__int64)((unsigned __int64)(aGetFreeSpace ? free.QuadPart : total.QuadPart)
/ (1024*1024));
}
else // For unpatched versions of Win95/NT4, fall back to compatibility mode.
{
DWORD sectors_per_cluster, bytes_per_sector, free_clusters, total_clusters;
if (!GetDiskFreeSpace(buf, §ors_per_cluster, &bytes_per_sector, &free_clusters, &total_clusters))
goto error;
free_space = (__int64)((unsigned __int64)((aGetFreeSpace ? free_clusters : total_clusters)
* sectors_per_cluster * bytes_per_sector) / (1024*1024));
}
g_ErrorLevel->Assign(ERRORLEVEL_NONE); // Indicate success.
return OUTPUT_VAR->Assign(free_space);
error:
return SetErrorLevelOrThrow();
}
ResultType Line::Drive(LPTSTR aCmd, LPTSTR aValue, LPTSTR aValue2) // aValue not aValue1, for use with a shared macro.
{
DriveCmds drive_cmd = ConvertDriveCmd(aCmd);
TCHAR path[MAX_PATH + 1]; // +1 to allow room for trailing backslash in case it needs to be added.
size_t path_length;
// Notes about the below macro:
// - It adds a backslash to the contents of the path variable because certain API calls or OS versions
// might require it.
// - It is used by both Drive() and DriveGet().
// - Leave space for the backslash in case its needed.
#define DRIVE_SET_PATH \
tcslcpy(path, aValue, _countof(path) - 1);\
path_length = _tcslen(path);\
if (path_length && path[path_length - 1] != '\\')\
path[path_length++] = '\\';
switch(drive_cmd)
{
case DRIVE_CMD_INVALID:
// Since command names are validated at load-time, this only happens if the command name
// was contained in a variable reference. Since that is very rare, just set ErrorLevel
// and return:
return SetErrorLevelOrThrow();
case DRIVE_CMD_LOCK:
case DRIVE_CMD_UNLOCK:
return SetErrorLevelOrThrowBool(!DriveLock(*aValue, drive_cmd == DRIVE_CMD_LOCK));
case DRIVE_CMD_EJECT:
// Don't do DRIVE_SET_PATH in this case since trailing backslash might prevent it from
// working on some OSes.
// It seems best not to do the below check since:
// 1) aValue usually lacks a trailing backslash so that it will work correctly with "open c: type cdaudio".
// That lack might prevent DriveGetType() from working on some OSes.
// 2) It's conceivable that tray eject/retract might work on certain types of drives even though
// they aren't of type DRIVE_CDROM.
// 3) One or both of the calls to mciSendString() will simply fail if the drive isn't of the right type.
//if (GetDriveType(aValue) != DRIVE_CDROM) // Testing reveals that the below method does not work on Network CD/DVD drives.
// return g_ErrorLevel->Assign(ERRORLEVEL_ERROR);
TCHAR mci_string[256];
MCIERROR error;
// Note: The following comment is obsolete because research of MSDN indicates that there is no way
// not to wait when the tray must be physically opened or closed, at least on Windows XP. Omitting
// the word "wait" from both "close cd wait" and "set cd door open/closed wait" does not help, nor
// does replacing wait with the word notify in "set cdaudio door open/closed wait".
// The word "wait" is always specified with these operations to ensure consistent behavior across
// all OSes (on the off-chance that the absence of "wait" really avoids waiting on Win9x or future
// OSes, or perhaps under certain conditions or for certain types of drives). See above comment
// for details.
if (!*aValue) // When drive is omitted, operate upon default CD/DVD drive.
{
sntprintf(mci_string, _countof(mci_string), _T("set cdaudio door %s wait"), ATOI(aValue2) == 1 ? _T("closed") : _T("open"));
error = mciSendString(mci_string, NULL, 0, NULL); // Open or close the tray.
return SetErrorLevelOrThrowBool(error);
}
sntprintf(mci_string, _countof(mci_string), _T("open %s type cdaudio alias cd wait shareable"), aValue);
if (mciSendString(mci_string, NULL, 0, NULL)) // Error.
return SetErrorLevelOrThrow();
sntprintf(mci_string, _countof(mci_string), _T("set cd door %s wait"), ATOI(aValue2) == 1 ? _T("closed") : _T("open"));
error = mciSendString(mci_string, NULL, 0, NULL); // Open or close the tray.
mciSendString(_T("close cd wait"), NULL, 0, NULL);
return SetErrorLevelOrThrowBool(error);
case DRIVE_CMD_LABEL: // Note that it is possible and allowed for the new label to be blank.
DRIVE_SET_PATH
SetErrorMode(SEM_FAILCRITICALERRORS); // So that a floppy drive doesn't prompt for a disk
return SetErrorLevelOrThrowBool(!SetVolumeLabel(path, aValue2));
} // switch()
return FAIL; // Should never be executed. Helps catch bugs.
}
ResultType Line::DriveLock(TCHAR aDriveLetter, bool aLockIt)
{
HANDLE hdevice;
DWORD unused;
BOOL result;
if (g_os.IsWin9x())
{
// [email protected] has confirmed that the code below works on Win98 with an IDE CD Drive:
// System: Win98 IDE CdRom (my ejector is CloseTray)
// I get a blue screen when I try to eject after using the test script.
// "eject request to drive in use"
// It asks me to Ok or Esc, Ok is default.
// -probably a bit scary for a novice.
// BUT its locked alright!"
// Use the Windows 9x method. The code below is based on an example posted by Microsoft.
// Note: The presence of the code below does not add a detectible amount to the EXE size
// (probably because it's mostly defines and data types).
#pragma pack(push, 1)
typedef struct _DIOC_REGISTERS
{
DWORD reg_EBX;
DWORD reg_EDX;
DWORD reg_ECX;
DWORD reg_EAX;
DWORD reg_EDI;
DWORD reg_ESI;
DWORD reg_Flags;
} DIOC_REGISTERS, *PDIOC_REGISTERS;
typedef struct _PARAMBLOCK
{
BYTE Operation;
BYTE NumLocks;
} PARAMBLOCK, *PPARAMBLOCK;
#pragma pack(pop)
// MS: Prepare for lock or unlock IOCTL call
#define CARRY_FLAG 0x1
#define VWIN32_DIOC_DOS_IOCTL 1
#define LOCK_MEDIA 0
#define UNLOCK_MEDIA 1
#define STATUS_LOCK 2
PARAMBLOCK pb = {0};
pb.Operation = aLockIt ? LOCK_MEDIA : UNLOCK_MEDIA;
DIOC_REGISTERS regs = {0};
regs.reg_EAX = 0x440D;
regs.reg_EBX = ctoupper(aDriveLetter) - 'A' + 1; // Convert to drive index. 0 = default, 1 = A, 2 = B, 3 = C
regs.reg_ECX = 0x0848; // MS: Lock/unlock media
regs.reg_EDX = (DWORD)(size_t)&pb;
// MS: Open VWIN32
hdevice = CreateFile(_T("\\\\.\\vwin32"), 0, 0, NULL, 0, FILE_FLAG_DELETE_ON_CLOSE, NULL);
if (hdevice == INVALID_HANDLE_VALUE)
return FAIL;
// MS: Call VWIN32
result = DeviceIoControl(hdevice, VWIN32_DIOC_DOS_IOCTL, ®s, sizeof(regs), ®s, sizeof(regs), &unused, 0);
if (result)
result = !(regs.reg_Flags & CARRY_FLAG);
}
else // NT4/2k/XP or later
{
// The calls below cannot work on Win9x (as documented by MSDN's PREVENT_MEDIA_REMOVAL).
// Don't even attempt them on Win9x because they might blow up.
TCHAR filename[64];
_stprintf(filename, _T("\\\\.\\%c:"), aDriveLetter);
// FILE_READ_ATTRIBUTES is not enough; it yields "Access Denied" error. So apparently all or part
// of the sub-attributes in GENERIC_READ are needed. An MSDN example implies that GENERIC_WRITE is
// only needed for GetDriveType() == DRIVE_REMOVABLE drives, and maybe not even those when all we
// want to do is lock/unlock the drive (that example did quite a bit more). In any case, research
// indicates that all CD/DVD drives are ever considered DRIVE_CDROM, not DRIVE_REMOVABLE.
// Due to this and the unlikelihood that GENERIC_WRITE is ever needed anyway, GetDriveType() is
// not called for the purpose of conditionally adding the GENERIC_WRITE attribute.
hdevice = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hdevice == INVALID_HANDLE_VALUE)
return FAIL;
PREVENT_MEDIA_REMOVAL pmr;
pmr.PreventMediaRemoval = aLockIt;
result = DeviceIoControl(hdevice, IOCTL_STORAGE_MEDIA_REMOVAL, &pmr, sizeof(PREVENT_MEDIA_REMOVAL)
, NULL, 0, &unused, NULL);
}
CloseHandle(hdevice);
return result ? OK : FAIL;
}
ResultType Line::DriveGet(LPTSTR aCmd, LPTSTR aValue)
{
DriveGetCmds drive_get_cmd = ConvertDriveGetCmd(aCmd);
if (drive_get_cmd == DRIVEGET_CMD_CAPACITY)
return DriveSpace(aValue, false);
TCHAR path[MAX_PATH + 1]; // +1 to allow room for trailing backslash in case it needs to be added.
size_t path_length;
if (drive_get_cmd == DRIVEGET_CMD_SETLABEL) // The is retained for backward compatibility even though the Drive cmd is normally used.
{
DRIVE_SET_PATH
SetErrorMode(SEM_FAILCRITICALERRORS); // If drive is a floppy, prevents pop-up dialog prompting to insert disk.
LPTSTR new_label = omit_leading_whitespace(aCmd + 9); // Example: SetLabel:MyLabel
return g_ErrorLevel->Assign(SetVolumeLabel(path, new_label) ? ERRORLEVEL_NONE : ERRORLEVEL_ERROR);
}
Var &output_var = *OUTPUT_VAR;
output_var.Assign(); // Init to empty string.
switch(drive_get_cmd)
{
case DRIVEGET_CMD_INVALID:
// Since command names are validated at load-time, this only happens if the command name
// was contained in a variable reference. Since that is very rare, just set ErrorLevel
// and return:
goto error;
case DRIVEGET_CMD_LIST:
{
UINT drive_type;
#define ALL_DRIVE_TYPES 256
if (!*aValue) drive_type = ALL_DRIVE_TYPES;
else if (!_tcsicmp(aValue, _T("CDRom"))) drive_type = DRIVE_CDROM;
else if (!_tcsicmp(aValue, _T("Removable"))) drive_type = DRIVE_REMOVABLE;
else if (!_tcsicmp(aValue, _T("Fixed"))) drive_type = DRIVE_FIXED;
else if (!_tcsicmp(aValue, _T("Network"))) drive_type = DRIVE_REMOTE;
else if (!_tcsicmp(aValue, _T("Ramdisk"))) drive_type = DRIVE_RAMDISK;
else if (!_tcsicmp(aValue, _T("Unknown"))) drive_type = DRIVE_UNKNOWN;
else
goto error;
TCHAR found_drives[32]; // Need room for all 26 possible drive letters.
int found_drives_count;
UCHAR letter;
TCHAR buf[128], *buf_ptr;
SetErrorMode(SEM_FAILCRITICALERRORS); // If drive is a floppy, prevents pop-up dialog prompting to insert disk.
for (found_drives_count = 0, letter = 'A'; letter <= 'Z'; ++letter)
{
buf_ptr = buf;
*buf_ptr++ = letter;
*buf_ptr++ = ':';
*buf_ptr++ = '\\';
*buf_ptr = '\0';
UINT this_type = GetDriveType(buf);
if (this_type == drive_type || (drive_type == ALL_DRIVE_TYPES && this_type != DRIVE_NO_ROOT_DIR))
found_drives[found_drives_count++] = letter; // Store just the drive letters.
}
found_drives[found_drives_count] = '\0'; // Terminate the string of found drive letters.
output_var.Assign(found_drives);
if (!*found_drives)
goto error; // Seems best to flag zero drives in the system as ErrorLevel of "1".
break;
}
case DRIVEGET_CMD_FILESYSTEM:
case DRIVEGET_CMD_LABEL:
case DRIVEGET_CMD_SERIAL:
{
TCHAR volume_name[256];
TCHAR file_system[256];
DRIVE_SET_PATH
SetErrorMode(SEM_FAILCRITICALERRORS); // If drive is a floppy, prevents pop-up dialog prompting to insert disk.
DWORD serial_number, max_component_length, file_system_flags;
if (!GetVolumeInformation(path, volume_name, _countof(volume_name) - 1, &serial_number, &max_component_length
, &file_system_flags, file_system, _countof(file_system) - 1))
goto error;
switch(drive_get_cmd)
{
case DRIVEGET_CMD_FILESYSTEM: output_var.Assign(file_system); break;
case DRIVEGET_CMD_LABEL: output_var.Assign(volume_name); break;
case DRIVEGET_CMD_SERIAL: output_var.Assign(serial_number); break;
}
break;
}
case DRIVEGET_CMD_TYPE:
{
DRIVE_SET_PATH
SetErrorMode(SEM_FAILCRITICALERRORS); // If drive is a floppy, prevents pop-up dialog prompting to insert disk.
switch (GetDriveType(path))
{
case DRIVE_UNKNOWN: output_var.Assign(_T("Unknown")); break;
case DRIVE_REMOVABLE: output_var.Assign(_T("Removable")); break;
case DRIVE_FIXED: output_var.Assign(_T("Fixed")); break;
case DRIVE_REMOTE: output_var.Assign(_T("Network")); break;
case DRIVE_CDROM: output_var.Assign(_T("CDROM")); break;
case DRIVE_RAMDISK: output_var.Assign(_T("RAMDisk")); break;
default: // DRIVE_NO_ROOT_DIR
goto error;
}
break;
}
case DRIVEGET_CMD_STATUS:
{
DRIVE_SET_PATH
SetErrorMode(SEM_FAILCRITICALERRORS); // If drive is a floppy, prevents pop-up dialog prompting to insert disk.
DWORD sectors_per_cluster, bytes_per_sector, free_clusters, total_clusters;
switch (GetDiskFreeSpace(path, §ors_per_cluster, &bytes_per_sector, &free_clusters, &total_clusters)
? ERROR_SUCCESS : GetLastError())
{
case ERROR_SUCCESS: output_var.Assign(_T("Ready")); break;
case ERROR_PATH_NOT_FOUND: output_var.Assign(_T("Invalid")); break;
case ERROR_NOT_READY: output_var.Assign(_T("NotReady")); break;
case ERROR_WRITE_PROTECT: output_var.Assign(_T("ReadOnly")); break;
default: output_var.Assign(_T("Unknown"));
}
break;
}
case DRIVEGET_CMD_STATUSCD:
// Don't do DRIVE_SET_PATH in this case since trailing backslash might prevent it from
// working on some OSes.
// It seems best not to do the below check since:
// 1) aValue usually lacks a trailing backslash so that it will work correctly with "open c: type cdaudio".
// That lack might prevent DriveGetType() from working on some OSes.
// 2) It's conceivable that tray eject/retract might work on certain types of drives even though
// they aren't of type DRIVE_CDROM.
// 3) One or both of the calls to mciSendString() will simply fail if the drive isn't of the right type.
//if (GetDriveType(aValue) != DRIVE_CDROM) // Testing reveals that the below method does not work on Network CD/DVD drives.
// return g_ErrorLevel->Assign(ERRORLEVEL_ERROR);
TCHAR mci_string[256], status[128];
// Note that there is apparently no way to determine via mciSendString() whether the tray is ejected
// or not, since "open" is returned even when the tray is closed but there is no media.
if (!*aValue) // When drive is omitted, operate upon default CD/DVD drive.
{
if (mciSendString(_T("status cdaudio mode"), status, _countof(status), NULL)) // Error.
goto error;
}
else // Operate upon a specific drive letter.
{
sntprintf(mci_string, _countof(mci_string), _T("open %s type cdaudio alias cd wait shareable"), aValue);
if (mciSendString(mci_string, NULL, 0, NULL)) // Error.
goto error;
MCIERROR error = mciSendString(_T("status cd mode"), status, _countof(status), NULL);
mciSendString(_T("close cd wait"), NULL, 0, NULL);
if (error)
goto error;
}
// Otherwise, success:
output_var.Assign(status);
break;
} // switch()
// Note that ControlDelay is not done for the Get type commands, because it seems unnecessary.
return g_ErrorLevel->Assign(ERRORLEVEL_NONE); // Indicate success.
error:
return SetErrorLevelOrThrow();
}
ResultType Line::SoundSetGet(LPTSTR aSetting, LPTSTR aComponentType, LPTSTR aControlType, LPTSTR aDevice)
// If the caller specifies NULL for aSetting, the mode will be "Get". Otherwise, it will be "Set".
{
int instance_number = 1; // Set default.
DWORD component_type = *ARG2 ? SoundConvertComponentType(ARG2, &instance_number) : MIXERLINE_COMPONENTTYPE_DST_SPEAKERS;
DWORD control_type = *ARG3 ? SoundConvertControlType(ARG3) : MIXERCONTROL_CONTROLTYPE_VOLUME;
#define SOUND_MODE_IS_SET aSetting // Boolean: i.e. if it's not NULL, the mode is "SET".
if (!SOUND_MODE_IS_SET)
OUTPUT_VAR->Assign(); // Init to empty string regardless of whether we succeed here.
// Rare, since load-time validation would have caught problems unless the params were variable references.
// Text values for ErrorLevels should be kept below 64 characters in length so that the variable doesn't
// have to be expanded with a different memory allocation method:
if (control_type == MIXERCONTROL_CONTROLTYPE_INVALID || aComponentType == MIXERLINE_COMPONENTTYPE_DST_UNDEFINED)
return SetErrorLevelOrThrowStr(_T("Invalid Control Type or Component Type"));
if (g_os.IsWinVistaOrLater())
return SoundSetGetVista(aSetting, component_type, instance_number, control_type, aDevice);
else
return SoundSetGet2kXP(aSetting, component_type, instance_number, control_type, aDevice);
}
ResultType Line::SoundSetGet2kXP(LPTSTR aSetting, DWORD aComponentType, int aComponentInstance
, DWORD aControlType, LPTSTR aDevice)
{
int aMixerID = *aDevice ? ATOI(aDevice) - 1 : 0;
if (aMixerID < 0)
aMixerID = 0;
double setting_percent;
Var *output_var;
if (SOUND_MODE_IS_SET)
{
output_var = NULL; // To help catch bugs.
setting_percent = ATOF(aSetting);
if (setting_percent < -100)
setting_percent = -100;
else if (setting_percent > 100)
setting_percent = 100;
}
else // The mode is GET.
{
output_var = OUTPUT_VAR;
}
// Open the specified mixer ID:
HMIXER hMixer;
if (mixerOpen(&hMixer, aMixerID, 0, 0, 0) != MMSYSERR_NOERROR)
return SetErrorLevelOrThrowStr(_T("Can't Open Specified Mixer"));
// Find out how many destinations are available on this mixer (should always be at least one):
int dest_count;
diff --git a/source/script_struct.cpp b/source/script_struct.cpp
index 8d888c4..6549e9b 100644
--- a/source/script_struct.cpp
+++ b/source/script_struct.cpp
@@ -1,1910 +1,1907 @@
#include "stdafx.h" // pre-compiled headers
#include "defines.h"
#include "application.h"
#include "globaldata.h"
#include "script.h"
#include "TextIO.h"
#include "script_object.h"
//
// Struct::Create - Called by BIF_ObjCreate to create a new object, optionally passing key/value pairs to set.
//
Struct *Struct::Create(ExprTokenType *aParam[], int aParamCount)
// This code is very similar to BIF_sizeof so should be maintained together
{
int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system
int offset = 0; // also used to calculate total size of structure
int arraydef = 0; // count arraysize to update offset
int unionoffset[100]; // backup offset before we enter union or structure
int unionsize[100]; // calculate unionsize
bool unionisstruct[100]; // updated to move offset for structure in structure
int totalunionsize = 0; // total size of all unions and structures in structure
int uniondepth = 0; // count how deep we are in union/structure
int ispointer = NULL; // identify pointer and how deep it goes
int aligntotal = 0; // pointer alignment for total structure
int thissize; // used to check if type was found in above array.
// following are used to find variable and also get size of a structure defined in variable
// this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit
ResultType Result = OK;
ExprTokenType ResultToken;
ExprTokenType Var1,Var2,Var3;
ExprTokenType *param[] = {&Var1,&Var2,&Var3};
Var1.symbol = SYM_VAR;
Var2.symbol = SYM_INTEGER;
Var3.symbol = SYM_INTEGER;
// will hold pointer to structure definition string while we parse trough it
TCHAR *buf;
size_t buf_size;
// Use enough buffer to accept any definition in a field.
TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment
// definition and field name are same max size as variables
// also add enough room to store pointers (**) and arrays [1000]
TCHAR defbuf[MAX_VAR_NAME_LENGTH*2 + 40]; // give more room to use local or static variable Function(variable)
TCHAR keybuf[MAX_VAR_NAME_LENGTH + 40];
// buffer for arraysize + 2 for bracket ] and terminating character
TCHAR intbuf[MAX_INTEGER_LENGTH + 2];
FieldType *field; // used to define a field
// Structure object is saved in fixed order
// insert_pos is simply increased each time
// for loop will enumerate items in same order as it was created
IndexType insert_pos = 0;
// the new structure object
Struct *obj = new Struct();
// Parameter passed to IsDefaultType needs to be ' Definition '
// this is because spaces are used as delimiters ( see IsDefaultType function )
// So first character will be always a space
defbuf[0] = ' ';
if (TokenToObject(*aParam[0]))
{
obj->Release();
obj = ((Struct *)TokenToObject(*aParam[0]))->Clone();
if (aParamCount > 2)
{
obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]);
obj->ObjectToStruct(TokenToObject(*aParam[2]));
}
else if (aParamCount > 1)
{
if (TokenToObject(*aParam[1]))
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,offset);
obj->ObjectToStruct(TokenToObject(*aParam[1]));
}
else
obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]);
}
else
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
}
return obj;
}
// Set initial capacity to avoid multiple expansions.
// For simplicity, failure is handled by the loop below.
obj->SetInternalCapacity(aParamCount >> 1);
// Set buf to beginning of structure definition
buf = TokenToString(*aParam[0]);
// continue as long as we did not reach end of string / structure definition
while (*buf)
{
if (!_tcsncmp(buf,_T("//"),2)) // exclude comments
{
buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf));
if (!*buf)
break; // end of definition reached
}
if (buf == StrChrAny(buf,_T("\n\r\t ")))
{ // Ignore spaces, tabs and new lines before field definition
buf++;
continue;
}
else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,"))))
{ // union or structure in structure definition
if (!uniondepth++)
totalunionsize = 0; // done here to reduce code
if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{'))
unionisstruct[uniondepth] = true; // mark that union is a structure
else
unionisstruct[uniondepth] = false;
// backup offset because we need to set it back after this union / struct was parsed
// unionsize is initialized to 0 and buffer moved to next character
unionoffset[uniondepth] = offset; // backup offset
unionsize[uniondepth] = 0;
// ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union
buf = _tcschr(buf,'{') + 1;
continue;
}
else if (*buf == '}')
{ // update union
// restore offset even if we had a structure in structure
if (unionsize[uniondepth]>totalunionsize)
totalunionsize = unionsize[uniondepth];
// last item in union or structure, update offset now if not struct, for struct offset is up to date
if (--uniondepth == 0)
{
// end of structure, align it
if (totalunionsize % aligntotal)
totalunionsize += aligntotal - (totalunionsize % aligntotal);
if (!unionisstruct[uniondepth + 1]) // because it was decreased above
offset += totalunionsize;
else if (offset % aligntotal)
offset += aligntotal - (offset % aligntotal);
}
else
offset = unionoffset[uniondepth];
buf++;
if (buf == StrChrAny(buf,_T(";,")))
buf++;
continue;
}
// set defaults
ispointer = false;
arraydef = 0;
// copy current definition field to temporary buffer
if (StrChrAny(buf, _T("};,")))
{
if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1)
{
obj->Release();
return NULL;
}
_tcsncpy(tempbuf,buf,buf_size);
tempbuf[buf_size] = '\0';
}
else if (_tcslen(buf) > LINE_SIZE - 1)
{
obj->Release();
return NULL;
}
else
_tcscpy(tempbuf,buf);
// Trim trailing spaces
rtrim(tempbuf);
// Pointer
if (_tcschr(tempbuf,'*'))
ispointer = StrReplace(tempbuf, _T("*"), _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
// Array
if (_tcschr(tempbuf,'['))
{
_tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH);
intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0';
arraydef = (int)ATOI64(intbuf + 1);
// remove array definition from temp buffer to identify key easier
StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE);
// Trim trailing spaces in case we had a definition like UInt [10]
rtrim(tempbuf);
}
// copy type
// if offset is 0 and there are no };, characters, it means we have a pure definition
if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset))
{
if ((buf_size = _tcscspn(tempbuf,_T("\t "))) > MAX_VAR_NAME_LENGTH*2 + 30)
{
obj->Release();
return NULL;
}
_tcsncpy(defbuf + 1,tempbuf,buf_size);
//_tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t ")),_T(" "));
defbuf[1 + buf_size] = ' ';
defbuf[2 + buf_size] = '\0';
if (StrChrAny(tempbuf, _T(" \t")))
{
if (_tcslen(StrChrAny(tempbuf, _T(" \t"))) > MAX_VAR_NAME_LENGTH + 30)
{
obj->Release();
return NULL;
}
_tcscpy(keybuf,StrChrAny(tempbuf, _T(" \t")) + 1);
ltrim(keybuf);
}
else
keybuf[0] = '\0';
}
else // Not 'TypeOnly' definition because there are more than one fields in array so use default type UInt
{
_tcscpy(defbuf,_T(" UInt "));
_tcscpy(keybuf,tempbuf);
}
// Now find size in default types array and create new field
// If Type not found, resolve type to variable and get size of struct defined in it
if ((thissize = IsDefaultType(defbuf)))
{
if (!_tcscmp(defbuf,_T(" bool ")))
thissize = 1;
// align offset
if (ispointer)
{
if (offset % ptrsize)
offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1);
if (ptrsize > aligntotal)
aligntotal = ptrsize;
}
else
{
if (offset % thissize)
offset += thissize - (offset % thissize);
if (thissize > aligntotal)
aligntotal = thissize > ptrsize ? ptrsize : thissize;
}
- if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,NULL,ispointer ? ptrsize : thissize
+ if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,NULL,thissize
,ispointer ? true : !tcscasestr(_T(" FLOAT DOUBLE PFLOAT PDOUBLE "),defbuf)
,!tcscasestr(_T(" PTR SHORT INT INT64 CHAR VOID HALF_PTR BOOL INT32 LONG LONG32 LONGLONG LONG64 USN INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM __int64 "),defbuf)
,tcscasestr(_T(" TCHAR LPTSTR LPCTSTR LPWSTR LPCWSTR WCHAR "),defbuf) ? 1200 : tcscasestr(_T(" CHAR LPSTR LPCSTR LPSTR UCHAR "),defbuf) ? 0 : -1)))
{ // Out of memory.
obj->Release();
return NULL;
}
offset += (ispointer ? ptrsize : thissize) * (arraydef ? arraydef : 1);
}
else // type was not found, check for user defined type in variables
{
Var1.var = NULL; // init to not found
Func *bkpfunc = NULL;
// check if we have a local/static declaration and resolve to function
// For example Struct("*MyFunc(mystruct) mystr")
if (_tcschr(defbuf,'('))
{
bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later
g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1);
if (g->CurrentFunc) // break if not found to identify error
{
_tcscpy(tempbuf,defbuf + 1);
_tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'('));
_tcscpy(_tcschr(defbuf,')'),_T(" \0"));
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL);
g->CurrentFunc = bkpfunc;
}
else // release object and return
{
g->CurrentFunc = bkpfunc;
obj->Release();
return NULL;
}
}
else if (g->CurrentFunc) // try to find local variable first
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL);
// try to find global variable if local was not found or we are not in func
if (Var1.var == NULL)
Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL);
// variable found
if (Var1.var != NULL)
{
if (!ispointer && !_tcsncmp(tempbuf,buf,_tcslen(buf)) && !*keybuf)
{ // Whole definition is not a pointer and no key was given so create Structure from variable
obj->Release();
if (aParamCount == 1)
{
if (TokenToObject(*param[0]))
{ // assume variable is a structure object
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
return obj;
}
// else create structure from string definition
return Struct::Create(param,1);
}
else if (aParamCount > 1)
{ // more than one parameter was given, copy aParam to param
param[1]->symbol = aParam[1]->symbol;
param[1]->object = aParam[1]->object;
param[1]->value_int64 = aParam[1]->value_int64;
param[1]->var = aParam[1]->var;
}
if (aParamCount > 2)
{ // more than 2 parameters were given, copy aParam to param
param[2]->symbol = aParam[2]->symbol;
param[2]->object = aParam[2]->object;
param[2]->var = aParam[2]->var;
// definition variable is a structure object, clone it, assign memory and init object
if (TokenToObject(*param[0]))
{
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
obj->mMemAllocated = 0;
obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64;
obj->ObjectToStruct(TokenToObject(*aParam[2]));
return obj;
}
return Struct::Create(param,3);
}
else if (TokenToObject(*param[0]))
{ // definition variable is a structure object, clone it and assign memory or init object
obj = ((Struct *)TokenToObject(*param[0]))->Clone();
if (TokenToObject(*aParam[1]))
{
obj->mStructMem = (UINT_PTR *)malloc(obj->mSize);
obj->mMemAllocated = obj->mSize;
memset(obj->mStructMem,NULL,obj->mSize);
obj->ObjectToStruct(TokenToObject(*aParam[1]));
}
else
obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64;
return obj;
}
// else simply create structure from variable and given memory/initobject
return Struct::Create(param,2);
}
// Call BIF_sizeof passing offset in second parameter to align offset if necessary
// if field is a pointer we will need its size only
if (!ispointer)
{
param[1]->value_int64 = (__int64)ispointer ? 0 : offset;
param[2]->value_int64 = (__int64)&aligntotal;
BIF_sizeof(Result,ResultToken,param,ispointer ? 1 : 3);
if (ResultToken.symbol != SYM_INTEGER)
{ // could not resolve structure
obj->Release();
return NULL;
}
}
else
{
if (offset % ptrsize)
offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1);
if (ptrsize > aligntotal)
aligntotal = ptrsize;
}
// Insert new field in our structure
- if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,Var1.var,ispointer ? ptrsize : (int)ResultToken.value_int64,1,1,-1)))
+ if (!(field = obj->Insert(keybuf, insert_pos++, ispointer, offset, arraydef, Var1.var, (int)ResultToken.value_int64,1,1,-1)))
{ // Out of memory.
obj->Release();
return NULL;
}
if (ispointer)
offset += (int)ptrsize * (arraydef ? arraydef : 1);
else
// sizeof was given an offset that it applied and aligned if necessary, so set offset = and not +=
offset = (int)ResultToken.value_int64 + (arraydef ? ((arraydef - 1) * ((int)ResultToken.value_int64 - offset)) : 0);
}
else // No variable was found and it is not default type so we can't determine size.
{
obj->Release();
return NULL;
}
}
// update union size
if (uniondepth)
{
if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth])
unionsize[uniondepth] = offset - unionoffset[uniondepth];
// reset offset if in union and union is not a structure
if (!unionisstruct[uniondepth])
offset = unionoffset[uniondepth];
}
// Move buffer pointer now
if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,"))))
buf += _tcscspn(buf,_T("}")); // keep } character to update union
else if (StrChrAny(buf, _T(";,")))
buf += _tcscspn(buf,_T(";,")) + 1;
else
{
// identify that structure object has no fields
if (!*keybuf)
obj->mTypeOnly = true;
buf += _tcslen(buf);
}
}
// align total structure if necessary
if (aligntotal && offset % aligntotal)
offset += aligntotal - (offset % aligntotal);
if (!offset) // structure could not be build
{
obj->Release();
return NULL;
}
obj->mSize = offset;
if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1]))
{ // second parameter exist and it is digit assumme this is new pointer for our structure
obj->mStructMem = (UINT_PTR *)TokenToInt64(*aParam[1]);
obj->mMemAllocated = 0;
}
else // no pointer given so allocate memory and fill memory with 0
{ // setting the memory after parsing definition saves a call to BIF_sizeof
obj->mStructMem = (UINT_PTR *)malloc(offset);
obj->mMemAllocated = offset;
memset(obj->mStructMem,NULL,offset);
}
// an object was passed to initialize fields
// enumerate trough object and assign values
if ((aParamCount > 1 && !TokenIsPureNumeric(*aParam[1])) || aParamCount > 2 )
obj->ObjectToStruct(TokenToObject(*aParam[aParamCount - 1]));
return obj;
}
//
// Struct::ObjectToStruct - Initialize structure from array, object or structure.
//
void Struct::ObjectToStruct(IObject *objfrom)
{
ExprTokenType ResultToken, this_token,enum_token,param_tokens[3];
ExprTokenType *params[] = { param_tokens, param_tokens+1, param_tokens+2 };
TCHAR defbuf[MAX_PATH],buf[MAX_PATH];
int param_count = 3;
// Set up enum_token the way Invoke expects:
enum_token.symbol = SYM_STRING;
enum_token.marker = _T("");
enum_token.mem_to_free = NULL;
enum_token.buf = defbuf;
// Prepare to call object._NewEnum():
param_tokens[0].symbol = SYM_STRING;
param_tokens[0].marker = _T("_NewEnum");
objfrom->Invoke(enum_token, ResultToken, IT_CALL, params, 1);
if (enum_token.mem_to_free)
// Invoke returned memory for us to free.
free(enum_token.mem_to_free);
// Check if object returned an enumerator, otherwise return
if (enum_token.symbol != SYM_OBJECT)
return;
// create variables to use in for loop / for enumeration
// these will be deleted afterwards
Var *var1 = (Var*)alloca(sizeof(Var));
Var *var2 = (Var*)alloca(sizeof(Var));
var1->mType = var2->mType = VAR_NORMAL;
var1->mAttrib = var2->mAttrib = 0;
var1->mByteCapacity = var2->mByteCapacity = 0;
var1->mHowAllocated = var2->mHowAllocated = ALLOC_MALLOC;
// Prepare parameters for the loop below: enum.Next(var1 [, var2])
param_tokens[0].marker = _T("Next");
param_tokens[1].symbol = SYM_VAR;
param_tokens[1].var = var1;
param_tokens[1].mem_to_free = 0;
param_tokens[2].symbol = SYM_VAR;
param_tokens[2].var = var2;
param_tokens[2].mem_to_free = 0;
ExprTokenType result_token;
IObject &enumerator = *enum_token.object; // Might perform better as a reference?
this_token.symbol = SYM_OBJECT;
this_token.object = this;
for (;;)
{
// Set up result_token the way Invoke expects; each Invoke() will change some or all of these:
result_token.symbol = SYM_STRING;
result_token.marker = _T("");
result_token.mem_to_free = NULL;
result_token.buf = buf;
// Call enumerator.Next(var1, var2)
enumerator.Invoke(result_token,enum_token,IT_CALL, params, param_count);
bool next_returned_true = TokenToBOOL(result_token, TokenIsPureNumeric(result_token));
if (!next_returned_true)
break;
this->Invoke(ResultToken,this_token,IT_SET,params+1,2);
// release object if it was assigned prevoiously when calling enum.Next
if (var1->IsObject())
var1->ReleaseObject();
if (var2->IsObject())
var2->ReleaseObject();
// Free any memory or object which may have been returned by Invoke:
if (result_token.mem_to_free)
free(result_token.mem_to_free);
if (result_token.symbol == SYM_OBJECT)
result_token.object->Release();
}
// release enumerator and free vars
enumerator.Release();
var1->Free();
var2->Free();
}
//
// Struct::Delete - Called immediately before the object is deleted.
// Returns false if object should not be deleted yet.
//
bool Struct::Delete()
{
return ObjectBase::Delete();
}
Struct::~Struct()
{
if (mMemAllocated > 0)
free(mStructMem);
if (mFields)
{
if (mFieldCount)
{
IndexType i = mFieldCount - 1;
// Free keys
for ( ; i >= 0 ; --i)
{
if (mFields[i].mMemAllocated > 0)
free(mFields[i].mStructMem);
free(mFields[i].key);
}
}
// Free fields array.
free(mFields);
}
}
//
// Struct::SetPointer - used to set pointer for a field or array item
//
UINT_PTR Struct::SetPointer(UINT_PTR aPointer,int aArrayItem)
{
if (mIsPointer)
*((UINT_PTR*)(*mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer;
else
*((UINT_PTR*)((UINT_PTR)mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer;
return aPointer;
}
//
// Struct::FieldType::Clone - used to clone a field to structure.
//
Struct *Struct::CloneField(FieldType *field,bool aIsDynamic)
// Creates an object and copies to it the fields at and after the given offset.
{
Struct *objptr = new Struct();
if (!objptr)
return objptr;
Struct &obj = *objptr;
// if field is an array, set correct size
if (obj.mArraySize = field->mArraySize)
obj.mSize = field->mSize*obj.mArraySize;
else
obj.mSize = field->mSize;
obj.mIsInteger = field->mIsInteger;
obj.mIsPointer = field->mIsPointer;
obj.mEncoding = field->mEncoding;
obj.mIsUnsigned = field->mIsUnsigned;
obj.mVarRef = field->mVarRef;
obj.mTypeOnly = 1;
obj.mMemAllocated = aIsDynamic ? -1 : 0;
return objptr;
}
//
// Struct::Clone - used for cloning structures.
//
Struct *Struct::Clone(bool aIsDynamic)
// Creates an object and copies to it the fields at and after the given offset.
{
Struct *objptr = new Struct();
if (!objptr)
return objptr;
Struct &obj = *objptr;
obj.mArraySize = mArraySize;
obj.mIsInteger = mIsInteger;
obj.mIsPointer = mIsPointer;
obj.mEncoding = mEncoding;
obj.mIsUnsigned = mIsUnsigned;
obj.mSize = mSize;
obj.mVarRef = mVarRef;
obj.mTypeOnly = mTypeOnly;
// -1 will identify a dynamic structure, no memory can be allocated to such
obj.mMemAllocated = aIsDynamic ? -1 : 0;
// Allocate space in destination object.
if (!obj.SetInternalCapacity(mFieldCount))
{
obj.Release();
return NULL;
}
FieldType *fields = obj.mFields; // Newly allocated by above.
int failure_count = 0; // See comment below.
IndexType i;
obj.mFieldCount = mFieldCount;
for (i = 0; i < mFieldCount; ++i)
{
FieldType &dst = fields[i];
FieldType &src = mFields[i];
if ( !(dst.key = _tcsdup(src.key)) )
{
// Key allocation failed.
// Rather than trying to set up the object so that what we have
// so far is valid in order to break out of the loop, continue,
// make all fields valid and then allow them to be freed.
++failure_count;
}
dst.mArraySize = src.mArraySize;
dst.mIsInteger = src.mIsInteger;
dst.mIsPointer = src.mIsPointer;
dst.mEncoding = src.mEncoding;
dst.mIsUnsigned = src.mIsUnsigned;
dst.mOffset = src.mOffset;
dst.mSize = src.mSize;
dst.mVarRef = src.mVarRef;
dst.mMemAllocated = aIsDynamic ? -1 : 0;
}
if (failure_count)
{
// One or more memory allocations failed. It seems best to return a clear failure
// indication rather than an incomplete copy. Now that the loop above has finished,
// the object's contents are at least valid and it is safe to free the object:
obj.Release();
return NULL;
}
return &obj;
}
//
// Struct::Invoke - Called by BIF_ObjInvoke when script explicitly interacts with an object.
//
ResultType STDMETHODCALLTYPE Struct::Invoke(
ExprTokenType &aResultToken,
ExprTokenType &aThisToken,
int aFlags,
ExprTokenType *aParam[],
int aParamCount
)
// L40: Revised base mechanism for flexibility and to simplify some aspects.
// obj[] -> obj.base.__Get -> obj.base[] -> obj.base.__Get etc.
{
int ptrsize = sizeof(UINT_PTR);
FieldType *field = NULL; // init to NULL to use in IS_INVOKE_CALL
ResultType Result = OK;
// Used to resolve dynamic structures
ExprTokenType Var1,Var2;
Var1.symbol = SYM_VAR;
Var2.symbol = SYM_INTEGER;
ExprTokenType *param[] = {&Var1,&Var2},ResultToken;
// used to clone a dynamic field or structure
Struct *objclone = NULL;
// used for StrGet/StrPut
LPCVOID source_string;
int source_length;
DWORD flags = WC_NO_BEST_FIT_CHARS;
int length = -1;
int char_count;
// Identify that we need to release/delete field or structure object
bool deletefield = false;
bool releaseobj = false;
int param_count_excluding_rvalue = aParamCount;
// target may be altered here to resolve dynamic structure so hold it separately
UINT_PTR *target = mStructMem;
if (IS_INVOKE_SET)
{
// Prior validation of ObjSet() param count ensures the result won't be negative:
--param_count_excluding_rvalue;
// Since defining base[key] prevents base.base.__Get and __Call from being invoked, it seems best
// to have it also block __Set. The code below is disabled to achieve this, with a slight cost to
// performance when assigning to a new key in any object which has a base object. (The cost may
// depend on how many key-value pairs each base object has.) Note that this doesn't affect meta-
// functions defined in *this* base object, since they were already invoked if present.
//if (IS_INVOKE_META)
//{
// if (param_count_excluding_rvalue == 1)
// // Prevent below from unnecessarily searching for a field, since it won't actually be assigned to.
// // Relies on mBase->Invoke recursion using aParamCount and not param_count_excluding_rvalue.
// param_count_excluding_rvalue = 0;
// //else: Allow SET to operate on a field of an object stored in the target's base.
// // For instance, x[y,z]:=w may operate on x[y][z], x.base[y][z], x[y].base[z], etc.
//}
}
if (!param_count_excluding_rvalue || (param_count_excluding_rvalue == 1 && TokenIsEmptyString(*aParam[0])))
{ // for struct[] and struct[""...] / struct[] := ptr and struct[""...] := ptr
if (IS_INVOKE_SET)
{
if (TokenToObject(*aParam[param_count_excluding_rvalue]))
{ // Initialize structure using an object. e.g. struct[]:={x:1,y:2}
this->ObjectToStruct(TokenToObject(*aParam[param_count_excluding_rvalue]));
// return struct object
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = this;
this->AddRef();
return OK;
}
if (mMemAllocated > 0) // free allocated memory because we will assign a custom pointer
{
free(mStructMem);
mMemAllocated = 0;
}
// assign new pointer to structure
// releasing/deleting structure will not free that memory
mStructMem = (UINT_PTR *)TokenToInt64(*aParam[param_count_excluding_rvalue]);
}
// Return new structure address
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = (__int64)mStructMem;
return OK;
}
else
{
// Array access, struct.1 or struct[1] or struct[1].x ...
if (TokenIsPureNumeric(*aParam[0]))
{
if (param_count_excluding_rvalue > 1 && TokenIsEmptyString(*aParam[1]))
{ // caller wants set/get pointer. E.g. struct.2[""] or struct.2[""] := ptr
if (IS_INVOKE_SET)
{
if (param_count_excluding_rvalue < 3) // simply set pointer
aResultToken.value_int64 = SetPointer((UINT_PTR)TokenToInt64(*aParam[2]),(int)TokenToInt64(*aParam[0]));
else
{ // resolve pointer to pointer and set it
UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + (TokenToInt64(*aParam[0])-1)*(mSize/(mArraySize ? mArraySize : 1))));
for (int i = param_count_excluding_rvalue - 2;i && aDeepPointer;i--)
aDeepPointer = (UINT_PTR*)*aDeepPointer;
*aDeepPointer = (UINT_PTR)TokenToInt64(*aParam[aParamCount]);
aResultToken.value_int64 = *aDeepPointer;
}
}
else // GET pointer
{
if (param_count_excluding_rvalue < 3)
aResultToken.value_int64 = ((mIsPointer ? *target : (UINT_PTR)target) + (TokenToInt64(*aParam[0])-1)*(mSize / (mArraySize ? mArraySize : 1)));
else
{ // resolve pointer to pointer
UINT_PTR *aDeepPointer = ((UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mSize/(mArraySize ? mArraySize : 1))));
for (int i = param_count_excluding_rvalue - 2;i && *aDeepPointer;i--)
aDeepPointer = (UINT_PTR*)*aDeepPointer;
aResultToken.value_int64 = (__int64)aDeepPointer;
}
}
aResultToken.symbol = SYM_INTEGER;
return OK;
}
// Structure is a reference to variable and not a pointer, get size of structure
- if (mVarRef && !mIsPointer)
+ if (mVarRef) // && !mIsPointer)
{
Var2.symbol = SYM_VAR;
Var2.var = mVarRef;
// Variable is a structure object, copy size
if (TokenToObject(Var2))
ResultToken.value_int64 = ((Struct *)TokenToObject(Var2))->mSize;
else
{ // use sizeof to find out the size of structure
param[0]->symbol = SYM_STRING;
Var1.marker = TokenToString(*param[1]);
BIF_sizeof(Result,ResultToken,param,1);
}
}
// Check if we have an array, if structure is not array and not pointer, assume array
- if (mArraySize || !mIsPointer) // if not Array and not pointer assume it is an array
- target = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mIsPointer ? ptrsize : (mVarRef ? ResultToken.value_int64 : mSize/(mArraySize ? mArraySize : 1))));
- else if (mIsPointer) // resolve pointer
- target = (UINT_PTR*)(*target + (TokenToInt64(*aParam[0])-1)*ptrsize);
- else // amend target to memory of field
- target = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mVarRef ? ResultToken.value_int64 : mSize));
+ if (mIsPointer) // resolve pointer
+ target = (UINT_PTR*)(*target + (TokenToInt64(*aParam[0]) - 1)*(mIsPointer>1 ? ptrsize : (mVarRef ? ResultToken.value_int64 : mSize / (mArraySize ? mArraySize : 1))));
+ else // amend target to memory of field, if it is not an array and not a pointer assume array
+ target = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0]) - 1)*(mVarRef ? ResultToken.value_int64 : mSize / (mArraySize ? mArraySize : 1)));
// Structure has a variable reference and might be a pointer but not pointer to pointer
if (mVarRef && mIsPointer < 2)
{
Var2.symbol = SYM_VAR;
Var2.var = mVarRef;
// variable is a structure object, clone it
if (TokenToObject(Var2))
{
objclone = ((Struct *)TokenToObject(Var2))->Clone(true);
objclone->mStructMem = target;
if (mArraySize)
{
objclone->mArraySize = 0;
objclone->mSize = mSize / mArraySize;
}
// Object to Structure
if (IS_INVOKE_SET && TokenToObject(*aParam[1]))
{
objclone->ObjectToStruct(TokenToObject(*aParam[1]));
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = objclone;
return OK;
}
// MULTIPARAM
if (param_count_excluding_rvalue > 1)
{
objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1);
objclone->Release();
return OK;
}
aResultToken.object = objclone;
aResultToken.symbol = SYM_OBJECT;
return OK;
}
else
{
Var1.symbol = SYM_STRING;
Var1.marker = TokenToString(Var2);
Var2.symbol = SYM_INTEGER;
Var2.value_int64 = (UINT_PTR)target;
if (objclone = Struct::Create(param,2))
{
Struct *tempobj = objclone;
objclone = objclone->Clone(true);
objclone->mStructMem = tempobj->mStructMem;
/*
if (mArraySize)
{
objclone->mArraySize = 0;
objclone->mSize = mSize / mArraySize;
}
*/
tempobj->Release();
if (IS_INVOKE_SET && TokenToObject(*aParam[1]))
{
objclone->ObjectToStruct(TokenToObject(*aParam[1]));
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = objclone;
return OK;
}
if (param_count_excluding_rvalue > 1)
{
objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1);
objclone->Release();
return OK;
}
aResultToken.object = objclone;
aResultToken.symbol = SYM_OBJECT;
return OK;
}
else
return INVOKE_NOT_HANDLED;
}
}
else
{
objclone = Clone(true);
releaseobj = true;
objclone->mStructMem = target;
if (!mArraySize && mIsPointer)
objclone->mIsPointer--;
/*else if (mArraySize)
{
objclone->mArraySize = 0;
objclone->mSize = mSize / mArraySize;
}
*/
if (objclone->mIsPointer || (aParamCount == 1 && !mTypeOnly))
{
if (param_count_excluding_rvalue > 1)
{ // MULTIPARAM
objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1);
objclone->Release();
return OK;
}
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = objclone;
return OK;
}
else if (!mTypeOnly)
{ // the given integer is now excluded from parameters
aParamCount--;param_count_excluding_rvalue--;aParam++;
}
}
}
if (mTypeOnly && !IS_INVOKE_CALL) // IS_INVOKE_CALL does not need the tentative field, it will handle it itself
{
if (mVarRef && !TokenIsEmptyString(*aParam[0]))
{
if (releaseobj)
objclone->Release();
Var2.symbol = SYM_VAR;
Var2.var = mVarRef;
if (TokenToObject(Var2) && (objclone = ((Struct *)TokenToObject(Var2))->Clone(true)))
{ // variable is a structure object
objclone->mStructMem = target;
objclone->Invoke(aResultToken,ResultToken ,aFlags,aParam,aParamCount);
objclone->Release();
return OK;
}
else
{
Var1.symbol = SYM_STRING;
Var1.marker = TokenToString(Var2);
Var2.symbol = SYM_INTEGER;
Var2.value_int64 = 0;
if (objclone = Struct::Create(param,2))
{ // create structure from variable
Struct* tempobj = objclone->Clone(true);
// resolve pointer
tempobj->mStructMem = mIsPointer ? (UINT_PTR*)*target : target;
tempobj->Invoke(aResultToken,aThisToken ,aFlags,aParam,aParamCount);
tempobj->Release();
objclone->Release();
return OK;
}
return INVOKE_NOT_HANDLED;
}
}
else // create field from structure
{
field = new FieldType();
deletefield = true;
if (objclone == NULL)
{ // use this structure
field->mMemAllocated = mMemAllocated;
field->mIsInteger = mIsInteger;
field->mIsPointer = mIsPointer;
field->mEncoding = mEncoding;
field->mIsUnsigned = mIsUnsigned;
field->mOffset = 0;
// structure with arrays so set to correct field size
field->mSize = mSize / (mArraySize ? mArraySize : 1);
field->mVarRef = 0;
}
else // use objclone created above
{
field->mMemAllocated = objclone->mMemAllocated;
field->mIsInteger = objclone->mIsInteger;
field->mIsPointer = objclone->mIsPointer;
field->mEncoding = objclone->mEncoding;
field->mIsUnsigned = objclone->mIsUnsigned;
field->mOffset = 0;
field->mSize = objclone->mSize / (objclone->mArraySize ? objclone->mArraySize : 1);
}
}
}
else if (!IS_INVOKE_CALL) // IS_INVOKE_CALL will handle the field itself
field = FindField(TokenToString(*aParam[0]));
}
//
// OPERATE ON A FIELD WITHIN THIS OBJECT
//
// CALL
if (IS_INVOKE_CALL)
{
LPTSTR name = TokenToString(*aParam[0]);
if (*name == '_')
++name; // ++ to exclude '_' from further consideration.
++aParam; --aParamCount; // Exclude the method identifier. A prior check ensures there was at least one param in this case.
if (!_tcsicmp(name, _T("NewEnum")))
{
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return _NewEnum(aResultToken, aParam, aParamCount);
}
// if first function parameter is a field get it
if (!mTypeOnly && aParamCount && !TokenIsPureNumeric(*aParam[0]))
{
if (field = FindField(TokenToString(*aParam[0])))
{ // exclude parameter in aParam
++aParam; --aParamCount;
}
}
aResultToken.symbol = SYM_INTEGER; // mostly used
aResultToken.value_int64 = 0; // set default
if (!_tcsicmp(name, _T("SetCapacity")))
{ // Set strcuture its capacity or fields capacity
if (!field)
{
if (!aParamCount || !TokenIsPureNumeric(*aParam[0]) || !TokenToInt64(*aParam[0]) || TokenToInt64(*aParam[0]) == 0)
{ // 0 or no parameters were given to free memory
if (mMemAllocated > 0)
{
mMemAllocated = 0;
free(mStructMem);
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (mMemAllocated > 0)
free(mStructMem);
// allocate memory and zero-fill
if (mStructMem = (UINT_PTR*)malloc((size_t)TokenToInt64(*aParam[0])))
{
mMemAllocated = (int)TokenToInt64(*aParam[0]);
memset(mStructMem,NULL,(size_t)mMemAllocated);
aResultToken.value_int64 = mMemAllocated;
}
else
mMemAllocated = 0;
}
else if (aParamCount)
{ // we must have to parmeters here since first parameter is field
if (!TokenIsPureNumeric(*aParam[0]) || !TokenToInt64(*aParam[0]) || TokenToInt64(*aParam[0]) == 0)
{
if (field->mMemAllocated > 0)
{
field->mMemAllocated = 0;
free(field->mStructMem);
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK; // not numeric
}
if (field->mMemAllocated > 0)
free(field->mStructMem);
// allocate memory and zero-fill
if (field->mStructMem = (UINT_PTR*)malloc((size_t)TokenToInt64(*aParam[0])))
{
field->mMemAllocated = (int)TokenToInt64(*aParam[0]);
memset(field->mStructMem,NULL,(size_t)field->mMemAllocated);
*((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)field->mStructMem;
aResultToken.value_int64 = mMemAllocated;
}
else
field->mMemAllocated = 0;
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("GetCapacity")))
{
if (field)
aResultToken.value_int64 = field->mMemAllocated;
else
aResultToken.value_int64 = mMemAllocated;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("Offset")))
{
if (field)
aResultToken.value_int64 = field->mOffset;
else if (aParamCount && TokenIsPureNumeric(*aParam[0]))
// calculate size if item is an array
aResultToken.value_int64 = mSize / (mArraySize ? mArraySize : 1) * (TokenToInt64(*aParam[0])-1);
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("IsPointer")))
{
if (field)
aResultToken.value_int64 = field->mIsPointer;
else
aResultToken.value_int64 = mIsPointer;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("Encoding")))
{
if (field)
aResultToken.value_int64 = field->mEncoding == 65535 ? -1 : field->mEncoding;
else
aResultToken.value_int64 = mEncoding == 65535 ? -1 : mEncoding;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("GetPointer")))
{
if (!field && aParamCount && mIsPointer)
{ // resolve array item
if (mArraySize && TokenIsPureNumeric(*aParam[0]))
aResultToken.value_int64 = *((UINT_PTR*)((UINT_PTR)target + ((mIsPointer ? ptrsize : (mSize/mArraySize)) * (TokenToInt64(*aParam[0])-1))));
else
aResultToken.value_int64 = *target;
}
else if (field)
aResultToken.value_int64 = *((UINT_PTR*)((UINT_PTR)target + field->mOffset));
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("Fill")))
{
if (!field) // only allow to fill main structure
{
if (aParamCount && TokenIsPureNumeric(*aParam[0]))
memset(objclone ? objclone->mStructMem : mStructMem,TokenIsPureNumeric(*aParam[0]),mSize);
else if (aParamCount && *TokenToString(*aParam[0]))
memset(objclone ? objclone->mStructMem : mStructMem,*TokenToString(*aParam[0]),mSize);
else
memset(objclone ? objclone->mStructMem : mStructMem,NULL,mSize);
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("GetAddress")))
{
if (!field)
{
if (mArraySize && aParamCount && TokenIsPureNumeric(*aParam[0]))
aResultToken.value_int64 = (UINT_PTR)target + (mSize / mArraySize * (TokenToInt64(*aParam[0])-1));
else
aResultToken.value_int64 = (UINT_PTR)target;
}
else
aResultToken.value_int64 = (UINT_PTR)target + field->mOffset;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("Size")))
{
if (!field)
{
if (mArraySize && aParamCount && TokenIsPureNumeric(*aParam[0]))
// we do not care which item was requested because all are same size
aResultToken.value_int64 = mSize / mArraySize;
else
aResultToken.value_int64 = mSize;
}
else
aResultToken.value_int64 = field->mSize;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("CountOf")))
{
if (!field)
aResultToken.value_int64 = mArraySize;
else
aResultToken.value_int64 = field->mArraySize;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("Clone")) || !_tcsicmp(name, _T("_New")))
{
if (!field)
{
if (!releaseobj) // else we have a clone already
objclone = this->Clone();
}
else
{
Struct* tempobj = objclone;
if (releaseobj) // release object, it is not requred anymore
{
objclone = objclone->CloneField(field);
tempobj->Release();
}
else
objclone = this->CloneField(field);
}
if (aParamCount)
{ // structure pointer and / or init object were given
if (TokenIsPureNumeric(*aParam[0]))
{
objclone->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[0]);
objclone->mMemAllocated = 0;
if (aParamCount > 1 && TokenToObject(*aParam[1]))
objclone->ObjectToStruct(TokenToObject(*aParam[1]));
}
else if (TokenToObject(*aParam[0]))
{
objclone->mStructMem = (UINT_PTR*)malloc(objclone->mSize);
objclone->mMemAllocated = objclone->mSize;
memset(objclone->mStructMem,NULL,objclone->mSize);
objclone->ObjectToStruct(TokenToObject(*aParam[0]));
}
}
else
{
objclone->mStructMem = (UINT_PTR*)malloc(objclone->mSize);
objclone->mMemAllocated = objclone->mSize;
memset(objclone->mStructMem,NULL,objclone->mSize);
}
// small fix for _New to work properly because aThisToken contains the new object
if (!_tcsicmp(name, _T("_New")))
{
if (aThisToken.symbol == SYM_OBJECT)
aThisToken.object->Release();
else
aThisToken.symbol = SYM_OBJECT;
aThisToken.object = objclone;
objclone->AddRef();
}
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = objclone;
if (deletefield) // we created the field from a structure
delete field;
// do not release objclone because it is returned
return OK;
}
// For maintainability: explicitly return since above has done ++aParam, --aParamCount.
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
aResultToken.symbol = SYM_STRING;
aResultToken.marker = _T(""); // identify that method was not found
return INVOKE_NOT_HANDLED;
}
else if (!field)
{ // field was not found
if (releaseobj)
objclone->Release();
return INVOKE_NOT_HANDLED;
}
// MULTIPARAM[x,y] -- may be SET[x,y]:=z or GET[x,y], but always treated like GET[x].
else if (param_count_excluding_rvalue > 1)
{ // second parameter = "", so caller wants get/set field pointer
if (TokenIsEmptyString(*aParam[1]))
{
aResultToken.symbol = SYM_INTEGER;
if (IS_INVOKE_SET)
{
if (param_count_excluding_rvalue < 3)
{ // set simple pointer
*((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)TokenToInt64(*aParam[2]);
aResultToken.value_int64 = (UINT_PTR)*(target + field->mOffset);
}
else // set pointer to pointer
{
UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + field->mOffset));
for (int i = param_count_excluding_rvalue - 2;i && aDeepPointer;i--)
aDeepPointer = (UINT_PTR*)*aDeepPointer;
*aDeepPointer = (UINT_PTR)TokenToInt64(*aParam[aParamCount]);
aResultToken.value_int64 = *aDeepPointer;
}
}
else // GET pointer
{
if (param_count_excluding_rvalue < 3)
aResultToken.value_int64 = (mIsPointer ? *target : (UINT_PTR)target) + field->mOffset;
else
{ // get pointer to pointer
UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + field->mOffset));
for (int i = param_count_excluding_rvalue - 2;i && *aDeepPointer;i--)
aDeepPointer = (UINT_PTR*)*aDeepPointer;
aResultToken.value_int64 = (__int64)aDeepPointer;
}
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
else // clone field to object and invoke again
{
if (releaseobj)
objclone->Release();
objclone = CloneField(field,true);
/*
if (!field->mArraySize && field->mIsPointer)
{
objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset));
//objclone->mIsPointer--;
if (--objclone->mIsPointer) // it is a pointer to array of pointers, set mArraySize to 1 to identify an array
objclone->mArraySize = 1;
}
else
objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[1])-1)*(field->mIsPointer ? ptrsize : field->mSize));
*/
objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + field->mOffset);
objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1);
objclone->Release();
if (deletefield) // we created the field from a structure
delete field;
return OK;
}
} // MULTIPARAM[x,y] x[y]
// SET
else if (IS_INVOKE_SET)
{
if (field->mVarRef && TokenToObject(*aParam[1]))
{ // field is a structure, assign objct to structure
if (releaseobj)
objclone->Release();
objclone = this->CloneField(field,true);
objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + field->mOffset);
objclone->ObjectToStruct(TokenToObject(*aParam[1]));
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = objclone;
return OK;
}
if (mIsPointer && objclone == NULL)
{ // resolve pointer
for (int i = mIsPointer;i;i--)
target = (UINT_PTR*)*target;
}
else if (objclone && objclone->mIsPointer)
{ // resolve pointer for objclone
for (int i = objclone->mIsPointer;i;i--)
target = (UINT_PTR*)*target;
}
if (field->mIsPointer)
{ // field is a pointer, clone to structure and invoke again
if (releaseobj)
objclone->Release();
objclone = this->CloneField(field,true);
objclone->mIsPointer--;
objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset));
objclone->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount);
objclone->Release();
return OK;
}
// StrPut (code stolen from BIF_StrPut())
if (field->mEncoding != 65535)
{ // field is [T|W|U]CHAR or LP[TC]STR, set get character or string
source_string = (LPCVOID)TokenToString(*aParam[1], aResultToken.buf);
source_length = (int)((aParam[1]->symbol == SYM_VAR) ? aParam[1]->var->CharLength() : _tcslen((LPCTSTR)source_string));
if (!source_length)
{ // Take a shortcut when source_string is empty, since some paths below might not handle it correctly.
if (field->mSize > 2 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset))) // no memory allocated, don't allocate just return
{
aResultToken.value_int64 = 0;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (field->mEncoding == CP_UTF16)
*(LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)) = '\0';
else
*(LPSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)) = '\0';
aResultToken.value_int64 = 1;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return g_script.ScriptError(ERR_MUST_INIT_STRUCT);
}
if (field->mSize > 2) // not [T|W|U]CHAR
source_length++; // for terminating character
if (field->mSize > 2 && (!target || !*((UINT_PTR*)((UINT_PTR)target + field->mOffset)) || (field->mMemAllocated > 0 && (field->mMemAllocated < ((source_length + 1) * (int)(field->mEncoding == 1200 ? sizeof(WCHAR) : sizeof(CHAR)))))))
{ // no memory allocated yet, allocate now
if (field->mMemAllocated == -1 && (!target || !*((UINT_PTR*)((UINT_PTR)target + field->mOffset)))){
if (deletefield) // we created the field from a structure so no memory can be allocated
delete field;
if (releaseobj)
objclone->Release();
return g_script.ScriptError(ERR_MUST_INIT_STRUCT);
}
else if (field->mMemAllocated > 0) // free previously allocated memory
free(field->mStructMem);
field->mMemAllocated = (source_length + 1) * (field->mEncoding == 1200 ? sizeof(WCHAR) : sizeof(CHAR)); // + 1 for terminating character
field->mStructMem = (UINT_PTR*)malloc(field->mMemAllocated);
*((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)field->mStructMem;
}
if (field->mEncoding == UorA(CP_UTF16, CP_ACP))
tmemcpy((LPTSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), (LPTSTR)source_string, field->mSize < 4 ? 1 : source_length);
else
{
// Conversion is required. For Unicode builds, this means encoding != CP_UTF16;
#ifndef UNICODE // therefore, this section is relevant only to ANSI builds:
if (field->mEncoding == CP_UTF16)
{
// See similar section below for comments.
char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, NULL, 0);
if (!char_count)
{
aResultToken.value_int64 = char_count;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (field->mSize > 2) // Not TCHAR or CHAR or WCHAR
++char_count; // + 1 for null-terminator (source_length causes it to be excluded from char_count).
length = char_count;
char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, (LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length);
if (field->mSize > 2 && char_count && char_count < length)
((LPWSTR)*(UINT_PTR*)((UINT_PTR)target + field->mOffset))[char_count] = '\0';
}
else // encoding != CP_UTF16
{
// Convert native ANSI string to UTF-16 first.
CStringWCharFromChar wide_buf((LPCSTR)source_string, source_length, CP_ACP);
source_string = wide_buf.GetString();
source_length = wide_buf.GetLength();
#endif
char_count = WideCharToMultiByte(field->mEncoding, WC_NO_BEST_FIT_CHARS, (LPCWSTR)source_string, source_length, NULL, 0, NULL, NULL);
if (!char_count) // Above has ensured source is not empty, so this must be an error.
{
if (GetLastError() == ERROR_INVALID_FLAGS)
{
// Try again without flags. MSDN lists a number of code pages for which flags must be 0, including UTF-7 and UTF-8 (but UTF-8 is handled above).
flags = 0; // Must be set for this call and the call further below.
char_count = WideCharToMultiByte(field->mEncoding, flags, (LPCWSTR)source_string, source_length, NULL, 0, NULL, NULL);
}
if (!char_count)
{
aResultToken.symbol = SYM_STRING;
aResultToken.marker = _T("");
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
}
// Assume there is sufficient buffer space and hope for the best:
length = char_count;
// Convert to target encoding.
char_count = WideCharToMultiByte(field->mEncoding, flags, (LPCWSTR)source_string, source_length, (LPSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), char_count, NULL, NULL);
// Since above did not null-terminate, check for buffer space and null-terminate if there's room.
// It is tempting to always null-terminate (potentially replacing the last byte of data),
// but that would exclude this function as a means to copy a string into a fixed-length array.
if (field->mSize > 2 && char_count && char_count < length) // NOT TCHAR or CHAR or WCHAR
((LPSTR)*(UINT_PTR*)((UINT_PTR)target + field->mOffset))[char_count] = '\0';
#ifndef UNICODE
}
#endif
}
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = char_count;
}
else // NumPut
{ // code stolen from BIF_NumPut
switch(field->mSize)
{
case 4: // Listed first for performance.
if (field->mIsInteger)
{
*((unsigned int *)((UINT_PTR)target + field->mOffset)) = (unsigned int)TokenToInt64(*aParam[1]);
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = *((unsigned int *)((UINT_PTR)target + field->mOffset));
}
else // Float (32-bit).
{
*((float *)((UINT_PTR)target + field->mOffset)) = (float)TokenToDouble(*aParam[1]);
aResultToken.symbol = SYM_FLOAT;
aResultToken.value_double = *((float *)((UINT_PTR)target + field->mOffset));
}
break;
case 8:
if (field->mIsInteger)
{
// v1.0.48: Support unsigned 64-bit integers like DllCall does:
*((__int64 *)((UINT_PTR)target + field->mOffset)) = (field->mIsUnsigned && !IS_NUMERIC(aParam[1]->symbol)) // Must not be numeric because those are already signed values, so should be written out as signed so that whoever uses them can interpret negatives as large unsigned values.
? (__int64)ATOU64(TokenToString(*aParam[1])) // For comments, search for ATOU64 in BIF_DllCall().
: TokenToInt64(*aParam[1]);
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = TokenToInt64(*aParam[1]);
}
else // Double (64-bit).
{
*((double *)((UINT_PTR)target + field->mOffset)) = TokenToDouble(*aParam[1]);
aResultToken.symbol = SYM_FLOAT;
aResultToken.value_double = *((double *)((UINT_PTR)target + field->mOffset));
}
break;
case 2:
*((unsigned short *)((UINT_PTR)target + field->mOffset)) = (unsigned short)TokenToInt64(*aParam[1]);
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = *((unsigned short *)((UINT_PTR)target + field->mOffset));
break;
default: // size 1
*((unsigned char *)((UINT_PTR)target + field->mOffset)) = (unsigned char)TokenToInt64(*aParam[1]);
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = *((unsigned char *)((UINT_PTR)target + field->mOffset));
}
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
// GET
else if (field)
{
if (field->mArraySize || field->mVarRef)
{ // filed is an array or variable reference, return a structure object.
if (field->mArraySize || field->mIsPointer)
{ // field is array or a pointer to variable
objclone = CloneField(field,true);
objclone->mStructMem = (UINT_PTR *)((UINT_PTR)target + field->mOffset);
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = objclone;
}
else // field is refference to a variable and not pointer, create structure
{
Var1.symbol = SYM_STRING;
Var2.symbol = SYM_VAR;
Var2.var = field->mVarRef;
if (TokenToObject(Var2))
{ // Variable is a structure object
objclone = ((Struct *)TokenToObject(Var2))->Clone(true);
objclone->mStructMem = (UINT_PTR *)((UINT_PTR)target + (UINT_PTR)field->mOffset);
aResultToken.object = objclone;
aResultToken.symbol = SYM_OBJECT;
}
else // Variable is a string definition
{
Var1.marker = TokenToString(Var2);
Var2.symbol = SYM_INTEGER;
Var2.value_int64 = field->mIsPointer ? *(UINT_PTR*)((UINT_PTR)target + field->mOffset) : (UINT_PTR)((UINT_PTR)target + field->mOffset);
if (objclone = Struct::Create(param,2))
{ // create and clone object because it is created dynamically
Struct *tempobj = objclone;
objclone = objclone->Clone(true);
objclone->mStructMem = tempobj->mStructMem;
tempobj->Release();
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = objclone;
}
}
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (mIsPointer && objclone == NULL)
{ // resolve pointer of main structure
for (int i = mIsPointer;i;i--)
target = (UINT_PTR*)*target;
}
else if (objclone && objclone->mIsPointer)
{ // resolve pointer for objclone
for (int i = objclone->mIsPointer;i;i--)
target = (UINT_PTR*)*target;
}
if (field->mIsPointer)
{ // field is a pointer we need to return an object
if (releaseobj)
objclone->Release();
objclone = this->CloneField(field,true);
- objclone->mIsPointer--;
- objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset));
+ objclone->mStructMem = (UINT_PTR*)((UINT_PTR*)((UINT_PTR)target + field->mOffset));
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = objclone;
return OK;
}
// StrGet (code stolen from BIF_StrGet())
if (field->mEncoding != 65535)
{
if (field->mEncoding != UorA(CP_UTF16, CP_ACP))
{
// Conversion is required.
int conv_length;
if (field->mSize < 4) // TCHAR or CHAR or WCHAR
length = 1;
#ifdef UNICODE
// Convert multi-byte encoded string to UTF-16.
conv_length = MultiByteToWideChar(field->mEncoding, 0, (LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, NULL, 0);
if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator.
{
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
conv_length = MultiByteToWideChar(field->mEncoding, 0, (LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, aResultToken.marker, conv_length);
#else
CStringW wide_buf;
// If the target string is not UTF-16, convert it to that first.
if (field->mEncoding != CP_UTF16)
{
StringCharToWChar((LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), wide_buf, length, field->mEncoding);
(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : *(UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)wide_buf.GetString();
length = wide_buf.GetLength();
}
// Now convert UTF-16 to ACP.
conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, NULL, 0, NULL, NULL);
if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator.
{
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK; // Out of memory.
}
conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, aResultToken.marker, conv_length, NULL, NULL);
#endif
if (conv_length && !aResultToken.marker[conv_length - 1])
--conv_length; // Exclude null-terminator.
else
aResultToken.marker[conv_length] = '\0';
aResultToken.marker_length = conv_length; // Update this in case TokenSetResult used mem_to_free.
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
else // no conversation required
{
if (field->mSize > 2 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset)))
{
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
aResultToken.symbol = SYM_STRING;
if (!TokenSetResult(aResultToken, (LPCTSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)),field->mSize < 4 ? 1 : -1))
aResultToken.marker = _T("");
}
aResultToken.symbol = SYM_STRING;
}
else // NumGet (code stolen from BIF_NumGet())
{
switch(field->mSize)
{
case 4: // Listed first for performance.
if (!field->mIsInteger)
{
aResultToken.value_double = *((float *)((UINT_PTR)target + field->mOffset));
aResultToken.symbol = SYM_FLOAT;
}
else if (!field->mIsUnsigned)
{
aResultToken.value_int64 = *((int *)((UINT_PTR)target + field->mOffset)); // aResultToken.symbol was set to SYM_FLOAT or SYM_INTEGER higher above.
aResultToken.symbol = SYM_INTEGER;
}
else
{
aResultToken.value_int64 = *((unsigned int *)((UINT_PTR)target + field->mOffset));
aResultToken.symbol = SYM_INTEGER;
}
break;
case 8:
// The below correctly copies both DOUBLE and INT64 into the union.
// Unsigned 64-bit integers aren't supported because variables/expressions can't support them.
aResultToken.value_int64 = *((__int64 *)((UINT_PTR)target + field->mOffset));
if (!field->mIsInteger)
aResultToken.symbol = SYM_FLOAT;
else
aResultToken.symbol = SYM_INTEGER;
break;
case 2:
if (!field->mIsUnsigned) // Don't use ternary because that messes up type-casting.
aResultToken.value_int64 = *((short *)((UINT_PTR)target + field->mOffset));
else
aResultToken.value_int64 = *((unsigned short *)((UINT_PTR)target + field->mOffset));
aResultToken.symbol = SYM_INTEGER;
break;
default: // size 1
if (!field->mIsUnsigned) // Don't use ternary because that messes up type-casting.
aResultToken.value_int64 = *((char *)((UINT_PTR)target + field->mOffset));
else
aResultToken.value_int64 = *((unsigned char *)((UINT_PTR)target + field->mOffset));
aResultToken.symbol = SYM_INTEGER;
}
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (releaseobj)
objclone->Release();
return INVOKE_NOT_HANDLED;
}
//
// Struct:: Internal Methods
//
Struct::FieldType *Struct::FindField(LPTSTR val)
{
for (int i = 0;i < mFieldCount;i++)
{
FieldType &field = mFields[i];
if (!_tcsicmp(field.key,val))
return &field;
}
return NULL;
}
bool Struct::SetInternalCapacity(IndexType new_capacity)
// Expands mFields to the specified number if fields.
// Caller *must* ensure new_capacity >= 1 && new_capacity >= mFieldCount.
{
FieldType *new_fields = (FieldType *)realloc(mFields, new_capacity * sizeof(FieldType));
if (!new_fields)
return false;
mFields = new_fields;
mFieldCountMax = new_capacity;
return true;
}
ResultType Struct::_NewEnum(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount)
{
if (aParamCount == 0)
{
IObject *newenum;
if (newenum = new Enumerator(this))
{
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = newenum;
}
}
return OK;
}
int Struct::Enumerator::Next(Var *aKey, Var *aVal)
{
if (++mOffset < mObject->mFieldCount)
{
FieldType &field = mObject->mFields[mOffset];
if (aKey)
aKey->Assign(field.key);
if (aVal)
{ // We need to invoke the structure to retrieve the value
ExprTokenType aResultToken;
// not sure about the buffer
TCHAR buf[MAX_PATH];
aResultToken.buf = buf;
ExprTokenType aThisToken;
aThisToken.symbol = SYM_OBJECT;
aThisToken.object = mObject;
ExprTokenType *aVarToken = new ExprTokenType();
aVarToken->symbol = SYM_STRING;
aVarToken->marker = field.key;
mObject->Invoke(aResultToken,aThisToken,0,&aVarToken,1);
switch (aResultToken.symbol)
{
case SYM_STRING: aVal->AssignString(aResultToken.marker); break;
case SYM_INTEGER: aVal->Assign(aResultToken.value_int64); break;
case SYM_FLOAT: aVal->Assign(aResultToken.value_double); break;
case SYM_OBJECT: aVal->Assign(aResultToken.object); break;
}
delete aVarToken;
}
return true;
}
else if (mOffset < mObject->mArraySize)
{ // structure is an array
if (aKey)
aKey->Assign(mOffset + 1); // mOffset starts at 1
if (aVal)
{ // again we need to invoke structure to retrieve the value
ExprTokenType aResultToken;
TCHAR buf[MAX_PATH];
aResultToken.buf = buf;
ExprTokenType aThisToken;
aThisToken.symbol = SYM_OBJECT;
aThisToken.object = mObject;
ExprTokenType *aVarToken = new ExprTokenType();
aVarToken->symbol = SYM_INTEGER;
aVarToken->value_int64 = mOffset + 1; // mOffset starts at 1
mObject->Invoke(aResultToken,aThisToken,0,&aVarToken,1);
switch (aResultToken.symbol)
{
case SYM_STRING: aVal->AssignString(aResultToken.marker); break;
case SYM_INTEGER: aVal->Assign(aResultToken.value_int64); break;
case SYM_FLOAT: aVal->Assign(aResultToken.value_double); break;
case SYM_OBJECT: aVal->Assign(aResultToken.object); break;
}
delete aVarToken;
}
return true;
}
return false;
}
Struct::FieldType *Struct::Insert(LPTSTR key, IndexType at,UCHAR aIspointer,int aOffset,int aArrsize,Var *variableref,int aFieldsize,bool aIsinteger,bool aIsunsigned,USHORT aEncoding)
// Inserts a single field with the given key at the given offset.
// Caller must ensure 'at' is the correct offset for this key.
{
if (!*key)
{
// empty key = only type was given so assign all to structure object
// do not assign size here since it will be assigned in StructCreate later
mArraySize = aArrsize;
mIsPointer = aIspointer;
mIsInteger = aIsinteger;
mIsUnsigned = aIsunsigned;
mEncoding = aEncoding;
mVarRef = variableref;
return (FieldType*)true;
}
if (mFieldCount == mFieldCountMax && !Expand() // Attempt to expand if at capacity.
|| !(key = _tcsdup(key))) // Attempt to duplicate key-string.
{ // Out of memory.
return NULL;
}
// There is now definitely room in mFields for a new field.
FieldType &field = mFields[at];
if (at < mFieldCount)
// Move existing fields to make room.
memmove(&field + 1, &field, (mFieldCount - at) * sizeof(FieldType));
++mFieldCount; // Only after memmove above.
// Update key-type offsets based on where and what was inserted; also update this key's ref count:
field.mSize = aFieldsize; // Init to ensure safe behaviour in Assign().
field.key = key; // Above has already copied string
field.mArraySize = aArrsize;
field.mIsPointer = aIspointer;
field.mOffset = aOffset;
field.mIsInteger = aIsinteger;
field.mIsUnsigned = aIsunsigned;
field.mEncoding = aEncoding;
field.mVarRef = variableref;
field.mMemAllocated = 0;
return &field;
}
|
tinku99/ahkdll
|
1487538246ac0b0a774d8b5c9ce89f28be5b7b20
|
Small WinApi fix
|
diff --git a/source/resources/WINAPI.zip b/source/resources/WINAPI.zip
index b4cea80..6151cff 100644
Binary files a/source/resources/WINAPI.zip and b/source/resources/WINAPI.zip differ
diff --git a/source/script.cpp b/source/script.cpp
index 2ef99e9..9e89ab3 100644
--- a/source/script.cpp
+++ b/source/script.cpp
@@ -9615,1025 +9615,1025 @@ ResultType Script::DefineClassVars(LPTSTR aBuf, bool aStatic)
{
*item_end = orig_char; // Undo termination.
// This is something like "object.key := 5", which is only valid if "object" was
// previously declared (and will presumably be assigned an object at runtime).
// Ensure that at least the root class var exists; any further validation would
// be impossible since the object doesn't exist yet.
if (!item_exists)
return ScriptError(_T("Unknown class var."), item);
for (TCHAR *cp; *item_end == '.'; item_end = cp)
{
for (cp = item_end + 1; cisalnum(*cp) || *cp == '_'; ++cp);
if (cp == item_end + 1)
// This '.' wasn't followed by a valid identifier. Leave item_end
// pointing at '.' and allow the switch() below to report the error.
break;
}
}
else
{
if (item_exists)
return ScriptError(ERR_DUPLICATE_DECLARATION, item);
// Assign class_object[item] := "" to mark it as a class variable
// and allow duplicate declarations to be detected:
if (!class_object->SetItem(item, aStatic ? empty_token : int_token))
return ScriptError(ERR_OUTOFMEM);
*item_end = orig_char; // Undo termination.
}
size_t name_length = item_end - item;
// This section is very similar to the one in ParseAndAddLine() which deals with
// variable declarations, so maybe maintain them together:
item_end = omit_leading_whitespace(item_end); // Move up to the next comma, assignment-op, or '\0'.
switch (*item_end)
{
case ',': // No initializer is present for this variable, so move on to the next one.
item = omit_leading_whitespace(item_end + 1); // Set "item" for use by the next iteration.
continue; // No further processing needed below.
case '\0': // No initializer is present for this variable, so move on to the next one.
item = item_end; // Set "item" for use by the loop's condition.
continue;
case '=': // Supported for consistency with v1 syntax; to be removed in v2.
++item_end; // Point to the character after the "=".
break;
case ':':
if (item_end[1] == '=')
{
item_end += 2; // Point to the character after the ":=".
break;
}
// Otherwise, fall through to below:
default:
return ScriptError(ERR_INVALID_CLASS_VAR, item);
}
// Since above didn't "continue", this declared variable also has an initializer.
// Append the class name, ":=" and initializer to pending_buf, to be turned into
// an expression below, and executed at script start-up.
item_end = omit_leading_whitespace(item_end);
LPTSTR right_side_of_operator = item_end; // Save for use below.
item_end += FindNextDelimiter(item_end); // Find the next comma which is not part of the initializer (or find end of string).
// Append "ClassNameOrThis.VarName := Initializer, " to the buffer.
int chars_written = _sntprintf(buf + buf_used, _countof(buf) - buf_used, _T("%s.%.*s := %.*s, ")
, aStatic ? mClassName : _T("this"), name_length, item, item_end - right_side_of_operator, right_side_of_operator);
if (chars_written < 0)
return ScriptError(_T("Declaration too long.")); // Short message since should be rare.
buf_used += chars_written;
// Set "item" for use by the next iteration:
item = (*item_end == ',') // i.e. it's not the terminator and thus not the final item in the list.
? omit_leading_whitespace(item_end + 1)
: item_end; // It's the terminator, so let the loop detect that to finish.
}
if (buf_used)
{
// Above wrote at least one initializer expression into buf.
buf[buf_used -= 2] = '\0'; // Remove the final ", "
// The following section temporarily replaces mLastLine in order to insert script lines
// either at the end of the list of static initializers (separate from the main script)
// or at the end of the __Init method belonging to this class. Save the current values:
Line *script_first_line = mFirstLine, *script_last_line = mLastLine;
Line *block_end;
Func *init_func = NULL;
if (aStatic)
{
mLastLine = mLastStaticLine;
mFirstLine = mFirstStaticLine;
}
else
{
ExprTokenType token;
if (class_object->GetItem(token, _T("__Init")) && token.symbol == SYM_OBJECT
&& (init_func = dynamic_cast<Func *>(token.object))) // This cast SHOULD always succeed; done for maintainability.
{
// __Init method already exists, so find the end of its body.
for (block_end = init_func->mJumpToLine;
block_end->mActionType != ACT_BLOCK_END || !block_end->mAttribute;
block_end = block_end->mNextLine);
}
else
{
// Create an __Init method for this class.
TCHAR def[] = _T("__Init()");
if (!DefineFunc(def, NULL) || !AddLine(ACT_BLOCK_BEGIN)
|| (class_object->Base() && !ParseAndAddLine(_T("base.__Init()"), ACT_EXPRESSION))) // Initialize base-class variables first. Relies on short-circuit evaluation.
return FAIL;
mLastLine->mLineNumber = 0; // Signal the debugger to skip this line while stepping in/over/out.
init_func = g->CurrentFunc;
init_func->mDefaultVarType = VAR_DECLARE_GLOBAL; // Allow global variables/class names in initializer expressions.
if (!AddLine(ACT_BLOCK_END)) // This also resets g->CurrentFunc to NULL.
return FAIL;
block_end = mLastLine;
block_end->mLineNumber = 0; // See above.
// These must be updated as one or both have changed:
script_first_line = mFirstLine;
script_last_line = mLastLine;
}
g->CurrentFunc = init_func; // g->CurrentFunc should be NULL prior to this.
mLastLine = block_end->mPrevLine; // i.e. insert before block_end.
mLastLine->mNextLine = NULL; // For maintainability; AddLine() should overwrite it regardless.
mCurrLine = NULL; // Fix for v1.1.09.02: Leaving this non-NULL at best causes error messages to show irrelevant vicinity lines, and at worst causes a crash because the linked list is in an inconsistent state.
}
if (!ParseAndAddLine(buf, ACT_EXPRESSION))
return FAIL; // Above already displayed the error.
if (aStatic)
{
if (!mFirstStaticLine)
mFirstStaticLine = mLastLine;
mLastStaticLine = mLastLine;
// The following is necessary if there weren't any executable lines above this static
// initializer (i.e. mFirstLine was NULL and has been set to the newly created line):
mFirstLine = script_first_line;
}
else
{
if (init_func->mJumpToLine == block_end) // This can be true only for the first initializer of a class with no base-class.
init_func->mJumpToLine = mLastLine;
// Rejoin the function's block-end (and any lines following it) to the main script.
mLastLine->mNextLine = block_end;
block_end->mPrevLine = mLastLine;
// mFirstLine should be left as it is: if it was NULL, it now contains a pointer to our
// __init function's block-begin, which is now the very first executable line in the script.
g->CurrentFunc = NULL;
}
// Restore mLastLine so that any subsequent script lines are added at the correct point.
mLastLine = script_last_line;
}
return OK;
}
Object *Script::FindClass(LPCTSTR aClassName, size_t aClassNameLength)
{
if (!aClassNameLength)
aClassNameLength = _tcslen(aClassName);
if (!aClassNameLength || aClassNameLength > MAX_CLASS_NAME_LENGTH)
return NULL;
LPTSTR cp, key;
ExprTokenType token;
Object *base_object = NULL;
TCHAR class_name[MAX_CLASS_NAME_LENGTH + 2]; // Extra +1 for '.' to simplify parsing.
// Make temporary copy which we can modify.
tmemcpy(class_name, aClassName, aClassNameLength);
class_name[aClassNameLength] = '.'; // To simplify parsing.
class_name[aClassNameLength + 1] = '\0';
// Get base variable; e.g. "MyClass" in "MyClass.MySubClass".
cp = _tcschr(class_name + 1, '.');
Var *base_var = FindVar(class_name, cp - class_name, NULL, FINDVAR_GLOBAL);
if (!base_var)
return NULL;
// Although at load time only the "Object" type can exist, dynamic_cast is used in case we're called at run-time:
if ( !(base_var->IsObject() && (base_object = dynamic_cast<Object *>(base_var->Object()))) )
return NULL;
// Even if the loop below has no iterations, it initializes 'key' to the appropriate value:
for (key = cp + 1; cp = _tcschr(key, '.'); key = cp + 1) // For each key in something like TypeVar.Key1.Key2.
{
if (cp == key)
return NULL; // ScriptError(_T("Missing name."), cp);
*cp = '\0'; // Terminate at the delimiting dot.
if (!base_object->GetItem(token, key))
return NULL;
base_object = (Object *)token.object; // See comment about Object() above.
}
return base_object;
}
Object *Object::GetUnresolvedClass(LPTSTR &aName)
// This method is only valid for mUnresolvedClass.
{
if (!mFieldCount)
return NULL;
aName = mFields[0].key.s;
return (Object *)mFields[0].object;
}
ResultType Script::ResolveClasses()
{
LPTSTR name;
Object *base = mUnresolvedClasses->GetUnresolvedClass(name);
if (!base)
return OK;
// There is at least one unresolved class.
ExprTokenType token;
if (base->GetItem(token, _T("__Class")))
{
// In this case (an object in the mUnresolvedClasses list), it is always an integer
// containing the file index and line number:
mCurrFileIndex = int(token.value_int64 >> 32);
mCombinedLineNumber = LineNumberType(token.value_int64);
}
mCurrLine = NULL;
return ScriptError(_T("Unknown class."), name);
}
#ifndef AUTOHOTKEYSC
struct FuncLibrary
{
LPTSTR path;
DWORD_PTR length;
};
Func *Script::FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool &aErrorWasShown, bool &aFileWasFound, bool aIsAutoInclude)
// Caller must ensure that aFuncName doesn't already exist as a defined function.
// If aFuncNameLength is 0, the entire length of aFuncName is used.
{
aErrorWasShown = false; // Set default for this output parameter.
aFileWasFound = false;
int i;
LPTSTR char_after_last_backslash, terminate_here;
TCHAR buf[MAX_PATH+1];
DWORD attr;
TextMem tmem;
TextMem::Buffer textbuf(NULL, 0, false);
#define FUNC_LIB_EXT _T(".ahk")
#define FUNC_LIB_EXT_LENGTH (_countof(FUNC_LIB_EXT) - 1)
#define FUNC_LOCAL_LIB _T("\\Lib\\") // Needs leading and trailing backslash.
#define FUNC_LOCAL_LIB_LENGTH (_countof(FUNC_LOCAL_LIB) - 1)
#define FUNC_USER_LIB _T("\\AutoHotkey\\Lib\\") // Needs leading and trailing backslash.
#define FUNC_USER_LIB_LENGTH (_countof(FUNC_USER_LIB) - 1)
#define FUNC_STD_LIB _T("Lib\\") // Needs trailing but not leading backslash.
#define FUNC_STD_LIB_LENGTH (_countof(FUNC_STD_LIB) - 1)
#define FUNC_LIB_COUNT 4
static FuncLibrary sLib[FUNC_LIB_COUNT] = {0};
static LPTSTR winapi;
if (!sLib[0].path) // Allocate & discover paths only upon first use because many scripts won't use anything from the library. This saves a bit of memory and performance.
{
LPVOID aDataBuf;
HRSRC hResInfo = FindResource(g_hInstance, _T("WINAPI"), MAKEINTRESOURCE(10));
DecompressBuffer(LockResource(LoadResource(g_hInstance, hResInfo)), aDataBuf, g_default_pwd);
#ifdef _UNICODE
winapi = UTF8ToWide((LPCSTR)aDataBuf);
#else
winapi = (LPTSTR)aDataBuf;
#endif
for (i = 0; i < FUNC_LIB_COUNT; ++i)
#ifdef _USRDLL
if ( !(sLib[i].path = tmalloc(MAX_PATH)) ) // When dll script is restarted, SimpleHeap is deleted and we don't want to delete static memberst
#else
if ( !(sLib[i].path = (LPTSTR) SimpleHeap::Malloc(MAX_PATH * sizeof(TCHAR))) ) // Need MAX_PATH for to allow room for appending each candidate file/function name.
#endif
return NULL; // Due to rarity, simply pass the failure back to caller.
FuncLibrary *this_lib;
// DETERMINE PATH TO "LOCAL" LIBRARY:
this_lib = sLib; // For convenience and maintainability.
this_lib->length = BIV_ScriptDir(NULL, _T(""));
if (this_lib->length < MAX_PATH-FUNC_LOCAL_LIB_LENGTH)
{
this_lib->length = BIV_ScriptDir(this_lib->path, _T(""));
_tcscpy(this_lib->path + this_lib->length, FUNC_LOCAL_LIB);
this_lib->length += FUNC_LOCAL_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "USER" LIBRARY:
this_lib++; // For convenience and maintainability.
this_lib->length = BIV_MyDocuments(this_lib->path, _T(""));
if (this_lib->length < MAX_PATH-FUNC_USER_LIB_LENGTH)
{
_tcscpy(this_lib->path + this_lib->length, FUNC_USER_LIB);
this_lib->length += FUNC_USER_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "STANDARD" LIBRARY:
this_lib++; // For convenience and maintainability.
GetModuleFileName(NULL, this_lib->path, MAX_PATH); // The full path to the currently-running AutoHotkey.exe.
char_after_last_backslash = 1 + _tcsrchr(this_lib->path, '\\'); // Should always be found, so failure isn't checked.
this_lib->length = (DWORD)(char_after_last_backslash - this_lib->path); // The length up to and including the last backslash.
if (this_lib->length < MAX_PATH-FUNC_STD_LIB_LENGTH)
{
_tcscpy(this_lib->path + this_lib->length, FUNC_STD_LIB);
this_lib->length += FUNC_STD_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "AHKPATH\Lib.lnk" LIBRARY:
this_lib++; // For convenience and maintainability.
BIV_AhkPath(this_lib->path, _T(""));
_tcscpy(_tcsrchr(this_lib->path,'\\')+1,_T("Lib.lnk"));
*(_tcsrchr(this_lib->path,'\\')+8) = '\0';
CoInitialize(NULL);
IShellLink *psl;
if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *)&psl)))
{
IPersistFile *ppf;
if (SUCCEEDED(psl->QueryInterface(IID_IPersistFile, (LPVOID *)&ppf)))
{
#ifdef UNICODE
if (SUCCEEDED(ppf->Load(this_lib->path, 0)))
#else
WCHAR wsz[MAX_PATH+1]; // +1 hasn't been explained, but is retained in case it's needed.
ToWideChar(this_lib->path, wsz, MAX_PATH+1); // Dest. size is in wchars, not bytes.
if (SUCCEEDED(ppf->Load((const WCHAR*)wsz, 0)))
#endif
{
TCHAR buf[MAX_PATH+1];
psl->GetPath(buf, MAX_PATH, NULL, SLGP_UNCPRIORITY);
_tcscpy(this_lib->path,buf);
_tcscpy(this_lib->path + _tcslen(buf),_T("\\\0"));
}
ppf->Release();
}
psl->Release();
}
CoUninitialize();
if ( !_tcsrchr(FileAttribToStr(buf, GetFileAttributes(this_lib->path)),'D') )
{
this_lib->length = 0;
*this_lib->path = '\0';
}
else
this_lib->length = _tcslen(this_lib->path);
for (i = 0; i < FUNC_LIB_COUNT; ++i)
{
attr = GetFileAttributes(sLib[i].path); // Seems to accept directories that have a trailing backslash, which is good because it simplifies the code.
if (attr == 0xFFFFFFFF || !(attr & FILE_ATTRIBUTE_DIRECTORY)) // Directory doesn't exist or it's a file vs. directory. Relies on short-circuit boolean order.
{
*sLib[i].path = '\0'; // Mark this library as disabled.
sLib[i].length = 0; //
}
}
}
// Above must ensure that all sLib[].path elements are non-NULL (but they can be "" to indicate "no library").
if (!aFuncNameLength) // Caller didn't specify, so use the entire string.
aFuncNameLength = _tcslen(aFuncName);
TCHAR *dest, *first_underscore, class_name_buf[MAX_VAR_NAME_LENGTH + 1];
LPTSTR naked_filename = aFuncName; // Set up for the first iteration.
size_t naked_filename_length = aFuncNameLength; //
for (int second_iteration = 0; second_iteration < 2; ++second_iteration)
{
for (i = 0; i < FUNC_LIB_COUNT; ++i)
{
if (!*sLib[i].path) // Library is marked disabled, so skip it.
continue;
if (sLib[i].length + naked_filename_length >= MAX_PATH-FUNC_LIB_EXT_LENGTH)
continue; // Path too long to match in this library, but try others.
dest = (LPTSTR) tmemcpy(sLib[i].path + sLib[i].length, naked_filename, naked_filename_length); // Append the filename to the library path.
_tcscpy(dest + naked_filename_length, FUNC_LIB_EXT); // Append the file extension.
attr = GetFileAttributes(sLib[i].path); // Testing confirms that GetFileAttributes() doesn't support wildcards; which is good because we want filenames containing question marks to be "not found" rather than being treated as a match-pattern.
if (attr == 0xFFFFFFFF || (attr & FILE_ATTRIBUTE_DIRECTORY)) // File doesn't exist or it's a directory. Relies on short-circuit boolean order.
continue;
aFileWasFound = true; // Indicate success for #include <lib>, which doesn't necessarily expect a function to be found.
// Since above didn't "continue", a file exists whose name matches that of the requested function.
// Before loading/including that file, set the working directory to its folder so that if it uses
// #Include, it will be able to use more convenient/intuitive relative paths. This is similar to
// the "#Include DirName" feature.
// Call SetWorkingDir() vs. SetCurrentDirectory() so that it succeeds even for a root drive like
// C: that lacks a backslash (see SetWorkingDir() for details).
terminate_here = sLib[i].path + sLib[i].length - 1; // The trailing backslash in the full-path-name to this library.
*terminate_here = '\0'; // Temporarily terminate it for use with SetWorkingDir().
SetWorkingDir(sLib[i].path); // See similar section in the #Include directive.
*terminate_here = '\\'; // Undo the termination.
if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude)
{
// For each auto-included library-file, write out two #Include lines:
// 1) Use #Include in its "change working directory" mode so that any explicit #include directives
// or FileInstalls inside the library file itself will work consistently and properly.
// 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include
// the library file itself.
// We don't directly append library files onto the main script here because:
// 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files
// might contain #Include even though it's rare).
// 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or
// subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they
// wouldn't be properly interleaved/asynchronous, but instead brought out of their library file
// and deposited separately/synchronously into the temp-include file by some new logic at the
// AutoHotkey.exe's code for the #Include directive.
// 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts.
mIncludeLibraryFunctionsThenExit->Format(_T("#Include %-0.*s\n#IncludeAgain %s\n")
, sLib[i].length, sLib[i].path, sLib[i].path);
// Now continue on normally so that our caller can continue looking for syntax errors.
}
// g->CurrentFunc is non-NULL when the function-call being resolved is inside
// a function. Save and reset it for correct behaviour in the include file:
Func *current_func = g->CurrentFunc;
g->CurrentFunc = NULL;
// Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the
// above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written.
if (!LoadIncludedFile(sLib[i].path, false, false)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included).
{
g->CurrentFunc = current_func; // Restore.
aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier.
return NULL;
}
g->CurrentFunc = current_func; // Restore.
// Now that a matching filename has been found, it seems best to stop searching here even if that
// file doesn't actually contain the requested function. This helps library authors catch bugs/typos.
// HotKeyIt, override so resource can be tried too
if (current_func = FindFunc(aFuncName, aFuncNameLength))
return current_func;
continue;
} // for() each library directory.
// Now that the first iteration is done, set up for the second one that searches by class/prefix.
// Notes about ambiguity and naming collisions:
// By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a
// match in a filename that isn't really a class, it seems inconsequential because at worst it will
// still not find the function and will then say "call to nonexistent function". In addition, the
// ability to customize which libraries are searched is planned. This would allow a publicly
// distributed script to turn off all libraries except stdlib.
if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed.
break; // All loops are done because second iteration is the last possible attempt.
naked_filename_length = first_underscore - aFuncName;
if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently).
break; // All loops are done because second iteration is the last possible attempt.
naked_filename = class_name_buf; // Point it to a buffer for use below.
tmemcpy(naked_filename, aFuncName, naked_filename_length);
naked_filename[naked_filename_length] = '\0';
} // 2-iteration for().
// HotKeyIt find library in Resource
// Since above didn't return, no match found in any library.
// Search in Resource for a library
//
// If using dll, first try find function in dll resource, then function + underscore (function_) in dll resource
// If nothing in dll resource is found, search again in main executable.
tmemcpy(class_name_buf, aFuncName, aFuncNameLength);
tmemcpy(class_name_buf + aFuncNameLength,_T(".ahk"),4);
class_name_buf[aFuncNameLength + 4] = '\0';
HRSRC lib_hResource;
BOOL aUseHinstance = true;
if (!(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB"))))
{
// Now that the resource is not found, set up for the second one that searches by class/prefix.
// Notes about ambiguity and naming collisions:
// By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a
// match in a filename that isn't really a class, it seems inconsequential because at worst it will
// still not find the function and will then say "call to nonexistent function". In addition, the
// ability to customize which libraries are searched is planned. This would allow a publicly
// distributed script to turn off all libraries except stdlib.
aUseHinstance = false;
if ( !(lib_hResource = FindResource(NULL, class_name_buf, _T("LIB"))) )
{
if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed.
goto winapi;
else
{
naked_filename_length = first_underscore - aFuncName;
if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently).
- return NULL;
+ goto winapi;
tmemcpy(class_name_buf, aFuncName, naked_filename_length);
tmemcpy(class_name_buf + naked_filename_length,_T(".ahk"),4);
class_name_buf[naked_filename_length + 4] = '\0';
if ( !(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB"))) )
{
if ( !(lib_hResource = FindResource(NULL, class_name_buf, _T("LIB"))) )
goto winapi;
}
else
aUseHinstance = true;
}
}
}
// Now a resouce was found and it can be loaded
HGLOBAL hResData;
HINSTANCE ahInstance = aUseHinstance ? g_hInstance : NULL;
if ( !( (textbuf.mLength = SizeofResource(ahInstance, lib_hResource))
&& (hResData = LoadResource(ahInstance, lib_hResource))
&& (textbuf.mBuffer = LockResource(hResData)) ) )
{ // aErrorWasShown = true; // Do not display errors here
goto winapi;
}
if (*(unsigned int*)textbuf.mBuffer == 0x04034b50)
{
LPVOID aDataBuf;
DWORD aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf);
if (aSizeDeCompressed)
{
LPVOID buff = _alloca(aSizeDeCompressed); // will be freed when function returns
memmove(buff,aDataBuf,aSizeDeCompressed);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
textbuf.mLength = aSizeDeCompressed;
textbuf.mBuffer = buff;
}
}
aFileWasFound = true;
// NOTE: Ahk2Exe strips off the UTF-8 BOM.
LPTSTR resource_script = (LPTSTR)_alloca(textbuf.mLength * sizeof(TCHAR));
tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF8);
tmem.Read(resource_script, textbuf.mLength);
// g->CurrentFunc is non-NULL when the function-call being resolved is inside
// a function. Save and reset it for correct behaviour in the include file:
Func *current_func = g->CurrentFunc;
g->CurrentFunc = NULL;
// Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the
// above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written.
if (!LoadIncludedText(resource_script, class_name_buf)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included).
{
g->CurrentFunc = current_func; // Restore.
aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier.
return NULL;
}
g->CurrentFunc = current_func; // Restore.
return FindFunc(aFuncName, aFuncNameLength);
winapi:
TCHAR parameter[1024] = { L'#', L'D', L'l', L'l', L'I', L'm', L'p', L'o', L'r', L't', L'\\' };
memmove(¶meter[11], aFuncName, aFuncNameLength*sizeof(TCHAR));
parameter[aFuncNameLength + 11] = L',';
parameter[aFuncNameLength + 12] = '\0';
LPTSTR found;
if (found = _tcsstr(winapi, (LPTSTR)¶meter[10]))
{
parameter[10] = L',';
LPTSTR aDest = (LPTSTR)¶meter[aFuncNameLength + 12];
LPTSTR aDllName = _tcsstr(found, _T("\t")) + 1;
size_t aNameLen = _tcsstr(aDllName, _T("\\")) - aDllName + 1;
_tcsncpy(aDest, aDllName, aNameLen);
aDest = aDest + aNameLen;
_tcsncpy(aDest, found + 1, aFuncNameLength + 1);
// Override _ in the end of definition (ahk function like SendMessage, Sleep, Send, SendInput ...
if (*(aFuncName + aFuncNameLength - 1) == '_')
{
*(aDest + aFuncNameLength - 1) = ',';
*(aDest + aFuncNameLength) = '\0';
aDest = aDest + aFuncNameLength;
}
else
{
aDest = aDest + aFuncNameLength + 1;
}
for (found = _tcsstr(found, _T(",")) + 1; *found != L'\\'; found++)
{
if (*found == L'U' || *found == L'u')
{
*aDest = L'U';
aDest++;
continue;
}
else if (*found == L'z' || *found == L'Z')
{
#ifdef _UNICODE
_tcscpy(aDest, _T("USHORT"));
aDest = aDest + 6;
#else
_tcscpy(aDest, _T("UCHAR"));
aDest = aDest + 5;
#endif
}
else if (*found == L's' || *found == L'S')
{
_tcscpy(aDest, _T("STR"));
aDest = aDest + 3;
}
else if (*found == L't' || *found == L't')
{
_tcscpy(aDest, _T("PTR"));
aDest = aDest + 3;
}
else if (*found == L'a' || *found == L'A')
{
_tcscpy(aDest, _T("ASTR"));
aDest = aDest + 4;
}
else if (*found == L'w' || *found == L'W')
{
_tcscpy(aDest, _T("WSTR"));
aDest = aDest + 4;
}
else if (*found == L'x' || *found == L'X') //TCHAR
{
#ifdef _UNICODE
_tcscpy(aDest, _T("USHORT"));
aDest = aDest + 6;
#else
_tcscpy(aDest, _T("UCHAR"));
aDest = aDest + 5;
#endif
}
else if ((*found == L'i' || *found == L'I') && *(found + 1) == L'6')
{
_tcscpy(aDest, _T("INT64"));
aDest = aDest + 5;
found++;
}
else if (*found == L'i' || *found == L'I')
{
if (*(found + 1) != L'\\' || *(aDest - 1) == 'u' || *(aDest - 1) == 'U')
{ // Not default return type int, no need to define
_tcscpy(aDest, _T("INT"));
aDest = aDest + 3;
}
else // remove last , since no return type is given
{
aDest--;
}
}
else if (*found == L'h' || *found == L'H')
{
_tcscpy(aDest, _T("SHORT"));
aDest = aDest + 5;
}
else if (*found == L'c' || *found == L'C')
{
_tcscpy(aDest, _T("CHAR"));
aDest = aDest + 4;
}
else if (*found == L'f' || *found == L'F')
{
_tcscpy(aDest, _T("FLOAT"));
aDest = aDest + 5;
}
else if (*found == L'd' || *found == L'D')
{
_tcscpy(aDest, _T("DOUBLE"));
aDest = aDest + 6;
}
if (*(found + 1) == L'*' || *(found + 1) == L'p' || *(found + 1) == L'P')
{
*aDest = *found;
aDest++;
}
_tcscpy(aDest, _T(",,"));
aDest = aDest + 2;
}
*(aDest - 2) = L'\0';
LoadDllFunction(_tcschr(parameter, L',') + 1, parameter);
return FindFunc(aFuncName, aFuncNameLength);
}
return NULL;
}
#endif
Func *Script::FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength, int *apInsertPos) // L27: Added apInsertPos for binary-search.
// Returns the Function whose name matches aFuncName (which caller has ensured isn't NULL).
// If it doesn't exist, NULL is returned.
{
if (!aFuncNameLength) // Caller didn't specify, so use the entire string.
aFuncNameLength = _tcslen(aFuncName);
if (apInsertPos) // L27: Set default for maintainability.
*apInsertPos = -1;
// For the below, no error is reported because callers don't want that. Instead, simply return
// NULL to indicate that names that are illegal or too long are not found. If the caller later
// tries to add the function, it will get an error then:
if (aFuncNameLength > MAX_VAR_NAME_LENGTH)
return NULL;
// The following copy is made because it allows the name searching to use _tcsicmp() instead of
// strlicmp(), which close to doubles the performance. The copy includes only the first aVarNameLength
// characters from aVarName:
TCHAR func_name[MAX_VAR_NAME_LENGTH + 1];
tcslcpy(func_name, aFuncName, aFuncNameLength + 1); // +1 to convert length to size.
Func *pfunc;
// Using a binary searchable array vs a linked list speeds up dynamic function calls, on average.
int left, right, mid, result;
for (left = 0, right = mFuncCount - 1; left <= right;)
{
mid = (left + right) / 2;
result = _tcsicmp(func_name, mFunc[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance.
if (result > 0)
left = mid + 1;
else if (result < 0)
right = mid - 1;
else // Match found.
return mFunc[mid];
}
if (apInsertPos)
*apInsertPos = left;
// Since above didn't return, there is no match. See if it's a built-in function that hasn't yet
// been added to the function list.
// Set defaults to be possibly overridden below:
int min_params = 1;
int max_params = 1;
BuiltInFunctionType bif;
LPTSTR suffix = func_name + 3;
#ifndef MINIDLL
if (!_tcsnicmp(func_name, _T("LV_"), 3)) // As a built-in function, LV_* can only be a ListView function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("GetNext")))
{
bif = BIF_LV_GetNextOrCount;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("GetCount")))
{
bif = BIF_LV_GetNextOrCount;
min_params = 0; // But leave max at its default of 1.
}
else if (!_tcsicmp(suffix, _T("GetText")))
{
bif = BIF_LV_GetText;
min_params = 2;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_LV_AddInsertModify;
min_params = 0; // 0 params means append a blank row.
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Insert")))
{
bif = BIF_LV_AddInsertModify;
// Leave min_params at 1. Passing only 1 param to it means "insert a blank row".
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Modify")))
{
bif = BIF_LV_AddInsertModify; // Although it shares the same function with "Insert", it can still have its own min/max params.
min_params = 2;
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Delete")))
{
bif = BIF_LV_Delete;
min_params = 0; // Leave max at its default of 1.
}
else if (!_tcsicmp(suffix, _T("InsertCol")))
{
bif = BIF_LV_InsertModifyDeleteCol;
// Leave min_params at 1 because inserting a blank column ahead of the first column
// does not seem useful enough to sacrifice the no-parameter mode, which might have
// potential future uses.
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("ModifyCol")))
{
bif = BIF_LV_InsertModifyDeleteCol;
min_params = 0;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("DeleteCol")))
bif = BIF_LV_InsertModifyDeleteCol; // Leave min/max set to 1.
else if (!_tcsicmp(suffix, _T("SetImageList")))
{
bif = BIF_LV_SetImageList;
max_params = 2; // Leave min at 1.
}
else
return NULL;
}
else if (!_tcsnicmp(func_name, _T("TV_"), 3)) // As a built-in function, TV_* can only be a TreeView function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_TV_AddModifyDelete;
max_params = 3; // Leave min at its default of 1.
}
else if (!_tcsicmp(suffix, _T("Modify")))
{
bif = BIF_TV_AddModifyDelete;
max_params = 3; // One-parameter mode is "select specified item".
}
else if (!_tcsicmp(suffix, _T("Delete")))
{
bif = BIF_TV_AddModifyDelete;
min_params = 0;
}
else if (!_tcsicmp(suffix, _T("GetParent")) || !_tcsicmp(suffix, _T("GetChild")) || !_tcsicmp(suffix, _T("GetPrev")))
bif = BIF_TV_GetRelatedItem;
else if (!_tcsicmp(suffix, _T("GetCount")) || !_tcsicmp(suffix, _T("GetSelection")))
{
bif = BIF_TV_GetRelatedItem;
min_params = 0;
max_params = 0;
}
else if (!_tcsicmp(suffix, _T("GetNext"))) // Unlike "Prev", Next also supports 0 or 2 parameters.
{
bif = BIF_TV_GetRelatedItem;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("Get")) || !_tcsicmp(suffix, _T("GetText")))
{
bif = BIF_TV_Get;
min_params = 2;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("SetImageList")))
{
bif = BIF_TV_SetImageList;
max_params = 2; // Leave min at 1.
}
else
return NULL;
}
else if (!_tcsnicmp(func_name, _T("IL_"), 3)) // It's an ImageList function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("Create")))
{
bif = BIF_IL_Create;
min_params = 0;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("Destroy")))
{
bif = BIF_IL_Destroy; // Leave Min/Max set to 1.
}
else if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_IL_Add;
min_params = 2;
max_params = 4;
}
else
return NULL;
}
else if (!_tcsicmp(func_name, _T("SB_SetText")))
{
bif = BIF_StatusBar;
max_params = 3; // Leave min_params at its default of 1.
}
else if (!_tcsicmp(func_name, _T("SB_SetParts")))
{
bif = BIF_StatusBar;
min_params = 0;
max_params = 255; // 255 params allows for up to 256 parts, which is SB's max.
}
else if (!_tcsicmp(func_name, _T("SB_SetIcon")))
{
bif = BIF_StatusBar;
max_params = 3; // Leave min_params at its default of 1.
}
else if (!_tcsicmp(func_name, _T("StrLen")))
#else
if (!_tcsicmp(func_name, _T("StrLen")))
#endif
bif = BIF_StrLen;
else if (!_tcsicmp(func_name, _T("SubStr")))
{
bif = BIF_SubStr;
min_params = 2;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("Struct")))
{
bif = BIF_Struct;
min_params = 1;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("Sizeof")))
{
bif = BIF_sizeof;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("CriticalObject")))
{
bif = BIF_CriticalObject;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("Lock")))
{
bif = BIF_Lock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("TryLock")))
{
bif = BIF_TryLock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("UnLock")))
{
bif = BIF_UnLock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("FindFunc"))) // addFile() Naveen v8.
{
bif = BIF_FindFunc;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("FindLabel"))) // HotKeyIt v1.1.02.00
{
bif = BIF_FindLabel;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("Alias"))) // lowlevel() Naveen v9.
{
bif = BIF_Alias;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("UnZipRawMemory"))) // lowlevel() Naveen v9.
{
bif = BIF_UnZipRawMemory;
min_params = 1;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("getTokenValue"))) // lowlevel() Naveen v9.
{
bif = BIF_getTokenValue;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("CacheEnable"))) // lowlevel() Naveen v9.
{
bif = BIF_CacheEnable;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("Getvar"))) // lowlevel() Naveen v9.
{
bif = BIF_Getvar;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("Trim")) || !_tcsicmp(func_name, _T("LTrim")) || !_tcsicmp(func_name, _T("RTrim"))) // L31
{
bif = BIF_Trim;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("InStr")))
{
bif = BIF_InStr;
min_params = 2;
max_params = 5;
}
else if (!_tcsicmp(func_name, _T("RegExMatch")))
{
bif = BIF_RegEx;
min_params = 2;
max_params = 4;
}
else if (!_tcsicmp(func_name, _T("RegExReplace")))
{
bif = BIF_RegEx;
min_params = 2;
max_params = 6;
}
else if (!_tcsicmp(func_name, _T("StrSplit")))
{
bif = BIF_StrSplit;
min_params = 1;
max_params = 3;
}
else if (!_tcsnicmp(func_name, _T("GetKey"), 6))
{
suffix = func_name + 6;
if (!_tcsicmp(suffix, _T("State")))
{
|
tinku99/ahkdll
|
591ec8306fd2623614f73e12526fced343d13a18
|
#DllImport terminate parameters
|
diff --git a/source/util.cpp b/source/util.cpp
index ecc1c41..d57743d 100644
--- a/source/util.cpp
+++ b/source/util.cpp
@@ -2346,808 +2346,809 @@ HBITMAP IconToBitmap(HICON ahIcon, bool aDestroyIcon)
HBITMAP hbitmap = NULL; // Set default. This will be the value returned.
HDC hdc_desktop = GetDC(HWND_DESKTOP);
HDC hdc = CreateCompatibleDC(hdc_desktop); // Don't pass NULL since I think that would result in a monochrome bitmap.
if (hdc)
{
ICONINFO ii;
if (GetIconInfo(ahIcon, &ii))
{
BITMAP icon_bitmap;
// Find out how big the icon is and create a bitmap compatible with the desktop DC (not the memory DC,
// since its bits per pixel (color depth) is probably 1.
if (GetObject(ii.hbmColor, sizeof(BITMAP), &icon_bitmap)
&& (hbitmap = CreateCompatibleBitmap(hdc_desktop, icon_bitmap.bmWidth, icon_bitmap.bmHeight))) // Assign
{
// To retain maximum quality in case caller needs to resize the bitmap we return, convert the
// icon to a bitmap that matches the icon's actual size:
HGDIOBJ old_object = SelectObject(hdc, hbitmap);
if (old_object) // Above succeeded.
{
// Use DrawIconEx() vs. DrawIcon() because someone said DrawIcon() always draws 32x32
// regardless of the icon's actual size.
// If it's ever needed, this can be extended so that the caller can pass in a background
// color to use in place of any transparent pixels within the icon (apparently, DrawIconEx()
// skips over transparent pixels in the icon when drawing to the DC and its bitmap):
RECT rect = {0, 0, icon_bitmap.bmWidth, icon_bitmap.bmHeight}; // Left, top, right, bottom.
HBRUSH hbrush = CreateSolidBrush(CLR_DEFAULT);
FillRect(hdc, &rect, hbrush);
DeleteObject(hbrush);
// Probably something tried and abandoned: FillRect(hdc, &rect, (HBRUSH)GetStockObject(NULL_BRUSH));
DrawIconEx(hdc, 0, 0, ahIcon, icon_bitmap.bmWidth, icon_bitmap.bmHeight, 0, NULL, DI_NORMAL);
// Debug: Find out properties of new bitmap.
//BITMAP b;
//GetObject(hbitmap, sizeof(BITMAP), &b);
SelectObject(hdc, old_object); // Might be needed (prior to deleting hdc) to prevent memory leak.
}
}
// It's our responsibility to delete these two when they're no longer needed:
DeleteObject(ii.hbmColor);
DeleteObject(ii.hbmMask);
}
DeleteDC(hdc);
}
ReleaseDC(HWND_DESKTOP, hdc_desktop);
if (aDestroyIcon)
DestroyIcon(ahIcon);
return hbitmap;
}
// Lexikos: Used for menu icons on Windows Vista and later. Some similarities to IconToBitmap, maybe should be merged if IconToBitmap does not specifically need to create a device-dependent bitmap?
HBITMAP IconToBitmap32(HICON ahIcon, bool aDestroyIcon)
{
// Get the icon's internal colour and mask bitmaps.
// hbmColor is needed to measure the icon.
// hbmMask is needed to generate an alpha channel if the icon does not have one.
ICONINFO icon_info;
if (!GetIconInfo(ahIcon, &icon_info))
return NULL;
HBITMAP hbitmap = NULL; // Set default in case of failure.
// Get size of icon's internal bitmap.
BITMAP icon_bitmap;
if (GetObject(icon_info.hbmColor, sizeof(BITMAP), &icon_bitmap))
{
int width = icon_bitmap.bmWidth;
int height = icon_bitmap.bmHeight;
HDC hdc = CreateCompatibleDC(NULL);
if (hdc)
{
BITMAPINFO bitmap_info = {0};
// Set parameters for 32-bit bitmap. May also be used to retrieve bitmap data from the icon's mask bitmap.
BITMAPINFOHEADER &bitmap_header = bitmap_info.bmiHeader;
bitmap_header.biSize = sizeof(BITMAPINFOHEADER);
bitmap_header.biWidth = width;
bitmap_header.biHeight = height;
bitmap_header.biBitCount = 32;
bitmap_header.biPlanes = 1;
// Create device-independent bitmap.
UINT *bits;
if (hbitmap = CreateDIBSection(hdc, &bitmap_info, 0, (void**)&bits, NULL, 0))
{
HGDIOBJ old_object = SelectObject(hdc, hbitmap);
if (old_object) // Above succeeded.
{
// Draw icon onto bitmap. Use DrawIconEx because DrawIcon always draws a large (usually 32x32) icon!
DrawIconEx(hdc, 0, 0, ahIcon, 0, 0, 0, NULL, DI_NORMAL);
// May be necessary for bits to be in sync, according to documentation for CreateDIBSection:
GdiFlush();
// Calculate end of bitmap data.
UINT *bits_end = bits + width*height;
UINT *this_pixel; // Used in a few loops below.
// Check for alpha data.
bool has_nonzero_alpha = false;
for (this_pixel = bits; this_pixel < bits_end; ++this_pixel)
{
if (*this_pixel >> 24)
{
has_nonzero_alpha = true;
break;
}
}
if (!has_nonzero_alpha)
{
// Get bitmap data from the icon's mask.
UINT *mask_bits = (UINT*)_alloca(height*width*4);
if (GetDIBits(hdc, icon_info.hbmMask, 0, height, (LPVOID)mask_bits, &bitmap_info, 0))
{
UINT *this_mask_pixel;
// Use the icon's mask to generate alpha data.
for (this_pixel = bits, this_mask_pixel = mask_bits; this_pixel < bits_end; ++this_pixel, ++this_mask_pixel)
{
if (*this_mask_pixel)
*this_pixel = 0;
else
*this_pixel |= 0xff000000;
}
}
else
{
// GetDIBits failed, simply make the bitmap opaque.
for (this_pixel = bits; this_pixel < bits_end; ++this_pixel)
*this_pixel |= 0xff000000;
}
}
SelectObject(hdc, old_object);
}
else
{
// Probably very rare, but be on the safe side.
DeleteObject(hbitmap);
hbitmap = NULL;
}
}
DWORD dwError = GetLastError();
DeleteDC(hdc);
}
}
// It's our responsibility to delete these two when they're no longer needed:
DeleteObject(icon_info.hbmColor);
DeleteObject(icon_info.hbmMask);
if (aDestroyIcon)
DestroyIcon(ahIcon);
return hbitmap;
}
HRESULT MySetWindowTheme(HWND hwnd, LPCWSTR pszSubAppName, LPCWSTR pszSubIdList)
{
// The library must be loaded dynamically, otherwise the app will not launch on OSes older than XP.
// Theme DLL is normally available only on XP+, but an attempt to load it is made unconditionally
// in case older OSes can ever have it.
HRESULT hresult = !S_OK; // Set default as "failure".
HINSTANCE hinstTheme = LoadLibrary(_T("uxtheme"));
if (hinstTheme)
{
typedef HRESULT (WINAPI *MySetWindowThemeType)(HWND, LPCWSTR, LPCWSTR);
MySetWindowThemeType DynSetWindowTheme = (MySetWindowThemeType)GetProcAddress(hinstTheme, "SetWindowTheme");
if (DynSetWindowTheme)
hresult = DynSetWindowTheme(hwnd, pszSubAppName, pszSubIdList);
FreeLibrary(hinstTheme);
}
return hresult;
}
//HRESULT MyEnableThemeDialogTexture(HWND hwnd, DWORD dwFlags)
//{
// // The library must be loaded dynamically, otherwise the app will not launch on OSes older than XP.
// // Theme DLL is normally available only on XP+, but an attempt to load it is made unconditionally
// // in case older OSes can ever have it.
// HRESULT hresult = !S_OK; // Set default as "failure".
// HINSTANCE hinstTheme = LoadLibrary(_T("uxtheme"));
// if (hinstTheme)
// {
// typedef HRESULT (WINAPI *MyEnableThemeDialogTextureType)(HWND, DWORD);
// MyEnableThemeDialogTextureType DynEnableThemeDialogTexture = (MyEnableThemeDialogTextureType)GetProcAddress(hinstTheme, "EnableThemeDialogTexture");
// if (DynEnableThemeDialogTexture)
// hresult = DynEnableThemeDialogTexture(hwnd, dwFlags);
// FreeLibrary(hinstTheme);
// }
// return hresult;
//}
LPTSTR ConvertEscapeSequences(LPTSTR aBuf, TCHAR aEscapeChar, bool aAllowEscapedSpace)
// Replaces any escape sequences in aBuf with their reduced equivalent. For example, if aEscapeChar
// is accent, Each `n would become a literal linefeed. aBuf's length should always be the same or
// lower than when the process started, so there is no chance of overflow.
{
LPTSTR cp, cp1;
for (cp = aBuf; ; ++cp) // Increment to skip over the symbol just found by the inner for().
{
for (; *cp && *cp != aEscapeChar; ++cp); // Find the next escape char.
if (!*cp) // end of string.
break;
cp1 = cp + 1;
switch (*cp1)
{
// Only lowercase is recognized for these:
case 'a': *cp1 = '\a'; break; // alert (bell) character
case 'b': *cp1 = '\b'; break; // backspace
case 'f': *cp1 = '\f'; break; // formfeed
case 'n': *cp1 = '\n'; break; // newline
case 'r': *cp1 = '\r'; break; // carriage return
case 't': *cp1 = '\t'; break; // horizontal tab
case 'v': *cp1 = '\v'; break; // vertical tab
case 's': // space (not always allowed for backward compatibility reasons).
if (aAllowEscapedSpace)
*cp1 = ' ';
//else do nothing extra, just let the standard action for unrecognized escape sequences.
break;
// Otherwise, if it's not one of the above, the escape-char is considered to
// mark the next character as literal, regardless of what it is. Examples:
// `` -> `
// `:: -> :: (effectively)
// `; -> ;
// `c -> c (i.e. unknown escape sequences resolve to the char after the `)
}
// Below has a final +1 to include the terminator:
tmemmove(cp, cp1, _tcslen(cp1) + 1);
}
return aBuf;
}
int FindNextDelimiter(LPCTSTR aBuf, TCHAR aDelimiter, int aStartIndex, LPCTSTR aLiteralMap)
// Returns the index of the next delimiter, taking into account quotes, parentheses, etc.
// If the delimiter is not found, returns the length of aBuf.
{
bool in_quotes = false;
int open_parens = 0;
for (int mark = aStartIndex; ; ++mark)
{
if (aBuf[mark] == aDelimiter)
{
if (!in_quotes && open_parens <= 0 && !(aLiteralMap && aLiteralMap[mark]))
// A delimiting comma other than one in a sub-statement or function.
return mark;
// Otherwise, its a quoted/literal comma or one in parentheses (such as function-call).
continue;
}
switch (aBuf[mark])
{
case '"': // There are sections similar this one later below; so see them for comments.
in_quotes = !in_quotes;
break;
case '(': // For our purpose, "(", "[" and "{" can be treated the same.
case '[': // If they aren't balanced properly, a later stage will detect it.
case '{': //
if (!in_quotes) // Literal parentheses inside a quoted string should not be counted for this purpose.
++open_parens;
break;
case ')':
case ']':
case '}':
if (!in_quotes)
--open_parens; // If this makes it negative, validation later on will catch the syntax error.
break;
case '\0':
// Reached the end of the string without finding a delimiter. Return the
// index of the null-terminator since that's typically what the caller wants.
return mark;
//default: some other character; just have the loop skip over it.
}
}
}
bool IsStringInList(LPTSTR aStr, LPTSTR aList, bool aFindExactMatch)
// Checks if aStr exists in aList (which is a comma-separated list).
// If aStr is blank, aList must start with a delimiting comma for there to be a match.
{
// Must use a temp. buffer because otherwise there's no easy way to properly match upon strings
// such as the following:
// if var in string,,with,,literal,,commas
TCHAR buf[LINE_SIZE];
TCHAR *next_field, *cp, *end_buf = buf + _countof(buf) - 1;
// v1.0.48.01: Performance improved by Lexikos.
for (TCHAR *this_field = aList; *this_field; this_field = next_field) // For each field in aList.
{
for (cp = buf, next_field = this_field; *next_field && cp < end_buf; ++cp, ++next_field) // For each char in the field, copy it over to temporary buffer.
{
if (*next_field == ',') // This is either a delimiter (,) or a literal comma (,,).
{
++next_field;
if (*next_field != ',') // It's "," instead of ",," so treat it as the end of this field.
break;
// Otherwise it's ",," and next_field now points at the second comma; so copy that comma
// over as a literal comma then continue copying.
}
*cp = *next_field;
}
// The end of this field has been reached (or reached the capacity of the buffer), so terminate the string
// in the buffer.
*cp = '\0';
if (*buf) // It is possible for this to be blank only for the first field. Example: if var in ,abc
{
if (aFindExactMatch)
{
if (!g_tcscmp(aStr, buf)) // Match found
return true;
}
else // Substring match
if (g_tcsstr(aStr, buf)) // Match found
return true;
}
else // First item in the list is the empty string.
if (aFindExactMatch) // In this case, this is a match if aStr is also blank.
{
if (!*aStr)
return true;
}
else // Empty string is always found as a substring in any other string.
return true;
} // for()
return false; // No match found.
}
LPTSTR InStrAny(LPTSTR aStr, LPTSTR aNeedle[], int aNeedleCount, size_t &aFoundLen)
{
// For each character in aStr:
for ( ; *aStr; ++aStr)
// For each needle:
for (int i = 0; i < aNeedleCount; ++i)
// For each character in this needle:
for (LPTSTR needle_pos = aNeedle[i], str_pos = aStr; ; ++needle_pos, ++str_pos)
{
if (!*needle_pos)
{
// All characters in needle matched aStr at this position, so we've
// found our string. If this needle is empty, it implicitly matches
// at the first position in the string.
aFoundLen = needle_pos - aNeedle[i];
return aStr;
}
// Otherwise, we haven't reached the end of the needle. If we've reached
// the end of aStr, *str_pos and *needle_pos won't match, so the check
// below will break out of the loop.
if (*needle_pos != *str_pos)
// Not a match: continue on to the next needle, or the next starting
// position in aStr if this is the last needle.
break;
}
// If the above loops completed without returning, no matches were found.
return NULL;
}
short IsDefaultType(LPTSTR aTypeDef){
static LPTSTR sTypeDef[8] = {_T(" CHAR UCHAR BOOLEAN BYTE ")
#ifndef _WIN64
,_T(" ATOM LANGID WCHAR WORD SHORT USHORT BYTE TCHAR HALF_PTR UHALF_PTR ")
#else
,_T(" ATOM LANGID WCHAR WORD SHORT USHORT BYTE TCHAR ")
#endif
,_T("")
#ifdef _WIN64
,_T(" INT UINT FLOAT INT32 LONG LONG32 HFILE HRESULT BOOL COLORREF DWORD DWORD32 LCID LCTYPE LGRPID LRESULT UINT32 ULONG ULONG32 HALF_PTR UHALF_PTR ")
#else
,_T(" INT UINT FLOAT INT32 LONG LONG32 HFILE HRESULT BOOL COLORREF DWORD DWORD32 LCID LCTYPE LGRPID LRESULT UINT32 ULONG ULONG32 PTR UPTR INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR PDWORD PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR DWORD_PTR HACCEL HANDLE HBITMAP HBRUSH HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP HENHMETAFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRGN HRSRC HSZ HWINSTA HWND LPARAM LPBOOL LPBYTE LPCOLORREF LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR LPVOID LPWORD LPWSTR PHANDLE PHKEY PINT PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 POINTER_UNSIGNED PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SIZE_T UINT_PTR ULONG_PTR VOID ")
#endif
,_T(""),_T(""),_T("")
#ifdef _WIN64
,_T(" INT64 UINT64 DOUBLE __int64 LONGLONG LONG64 USN DWORDLONG DWORD64 ULONGLONG ULONG64 PTR UPTR INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR PDWORD PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR DWORD_PTR HACCEL HANDLE HBITMAP HBRUSH HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP HENHMETAFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRGN HRSRC HSZ HWINSTA HWND LPARAM LPBOOL LPBYTE LPCOLORREF LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR LPVOID LPWORD LPWSTR PHANDLE PHKEY PINT PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 POINTER_UNSIGNED PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SIZE_T UINT_PTR ULONG_PTR VOID ")
#else
,_T(" INT64 UINT64 DOUBLE __int64 LONGLONG LONG64 USN DWORDLONG DWORD64 ULONGLONG ULONG64 ")
#endif
};
for (int i=0;i<8;i++)
{
if (tcscasestr(sTypeDef[i],aTypeDef))
return i + 1;
}
// type was not found
return NULL;
}
ResultType LoadDllFunction(LPTSTR parameter, LPTSTR aBuf)
{
LPTSTR aFuncName = omit_leading_whitespace(parameter);
// backup current function
// Func currentfunc = **g_script.mFunc;
if (!(parameter = _tcschr(parameter, ',')) || !*parameter)
return g_script.ScriptError(ERR_PARAM2_REQUIRED, aBuf);
else
parameter++;
if (_tcschr(aFuncName, ','))
*(_tcschr(aFuncName, ',')) = '\0';
ltrim(parameter);
int insert_pos;
Func *found_func = g_script.FindFunc(aFuncName, _tcslen(aFuncName), &insert_pos);
if (found_func)
return g_script.ScriptError(_T("Duplicate function definition."), aFuncName); // Seems more descriptive than "Function already defined."
else
if (!(found_func = g_script.AddFunc(aFuncName, _tcslen(aFuncName), false, insert_pos)))
return FAIL; // It already displayed the error.
void *function = NULL; // Will hold the address of the function to be called.
found_func->mBIF = (BuiltInFunctionType)BIF_DllImport;
found_func->mIsBuiltIn = true;
found_func->mMinParams = 0;
TCHAR buf[MAX_PATH];
size_t space_remaining = LINE_SIZE - (parameter - aBuf);
if (tcscasestr(parameter, _T("%A_ScriptDir%")))
{
BIV_ScriptDir(buf, _T("A_ScriptDir"));
StrReplace(parameter, _T("%A_ScriptDir%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_AppData%"))) // v1.0.45.04: This and the next were requested by Tekl to make it easier to customize scripts on a per-user basis.
{
BIV_SpecialFolderPath(buf, _T("A_AppData"));
StrReplace(parameter, _T("%A_AppData%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_AppDataCommon%"))) // v1.0.45.04.
{
BIV_SpecialFolderPath(buf, _T("A_AppDataCommon"));
StrReplace(parameter, _T("%A_AppDataCommon%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_AhkPath%"))) // v1.0.45.04.
{
BIV_AhkPath(buf, _T("A_AhkPath"));
StrReplace(parameter, _T("%A_AhkPath%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_AhkDir%"))) // v1.0.45.04.
{
BIV_AhkDir(buf, _T("A_AhkDir"));
StrReplace(parameter, _T("%A_AhkDir%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_DllDir%"))) // v1.0.45.04.
{
BIV_DllDir(buf, _T("A_DllDir"));
StrReplace(parameter, _T("%A_DllDir%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (tcscasestr(parameter, _T("%A_DllPath%"))) // v1.0.45.04.
{
BIV_DllPath(buf, _T("A_DllPath"));
StrReplace(parameter, _T("%A_DllPath%"), buf, SCS_INSENSITIVE, 1, space_remaining);
}
if (_tcschr(parameter, '%'))
{
return g_script.ScriptError(_T("Reference not allowed here, use & where possible. Only %A_AhkPath% %A_AhkDir% %A_DllPath% %A_DllDir% %A_ScriptDir% %A_AppData[Common]% can be used here."), parameter);
}
// terminate dll\function name, find it and jump to next parameter
if (_tcschr(parameter, ','))
*(_tcschr(parameter, ',')) = '\0';
function = (void*)ATOI64(parameter);
if (!function)
{
LPTSTR dll_name = _tcsrchr(parameter, '\\');
if (dll_name)
{
*dll_name = '\0';
if (!GetModuleHandle(parameter))
LoadLibrary(parameter);
*dll_name = '\\';
}
function = (void*)GetDllProcAddress(parameter);
}
if (!function)
return g_script.ScriptError(ERR_NONEXISTENT_FUNCTION, parameter);
parameter = parameter + _tcslen(parameter) + 1;
LPTSTR parm = SimpleHeap::Malloc(parameter);
bool has_return = false;
int aParamCount = ATOI(parm) ? 0 : 1;
if (*parm)
for (; _tcschr(parameter, ','); aParamCount++)
{
if (parameter = _tcschr(parameter, ','))
parameter++;
}
if (*parm && aParamCount < 1)
return g_script.ScriptError(ERR_PARAM3_REQUIRED, aBuf);
// Determine the type of return value.
DYNAPARM *return_attrib = (DYNAPARM*)SimpleHeap::Malloc(sizeof(DYNAPARM));
memset(return_attrib, 0, sizeof(DYNAPARM)); // Init all to default in case ConvertDllArgType() isn't called below. This struct holds the type and other attributes of the function's return value.
#ifdef WIN32_PLATFORM
int dll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it.
#endif
if (!(aParamCount % 2)) // Even number of parameters indicates the return type has been omitted, so assume BOOL/INT.
return_attrib->type = DLL_ARG_INT;
else
{
// Check validity of this arg's return type:
LPTSTR return_type_string[2];
- return_type_string[0] = parameter;
+ return_type_string[0] = omit_leading_whitespace(parameter);
return_type_string[1] = NULL; // Added in 1.0.48.
// 64-bit note: The calling convention detection code is preserved here for script compatibility.
if (!_tcsnicmp(return_type_string[0], _T("CDecl"), 5)) // Alternate calling convention.
{
#ifdef WIN32_PLATFORM
dll_call_mode = DC_CALL_CDECL;
#endif
return_type_string[0] = omit_leading_whitespace(return_type_string[0] + 5);
if (!*return_type_string[0])
{ // Take a shortcut since we know this empty string will be used as "Int":
return_attrib->type = DLL_ARG_INT;
goto has_valid_return_type;
}
}
ConvertDllArgType(return_type_string, *return_attrib);
if (return_attrib->type == DLL_ARG_INVALID)
return CONDITION_FALSE;
has_return = true;
has_valid_return_type:
aParamCount--;
#ifdef WIN32_PLATFORM
if (!return_attrib->passed_by_address) // i.e. the special return flags below are not needed when an address is being returned.
{
if (return_attrib->type == DLL_ARG_DOUBLE)
dll_call_mode |= DC_RETVAL_MATH8;
else if (return_attrib->type == DLL_ARG_FLOAT)
dll_call_mode |= DC_RETVAL_MATH4;
}
#endif
}
// Using stack memory, create an array of dll args large enough to hold the actual number of args present.
int arg_count = aParamCount / 2; // Might provide one extra due to first/last params, which is inconsequential.
DYNAPARM *dyna_param_def = arg_count ? (DYNAPARM *)SimpleHeap::Malloc(arg_count * sizeof(DYNAPARM)) : NULL;
DYNAPARM *dyna_param = arg_count ? (DYNAPARM *)SimpleHeap::Malloc(arg_count * sizeof(DYNAPARM)) : NULL;
// Above: _alloca() has been checked for code-bloat and it doesn't appear to be an issue.
// Above: Fix for v1.0.36.07: According to MSDN, on failure, this implementation of _alloca() generates a
// stack overflow exception rather than returning a NULL value. Therefore, NULL is no longer checked,
// nor is an exception block used since stack overflow in this case should be exceptionally rare (if it
// does happen, it would probably mean the script or the program has a design flaw somewhere, such as
// infinite recursion).
LPTSTR arg_type_string[2];
int i = arg_count * sizeof(void *);
// for Unicode <-> ANSI charset conversion
#ifdef UNICODE
CStringA **pStr = (CStringA **)
#else
CStringW **pStr = (CStringW **)
#endif
SimpleHeap::Malloc(i); // _alloca vs malloc can make a significant difference to performance in some cases.
memset(pStr, 0, i);
// Above has already ensured that after the first parameter, there are either zero additional parameters
// or an even number of them. In other words, each arg type will have an arg value to go with it.
// It has also verified that the dyna_param array is large enough to hold all of the args.
LPTSTR this_param;
for (arg_count = 0, i = 1; i < aParamCount; ++arg_count, i += 2) // Same loop as used later below, so maintain them together.
{
this_param = _tcschr(parm, ',');
*this_param = '\0';
this_param++;
arg_type_string[0] = parm; // It will be detected as invalid below.
arg_type_string[1] = NULL;
//ExprTokenType &this_param = *aParam[i + 1]; // Resolved for performance and convenience.
DYNAPARM &this_dyna_param = dyna_param_def[arg_count]; //
// Store the each arg into a dyna_param struct, using its arg type to determine how.
ConvertDllArgType(arg_type_string, this_dyna_param);
switch (this_dyna_param.type)
{
case DLL_ARG_STR:
if (ATOI64(this_param))
{
// For now, string args must be real strings rather than floats or ints. An alternative
// to this would be to convert it to number using persistent memory from the caller (which
// is necessary because our own stack memory should not be passed to any function since
// that might cause it to return a pointer to stack memory, or update an output-parameter
// to be stack memory, which would be invalid memory upon return to the caller).
// The complexity of this doesn't seem worth the rarity of the need, so this will be
// documented in the help file.
return CONDITION_FALSE;
}
// Otherwise, it's a supported type of string.
this_dyna_param.ptr = this_param; // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions).
// NOTES ABOUT THE ABOVE:
// UPDATE: The v1.0.44.14 item below doesn't work in release mode, only debug mode (turning off
// "string pooling" doesn't help either). So it's commented out until a way is found
// to pass the address of a read-only empty string (if such a thing is possible in
// release mode). Such a string should have the following properties:
// 1) The first byte at its address should be '\0' so that functions can read it
// and recognize it as a valid empty string.
// 2) The memory address should be readable but not writable: it should throw an
// access violation if the function tries to write to it (like "" does in debug mode).
// SO INSTEAD of the following, DllCall() now checks further below for whether sEmptyString
// has been overwritten/trashed by the call, and if so displays a warning dialog.
// See note above about this: v1.0.44.14: If a variable is being passed that has no capacity, pass a
// read-only memory area instead of a writable empty string. There are two big benefits to this:
// 1) It forces an immediate exception (catchable by DllCall's exception handler) so
// that the program doesn't crash from memory corruption later on.
// 2) It avoids corrupting the program's static memory area (because sEmptyString
// resides there), which can save many hours of debugging for users when the program
// crashes on some seemingly unrelated line.
// Of course, it's not a complete solution because it doesn't stop a script from
// passing a variable whose capacity is non-zero yet too small to handle what the
// function will write to it. But it's a far cry better than nothing because it's
// common for a script to forget to call VarSetCapacity before passing a buffer to some
// function that writes a string to it.
//if (this_dyna_param.str == Var::sEmptyString) // To improve performance, compare directly to Var::sEmptyString rather than calling Capacity().
// this_dyna_param.str = _T(""); // Make it read-only to force an exception. See comments above.
break;
case DLL_ARG_xSTR:
// See the section above for comments.
if (ATOI64(this_param))
return CONDITION_FALSE;
// String needing translation: ASTR on Unicode build, WSTR on ANSI build.
pStr[arg_count] = new UorA(CStringCharFromWChar, CStringWCharFromChar)(this_param);
this_dyna_param.ptr = pStr[arg_count]->GetBuffer();
break;
case DLL_ARG_DOUBLE:
case DLL_ARG_FLOAT:
// This currently doesn't validate that this_dyna_param.is_unsigned==false, since it seems
// too rare and mostly harmless to worry about something like "Ufloat" having been specified.
this_dyna_param.value_double = ATOF(this_param);
if (this_dyna_param.type == DLL_ARG_FLOAT)
this_dyna_param.value_float = (float)this_dyna_param.value_double;
break;
case DLL_ARG_INVALID:
return CONDITION_FALSE;
default: // Namely:
//case DLL_ARG_INT:
//case DLL_ARG_SHORT:
//case DLL_ARG_CHAR:
//case DLL_ARG_INT64:
if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !ATOI64(this_param))
// The above and below also apply to BIF_NumPut(), so maintain them together.
// !IS_NUMERIC() is checked because such tokens are already signed values, so should be
// written out as signed so that whoever uses them can interpret negatives as large
// unsigned values.
// Support for unsigned values that are 32 bits wide or less is done via ATOI64() since
// it should be able to handle both signed and unsigned values. However, unsigned 64-bit
// values probably require ATOU64(), which will prevent something like -1 from being seen
// as the largest unsigned 64-bit int; but more importantly there are some other issues
// with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere,
// so unsigned values can only be partially supported for incoming parameters, but probably
// not for outgoing parameters (values the function changed) or the return value. Those
// should probably be written back out to the script as negatives so that other parts of
// the script, such as expressions, can see them as signed values. In other words, if the
// script somehow gets a 64-bit unsigned value into a variable, and that value is larger
// that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve
// it, but any output parameter should be written back out as a negative if it exceeds
// LLONG_MAX (return values can be written out as unsigned since the script can specify
// signed to avoid this, since they don't need the incoming detection for ATOU()).
this_dyna_param.value_int64 = (__int64)ATOU64(this_param); // Cast should not prevent called function from seeing it as an undamaged unsigned number.
else
this_dyna_param.value_int64 = ATOI64(this_param);
// Values less than or equal to 32-bits wide always get copied into a single 32-bit value
// because they should be right justified within it for insertion onto the call stack.
if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall().
this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below).
} // switch (this_dyna_param.type)
- parm = _tcschr(this_param,',') + 1;
+ if ((parm = _tcschr(this_param, ',')))
+ *parm++ = '\0';
} // for() each arg.
if (has_return && aParamCount)
*(this_param) = '\0';
found_func->mClass = (Object*)function;
found_func->mParamCount = arg_count;
found_func->mVar = (Var**)return_attrib;
found_func->mStaticVar = (Var**)pStr;
found_func->mLazyVar = (Var**)dyna_param_def;
found_func->mParam = (FuncParam*)dyna_param;
#ifdef WIN32_PLATFORM
found_func->mVarCount = dll_call_mode;
#endif
return CONDITION_TRUE;
}
DWORD DecompressBuffer(void *aBuffer,LPVOID &aDataBuf, TCHAR *pwd[]) // LiteZip Raw compression
{
unsigned int hdrsz = 20;
TCHAR pw[1024] = {0};
if (pwd && pwd[0])
for(unsigned int i = 0;pwd[i];i++)
pw[i] = (TCHAR)*pwd[i];
ULONG aSizeCompressed = *(ULONG*)((UINT_PTR)aBuffer + 8);
DWORD aSizeEncrypted = *(DWORD*)((UINT_PTR)aBuffer + 16);
DWORD hash;
BYTE *aDataEncrypted = NULL;
HashData((LPBYTE)aBuffer + hdrsz,aSizeEncrypted?aSizeEncrypted:aSizeCompressed,(LPBYTE)&hash,4);
if (0x04034b50 == *(ULONG*)(UINT_PTR)aBuffer && hash == *(ULONG*)((UINT_PTR)aBuffer + 4))
{
HUNZIP huz;
ZIPENTRY ze;
DWORD result;
ULONG aSizeDeCompressed = *(ULONG*)((UINT_PTR)aBuffer + 12);
aDataBuf = VirtualAlloc(NULL, aSizeDeCompressed, MEM_COMMIT, PAGE_READWRITE);
if (aDataBuf)
{
if (aSizeEncrypted)
{
typedef BOOL (_stdcall *MyDecrypt)(HCRYPTKEY,HCRYPTHASH,BOOL,DWORD,BYTE*,DWORD*);
HMODULE advapi32 = LoadLibrary(_T("advapi32.dll"));
MyDecrypt Decrypt = (MyDecrypt)GetProcAddress(advapi32,"CryptDecrypt");
LPSTR aDataEncryptedString = (LPSTR)VirtualAlloc(NULL, aSizeEncrypted, MEM_COMMIT, PAGE_READWRITE);
DWORD aSizeEncryptedString = aSizeEncrypted;
DWORD aSizeEncryptedTemp = aSizeEncrypted;
HCRYPTPROV hProv;
HCRYPTKEY hKey;
HCRYPTHASH hHash;
CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_AES,CRYPT_VERIFYCONTEXT);
CryptCreateHash(hProv,CALG_SHA1,NULL,NULL,&hHash);
CryptHashData(hHash,(BYTE *) pw,(DWORD)_tcslen(pw) * sizeof(TCHAR),0);
CryptDeriveKey(hProv,CALG_AES_256,hHash,256<<16,&hKey);
CryptDestroyHash(hHash);
memmove(aDataEncryptedString,(LPBYTE)aBuffer + hdrsz,aSizeEncrypted);
Decrypt(hKey,NULL,true,0,(BYTE*)aDataEncryptedString,&aSizeEncryptedString);
CryptStringToBinaryA(aDataEncryptedString,NULL,CRYPT_STRING_BASE64,NULL,&aSizeEncryptedTemp,NULL,NULL);
if (aSizeEncryptedTemp == 0)
{ // incorrect password
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE);
return 0;
}
aDataEncrypted = (BYTE*)VirtualAlloc(NULL, aSizeEncryptedTemp, MEM_COMMIT, PAGE_READWRITE);
CryptStringToBinaryA(aDataEncryptedString,NULL,CRYPT_STRING_BASE64,aDataEncrypted,&aSizeEncryptedTemp,NULL,NULL);
VirtualFree(aDataEncryptedString,aSizeEncrypted,MEM_RELEASE);
CryptDestroyKey(hKey);
CryptReleaseContext(hProv,0);
if (openArchive(&huz,(LPBYTE)aDataEncrypted, aSizeCompressed, ZIP_MEMORY|ZIP_RAW, 0))
{ // failed to open archive
closeArchive((TUNZIP *)huz);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE);
return 0;
}
}
else if (openArchive(&huz,(LPBYTE)aBuffer + hdrsz, aSizeCompressed, ZIP_MEMORY|ZIP_RAW, 0))
{ // failed to open archive
closeArchive((TUNZIP *)huz);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
return 0;
}
ze.CompressedSize = aSizeDeCompressed;
ze.UncompressedSize = aSizeDeCompressed;
if ((result = unzipEntry((TUNZIP *)huz, aDataBuf, &ze, ZIP_MEMORY)))
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
else
{
closeArchive((TUNZIP *)huz);
if (aDataEncrypted)
VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE);
return aSizeDeCompressed;
}
closeArchive((TUNZIP *)huz);
if (aDataEncrypted)
VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE);
}
}
return 0;
}
#ifndef MINIDLL
LONG WINAPI DisableHooksOnException(PEXCEPTION_POINTERS pExceptionPtrs)
{
// Disable all hooks to avoid system/mouse freeze
if (pExceptionPtrs->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
&& pExceptionPtrs->ExceptionRecord->ExceptionFlags == EXCEPTION_NONCONTINUABLE)
AddRemoveHooks(0);
return EXCEPTION_CONTINUE_SEARCH;
}
#endif
#if defined(_MSC_VER) && defined(_DEBUG)
void OutputDebugStringFormat(LPCTSTR fmt, ...)
{
CString sMsg;
va_list ap;
va_start(ap, fmt);
sMsg.FormatV(fmt, ap);
OutputDebugString(sMsg);
}
#endif
|
tinku99/ahkdll
|
dfe0becdf14c25735d29b250151792b1ab675fdd
|
WinApi TCHAR update and some improvements
|
diff --git a/source/AutoHotkey.cpp b/source/AutoHotkey.cpp
index c499542..fe2ab86 100644
--- a/source/AutoHotkey.cpp
+++ b/source/AutoHotkey.cpp
@@ -1,346 +1,345 @@
/*
AutoHotkey
Copyright 2003-2009 Chris Mallett ([email protected])
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "stdafx.h" // pre-compiled headers
#ifndef _USRDLL
#include "globaldata.h" // for access to many global vars
#include "application.h" // for MsgSleep()
#include "window.h" // For MsgBox() & SetForegroundLockTimeout()
#include "TextIO.h"
#include "LiteUnzip.h"
// General note:
// The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep().
// The reason for this is that if the keyboard or mouse hook is installed, a straight call
// to Sleep() will cause user keystrokes & mouse events to lag because the message pump
// (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the
// hook functions.
int WINAPI _tWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
// Init any globals not in "struct g" that need it:
#ifdef _DEBUG
g_hResource = FindResource(NULL, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA));
#else
if (!(g_hResource = FindResource(NULL, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA)))
&& !(g_hResource = FindResource(NULL, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA))))
g_hResource = NULL;
#endif
g_hInstance = hInstance;
InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x).
InitializeCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment.
if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround.
*g_WorkingDir = '\0';
// Unlike the below, the above must not be Malloc'd because the contents can later change to something
// as large as MAX_PATH by means of the SetWorkingDir command.
g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command.
// Set defaults, to be overridden by command line args we receive:
bool restart_mode = false;
#ifndef AUTOHOTKEYSC
/* HotKeyIt start AutoHotkey.ahk in same folder as usual
#ifdef _DEBUG
TCHAR *script_filespec = _T("Test\\Test.ahk");
#else
*/
TCHAR *script_filespec = NULL; // Set default as "unspecified/omitted".
//#endif
#endif
// The problem of some command line parameters such as /r being "reserved" is a design flaw (one that
// can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled
// scripts because running a script via AutoHotkey.exe should avoid treating anything after the
// filename as switches. This flaw probably occurred because when this part of the program was designed,
// there was no plan to have compiled scripts.
//
// Examine command line args. Rules:
// Any special flags (e.g. /force and /restart) must appear prior to the script filespec.
// The script filespec (if present) must be the first non-backslash arg.
// All args that appear after the filespec are considered to be parameters for the script
// and will be added as variables %1% %2% etc.
// The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters
// unless the filename is explicitly given (shouldn't be an issue for 99.9% of people).
TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%).
Var *var;
bool switch_processing_is_complete = false;
int script_param_num = 1;
for (int i = 1; i < __argc; ++i) // Start at 1 because 0 contains the program name.
{
param = __targv[i]; // For performance and convenience.
if (switch_processing_is_complete) // All args are now considered to be input parameters for the script.
{
if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) )
return CRITICAL_ERROR; // Realistically should never happen.
var->Assign(param);
++script_param_num;
}
// Insist that switches be an exact match for the allowed values to cut down on ambiguity.
// For example, if the user runs "CompiledScript.exe /find", we want /find to be considered
// an input parameter for the script rather than a switch:
else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart")))
restart_mode = true;
else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force")))
g_ForceLaunch = true;
else if (!_tcsicmp(param, _T("/ErrorStdOut")))
g_script.mErrorStdOut = true;
#ifndef AUTOHOTKEYSC // i.e. the following switch is recognized only by AutoHotkey.exe (especially since recognizing new switches in compiled scripts can break them, unlike AutoHotkey.exe).
else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script.
{
++i; // Consume the next parameter too, because it's associated with this one.
if (i >= __argc) // Missing the expected filename parameter.
return CRITICAL_ERROR;
// For performance and simplicity, open/create the file unconditionally and keep it open until exit.
g_script.mIncludeLibraryFunctionsThenExit = new TextFile;
if (!g_script.mIncludeLibraryFunctionsThenExit->Open(__targv[i], TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file.
return CRITICAL_ERROR;
}
else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute")))
{
g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0
}
else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn
{
// Default codepage for the script file, NOT the default for commands used by it.
g_DefaultScriptCodepage = ATOU(param + 3);
}
#endif
#ifdef CONFIG_DEBUGGER
// Allow a debug session to be initiated by command-line.
else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '='))
{
if (param[6] == '=')
{
param += 7;
LPTSTR c = _tcsrchr(param, ':');
if (c)
{
StringTCharToChar(param, g_DebuggerHost, (int)(c-param));
StringTCharToChar(c + 1, g_DebuggerPort);
}
else
{
StringTCharToChar(param, g_DebuggerHost);
g_DebuggerPort = "9000";
}
}
else
{
g_DebuggerHost = "127.0.0.1";
g_DebuggerPort = "9000";
}
// The actual debug session is initiated after the script is successfully parsed.
}
#endif
else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design).
{
switch_processing_is_complete = true; // No more switches allowed after this point.
#ifdef AUTOHOTKEYSC
--i; // Make the loop process this item again so that it will be treated as a script param.
#else
if (!g_hResource) // Only apply if it is not a compiled AutoHotkey.exe
script_filespec = param; // The first unrecognized switch must be the script filespec, by design.
else
--i; // Make the loop process this item again so that it will be treated as a script param.
#endif
}
}
// Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero:
if ( !(var = g_script.FindOrAddVar(_T("0"))) )
return CRITICAL_ERROR; // Realistically should never happen.
var->Assign(script_param_num - 1);
global_init(*g); // Set defaults.
// Set up the basics of the script:
#ifdef AUTOHOTKEYSC
if (g_script.Init(*g, _T(""), restart_mode,0,false) != OK)
#else
if (g_script.Init(*g, script_filespec, restart_mode,0,false) != OK) // Set up the basics of the script, using the above.
#endif
return CRITICAL_ERROR;
// Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below,
// never returns, perhaps because it contains an infinite loop (intentional or not):
CopyMemory(&g_default, g, sizeof(global_struct));
// Could use CreateMutex() but that seems pointless because we have to discover the
// hWnd of the existing process so that we can close or restart it, so we would have
// to do this check anyway, which serves both purposes. Alt method is this:
// Even if a 2nd instance is run with the /force switch and then a 3rd instance
// is run without it, that 3rd instance should still be blocked because the
// second created a 2nd handle to the mutex that won't be closed until the 2nd
// instance terminates, so it should work ok:
//CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness.
//if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS)
#ifdef AUTOHOTKEYSC
UINT load_result = g_script.LoadFromFile();
#else
UINT load_result = g_script.LoadFromFile(script_filespec == NULL);
#endif
if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call).
return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it.
if (!load_result) // LoadFromFile() relies upon us to do this check. No script was loaded or we're in /iLib mode, so nothing more to do.
return 0;
// Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of
// SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts
// and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16:
if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE && IS_PERSISTENT)
g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT;
HWND w_existing = NULL;
UserMessages reason_to_close_prior = (UserMessages)0;
if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch)
{
// Note: the title below must be constructed the same was as is done by our
// CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle:
if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle))
{
if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE)
return 0;
if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE)
if (MsgBox(_T("An older instance of this script is already running. Replace it with this")
_T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.")
, MB_YESNO, g_script.mFileName) == IDNO)
return 0;
// Otherwise:
reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE;
}
}
if (!reason_to_close_prior && restart_mode)
if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle))
reason_to_close_prior = AHK_EXIT_BY_RELOAD;
if (reason_to_close_prior)
{
// Now that the script has been validated and is ready to run, close the prior instance.
// We wait until now to do this so that the prior instance's "restart" hotkey will still
// be available to use again after the user has fixed the script. UPDATE: We now inform
// the prior instance of why it is being asked to close so that it can make that reason
// available to the OnExit subroutine via a built-in variable:
ASK_INSTANCE_TO_CLOSE(w_existing, reason_to_close_prior);
//PostMessage(w_existing, WM_CLOSE, 0, 0);
// Wait for it to close before we continue, so that it will deinstall any
// hooks and unregister any hotkeys it has:
int interval_count;
for (interval_count = 0; ; ++interval_count)
{
Sleep(50); // No need to use MsgSleep() in this case.
if (!IsWindow(w_existing))
break; // done waiting.
if (interval_count == 100)
{
// This can happen if the previous instance has an OnExit subroutine that takes a long
// time to finish, or if it's waiting for a network drive to timeout or some other
// operation in which it's thread is occupied.
if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO)
return CRITICAL_ERROR;
interval_count = 0;
}
}
// Give it a small amount of additional time to completely terminate, even though
// its main window has already been destroyed:
Sleep(100);
}
// Call this only after closing any existing instance of the program,
// because otherwise the change to the "focus stealing" setting would never be undone:
SetForegroundLockTimeout();
// Create all our windows and the tray icon. This is done after all other chances
// to return early due to an error have passed, above.
if (g_script.CreateWindows() != OK)
return CRITICAL_ERROR;
// At this point, it is nearly certain that the script will be executed.
// v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately
// rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little
// impact on performance given the OS's built-in caching. I looked at the source code for setvbuf()
// and it seems like it should execute very quickly. Code size seems to be about 75 bytes.
setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout.
if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem))))
ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed.
//else leave it NULL as it was initialized in globaldata.
// MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required."
// Therefore, in case it's a high overhead call, it's not done on XP or later:
if (!g_os.IsWinXPorLater())
{
// Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal
// controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll
// 4.70+, must get the function's address dynamically in case the program is running on
// Windows 95/NT without the updated DLL (otherwise the program would not launch at all).
typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX);
MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType)
GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler.
if (MyInitCommonControlsEx)
{
INITCOMMONCONTROLSEX icce;
icce.dwSize = sizeof(INITCOMMONCONTROLSEX);
icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls().
MyInitCommonControlsEx(&icce);
}
else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4.
InitCommonControls();
}
#ifdef CONFIG_DEBUGGER
// Initiate debug session now if applicable.
if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK)
{
g_Debugger.Break();
}
#endif
// set exception filter to disable hook before exception occures to avoid system/mouse freeze
g_ExceptionHandler = AddVectoredExceptionHandler(NULL,DisableHooksOnException);
// Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the
// top part (the auto-execute part) of the script so that they will be in effect even if the
// top part is something that's very involved and requires user interaction:
Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop)
g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp.
Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable.
if (clipboard_var)
// This is done here rather than upon variable creation speed up runtime/dynamic variable creation.
// Since the clipboard can be changed by activity outside the program, don't read-cache its contents.
// Since other applications and the user should see any changes the program makes to the clipboard,
// don't write-cache it either.
clipboard_var->DisableCache();
-
// Run the auto-execute part at the top of the script (this call might never return):
if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort.
return CRITICAL_ERROR;
// REMEMBER: The call above will never return if one of the following happens:
// 1) The AutoExec section never finishes (e.g. infinite loop).
// 2) The AutoExec function uses the Exit or ExitApp command to terminate the script.
// 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit).
// Call it in this special mode to kick off the main event loop.
// Be sure to pass something >0 for the first param or it will
// return (and we never want this to return):
MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES);
return 0; // Never executed; avoids compiler warning.
}
#endif
\ No newline at end of file
diff --git a/source/dllmain.cpp b/source/dllmain.cpp
index 53e6e60..9a37200 100644
--- a/source/dllmain.cpp
+++ b/source/dllmain.cpp
@@ -1,628 +1,629 @@
/*
AutoHotkey
Copyright 2003-2009 Chris Mallett ([email protected])
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "stdafx.h" // pre-compiled headers
#ifdef _USRDLL
#include "globaldata.h" // for access to many global vars
#include "application.h" // for MsgSleep()
#include "window.h" // For MsgBox() & SetForegroundLockTimeout()
#include "TextIO.h"
#include "exports.h" // N11
#include <process.h> // N11
#include <objbase.h> // COM
#include "ComServer_i.h"
#include "ComServer_i.c"
#include <atlbase.h> // CComBSTR
#include "Registry.h"
#include "ComServerImpl.h"
#include "MemoryModule.h"
//#include <string>
// General note:
// The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep().
// The reason for this is that if the keyboard or mouse hook is installed, a straight call
// to Sleep() will cause user keystrokes & mouse events to lag because the message pump
// (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the
// hook functions.
static LPTSTR aDefaultDllScript = _T("#Persistent\n#NoTrayIcon");
static LPTSTR scriptstring;
// Naveen v1. HANDLE hThread
// Todo: move this to struct nameHinstance
static HANDLE hThread;
static struct nameHinstance
{
HINSTANCE hInstanceP;
LPTSTR name ;
LPTSTR argv;
LPTSTR args;
// TCHAR argv[1000];
// TCHAR args[1000];
int istext;
} nameHinstanceP ;
unsigned __stdcall runScript( void* pArguments );
// Naveen v1. DllMain() - puts hInstance into struct nameHinstanceP
// so it can be passed to OldWinMain()
// hInstance is required for script initialization
// probably for window creation
// Todo: better cleanup in DLL_PROCESS_DETACH: windows, variables, no exit from script
BOOL APIENTRY DllMain(HMODULE hInstance,DWORD fwdReason, LPVOID lpvReserved)
{
switch(fwdReason)
{
case DLL_PROCESS_ATTACH:
{
nameHinstanceP.hInstanceP = (HINSTANCE)hInstance;
g_hInstance = (HINSTANCE)hInstance;
g_hMemoryModule = (HMODULE)lpvReserved;
InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x).
InitializeCriticalSection(&g_CriticalHeapBlocks); // used to block memory freeing in case of timeout in ahkTerminate so no corruption happens when both threads try to free Heap.
InitializeCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment.
#ifdef AUTODLL
ahkdll("autoload.ahk", "", ""); // used for remoteinjection of dll
#endif
break;
}
case DLL_THREAD_ATTACH:
{
break;
}
case DLL_PROCESS_DETACH:
{
if (hThread)
{
int lpExitCode = 0;
GetExitCodeThread(hThread,(LPDWORD)&lpExitCode);
if ( lpExitCode == 259 )
CloseHandle( hThread );
}
- DeleteCriticalSection(&g_CriticalHeapBlocks); // g_CriticalHeapBlocks is used in simpleheap for thread-safety.
- DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety.
- DeleteCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment.
+ g_script.~Script();
if (scriptstring)
free(scriptstring);
if (Line::sMaxSourceFiles)
free(Line::sSourceFile);
#ifdef _DEBUG
free(g_Debugger.mStack.mBottom);
#endif
#ifndef MINIDLL
if (g_input.MatchCount)
{
free(g_input.match);
}
if (g_script.mTrayMenu)
g_script.ScriptDeleteMenu(g_script.mTrayMenu);
free(g_KeyHistory);
#endif
+ DeleteCriticalSection(&g_CriticalHeapBlocks); // g_CriticalHeapBlocks is used in simpleheap for thread-safety.
+ DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety.
+ DeleteCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment.
break;
}
case DLL_THREAD_DETACH:
break;
}
return(TRUE); // a FALSE will abort the DLL attach
}
int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
#ifndef MINIDLL
// Lastly (after the above have been initialized), anything that can fail:
if ( !g_script.mTrayMenu && !(g_script.mTrayMenu = g_script.AddMenu(_T("Tray"))) ) // realistically never happens
{
g_script.ScriptError(_T("No tray mem"));
g_script.ExitApp(EXIT_CRITICAL);
}
else
g_script.mTrayMenu->mIncludeStandardItems = true;
#endif
// Init any globals not in "struct g" that need it:
g_MainThreadID = GetCurrentThreadId();
#ifdef _DEBUG
g_hResource = FindResource(g_hInstance, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA));
#else
if (!(g_hResource = FindResource(g_hInstance, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA)))
&& !(g_hResource = FindResource(g_hInstance, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA))))
g_hResource = NULL;
#endif
if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround.
*g_WorkingDir = '\0';
// Unlike the below, the above must not be Malloc'd because the contents can later change to something
// as large as MAX_PATH by means of the SetWorkingDir command.
g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command.
// Set defaults, to be overridden by command line args we receive:
bool restart_mode = false;
LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL;
// The problem of some command line parameters such as /r being "reserved" is a design flaw (one that
// can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled
// scripts because running a script via AutoHotkey.exe should avoid treating anything after the
// filename as switches. This flaw probably occurred because when this part of the program was designed,
// there was no plan to have compiled scripts.
//
// Examine command line args. Rules:
// Any special flags (e.g. /force and /restart) must appear prior to the script filespec.
// The script filespec (if present) must be the first non-backslash arg.
// All args that appear after the filespec are considered to be parameters for the script
// and will be added as variables %1% %2% etc.
// The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters
// unless the filename is explicitly given (shouldn't be an issue for 99.9% of people).
TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%).
Var *var;
bool switch_processing_is_complete = false;
int script_param_num = 1;
int dllargc = 0;
#ifndef _UNICODE
LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR));
MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.args,-1,wargv,(_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR));
LPWSTR *dllargv = CommandLineToArgvW(wargv,&dllargc);
#else
LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.args,&dllargc);
#endif
int i;
if (*nameHinstanceP.args) // Only process if parameters were given
for (i = 0; i < dllargc; ++i) // Start at 1 because 0 contains the program name.
{
#ifndef _UNICODE
param = (TCHAR *) _alloca(wcslen(dllargv[i])+1);
WideCharToMultiByte(CP_ACP,0,dllargv[i],-1,param,(wcslen(dllargv[i])+1),0,0);
#else
param = dllargv[i]; // For performance and convenience.
#endif
if (switch_processing_is_complete) // All args are now considered to be input parameters for the script.
{
if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) )
{
g_Reloading = false;
return CRITICAL_ERROR; // Realistically should never happen.
}
var->Assign(param);
++script_param_num;
}
// Insist that switches be an exact match for the allowed values to cut down on ambiguity.
// For example, if the user runs "CompiledScript.exe /find", we want /find to be considered
// an input parameter for the script rather than a switch:
else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart")))
restart_mode = true;
else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force")))
g_ForceLaunch = true;
else if (!_tcsicmp(param, _T("/ErrorStdOut")))
g_script.mErrorStdOut = true;
else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script.
{
++i; // Consume the next parameter too, because it's associated with this one.
if (i >= dllargc) // Missing the expected filename parameter.
{
g_Reloading = false;
return CRITICAL_ERROR;
}
// For performance and simplicity, open/create the file unconditionally and keep it open until exit.
g_script.mIncludeLibraryFunctionsThenExit = new TextFile;
if (!g_script.mIncludeLibraryFunctionsThenExit->Open(param, TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file.
{
g_Reloading = false;
return CRITICAL_ERROR;
}
}
else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute")))
{
g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0
}
else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn
{
// Default codepage for the script file, NOT the default for commands used by it.
g_DefaultScriptCodepage = ATOU(param + 3);
}
#ifdef CONFIG_DEBUGGER
// Allow a debug session to be initiated by command-line.
else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '='))
{
if (param[6] == '=')
{
param += 7;
LPTSTR c = _tcsrchr(param, ':');
if (c)
{
StringTCharToChar(param, g_DebuggerHost, (int)(c-param));
StringTCharToChar(c + 1, g_DebuggerPort);
}
else
{
StringTCharToChar(param, g_DebuggerHost);
g_DebuggerPort = "9000";
}
}
else
{
g_DebuggerHost = "127.0.0.1";
g_DebuggerPort = "9000";
}
// The actual debug session is initiated after the script is successfully parsed.
}
#endif
else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design).
{
switch_processing_is_complete = true; // No more switches allowed after this point.
--i; // Make the loop process this item again so that it will be treated as a script param.
}
}
LocalFree(dllargv); // free memory allocated by CommandLineToArgvW
// Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero:
if ( !(var = g_script.FindOrAddVar(_T("0"))) )
{
g_Reloading = false;
return CRITICAL_ERROR; // Realistically should never happen.
}
var->Assign(script_param_num - 1);
// N11
Var *A_ScriptOptions;
A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions"),0,VAR_GLOBAL|VAR_SUPER_GLOBAL);
A_ScriptOptions->Assign(nameHinstanceP.argv);
global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts.
// Set up the basics of the script:
if (g_script.Init(*g, script_filespec, restart_mode,hInstance,g_hResource ? 0 : (bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above.
{
g_Reloading = false;
return CRITICAL_ERROR;
}
// Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below,
// never returns, perhaps because it contains an infinite loop (intentional or not):
CopyMemory(&g_default, g, sizeof(global_struct));
//if (nameHinstanceP.istext)
// GetCurrentDirectory(MAX_PATH, g_script.mFileDir);
// Could use CreateMutex() but that seems pointless because we have to discover the
// hWnd of the existing process so that we can close or restart it, so we would have
// to do this check anyway, which serves both purposes. Alt method is this:
// Even if a 2nd instance is run with the /force switch and then a 3rd instance
// is run without it, that 3rd instance should still be blocked because the
// second created a 2nd handle to the mutex that won't be closed until the 2nd
// instance terminates, so it should work ok:
//CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness.
//if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS)
#ifdef AUTOHOTKEYSC
LineNumberType load_result = g_script.LoadFromFile();
#else //HotKeyIt changed to load from Text in dll as well when file does not exist
LineNumberType load_result = (g_hResource || !nameHinstanceP.istext) ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec);
#endif
if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call).
{
g_Reloading = false;
return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it.
}
if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done.
{
g_Reloading = false;
return 0;
}
// Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of
// SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts
// and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16:
#ifndef MINIDLL
if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE)
g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT;
/*
HWND w_existing = NULL;
UserMessages reason_to_close_prior = (UserMessages)0;
if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch)
{
// Note: the title below must be constructed the same was as is done by our
// CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle:
if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle))
{
if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE)
return 0;
if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE)
if (MsgBox(_T("An older instance of this script is already running. Replace it with this")
_T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.")
, MB_YESNO, g_script.mFileName) == IDNO)
return 0;
// Otherwise:
reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE;
}
}
if (!reason_to_close_prior && restart_mode)
if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle))
reason_to_close_prior = AHK_EXIT_BY_RELOAD;
if (reason_to_close_prior)
{
// Now that the script has been validated and is ready to run, close the prior instance.
// We wait until now to do this so that the prior instance's "restart" hotkey will still
// be available to use again after the user has fixed the script. UPDATE: We now inform
// the prior instance of why it is being asked to close so that it can make that reason
// available to the OnExit subroutine via a built-in variable:
terminateDll();
//PostMessage(w_existing, WM_CLOSE, 0, 0);
// Wait for it to close before we continue, so that it will deinstall any
// hooks and unregister any hotkeys it has:
int interval_count;
for (interval_count = 0; ; ++interval_count)
{
Sleep(10); // No need to use MsgSleep() in this case.
if (!IsWindow(w_existing))
break; // done waiting.
if (interval_count == 100)
{
// This can happen if the previous instance has an OnExit subroutine that takes a long
// time to finish, or if it's waiting for a network drive to timeout or some other
// operation in which it's thread is occupied.
if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO)
return CRITICAL_ERROR;
interval_count = 0;
}
}
// Give it a small amount of additional time to completely terminate, even though
// its main window has already been destroyed:
Sleep(100);
}
// Call this only after closing any existing instance of the program,
// because otherwise the change to the "focus stealing" setting would never be undone:
SetForegroundLockTimeout();
*/
#endif
// Create all our windows and the tray icon. This is done after all other chances
// to return early due to an error have passed, above.
if (g_script.CreateWindows() != OK)
{
g_Reloading = false;
return CRITICAL_ERROR;
}
// Set AutoHotkey.dll its main window (ahk_class AutoHotkey) bottom so it does not receive Reload or ExitApp Message send e.g. when Reload message is sent.
SetWindowPos(g_hWnd,HWND_BOTTOM,0,0,0,0,SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOMOVE|SWP_NOREDRAW|SWP_NOSENDCHANGING|SWP_NOSIZE);
// At this point, it is nearly certain that the script will be executed.
// v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately
// rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little
// impact on performance given the OS's built-in caching. I looked at the source code for setvbuf()
// and it seems like it should execute very quickly. Code size seems to be about 75 bytes.
setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout.
#ifndef MINIDLL
if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)realloc(g_KeyHistory,g_MaxHistoryKeys * sizeof(KeyHistoryItem))))
ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed.
//else leave it NULL as it was initialized in globaldata.
#endif
// MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required."
// Therefore, in case it's a high overhead call, it's not done on XP or later:
if (!g_os.IsWinXPorLater())
{
// Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal
// controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll
// 4.70+, must get the function's address dynamically in case the program is running on
// Windows 95/NT without the updated DLL (otherwise the program would not launch at all).
typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX);
MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType)
GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler.
if (MyInitCommonControlsEx)
{
INITCOMMONCONTROLSEX icce;
icce.dwSize = sizeof(INITCOMMONCONTROLSEX);
icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls().
MyInitCommonControlsEx(&icce);
}
else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4.
InitCommonControls();
}
#ifdef CONFIG_DEBUGGER
// Initiate debug session now if applicable.
if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK)
{
g_Debugger.ProcessCommands();
}
#endif
#ifndef MINIDLL
// set exception filter to disable hook before exception occures to avoid system/mouse freeze
// also when dll will crash, it will only exit dll thread and try to destroy it, leaving the exe process running
g_ExceptionHandler = AddVectoredExceptionHandler(NULL,DisableHooksOnException);
// Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the
// top part (the auto-execute part) of the script so that they will be in effect even if the
// top part is something that's very involved and requires user interaction:
Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop)
//Hotkey::InstallKeybdHook();
//Hotkey::InstallMouseHook();
//if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0)
// AddRemoveHooks(3);
#endif
g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp.
Sleep(20);
g_Reloading = false;
//free(nameHinstanceP.name);
Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable.
if (clipboard_var)
// This is done here rather than upon variable creation speed up runtime/dynamic variable creation.
// Since the clipboard can be changed by activity outside the program, don't read-cache its contents.
// Since other applications and the user should see any changes the program makes to the clipboard,
// don't write-cache it either.
clipboard_var->DisableCache();
// Run the auto-execute part at the top of the script (this call might never return):
if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort.
return CRITICAL_ERROR;
// REMEMBER: The call above will never return if one of the following happens:
// 1) The AutoExec section never finishes (e.g. infinite loop).
// 2) The AutoExec function uses the Exit or ExitApp command to terminate the script.
// 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit).
// Call it in this special mode to kick off the main event loop.
// Be sure to pass something >0 for the first param or it will
// return (and we never want this to return):
MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES);
return 0; // Never executed; avoids compiler warning.
}
EXPORT BOOL ahkTerminate(int timeout = 0)
{
DWORD lpExitCode = 0;
if (hThread == 0)
return 0;
g_AllowInterruption = FALSE;
GetExitCodeThread(hThread,(LPDWORD)&lpExitCode);
DWORD tickstart = GetTickCount();
DWORD timetowait = timeout < 0 ? timeout * -1 : timeout;
for (;hThread && g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && (timeout == 0 || timetowait > (GetTickCount()-tickstart));)
{
SendMessageTimeout(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, OK, 0,timeout < 0 ? SMTO_NORMAL : SMTO_NOTIMEOUTIFNOTHUNG,SLEEP_INTERVAL * 3,0);
Sleep(100); // give it a bit time to exit thread
}
if (g_script.mIsReadyToExecute || hThread)
{
g_script.Destroy();
TerminateThread(hThread, (DWORD)EARLY_EXIT);
CloseHandle(hThread);
hThread = NULL;
}
g_AllowInterruption = TRUE;
return 0;
}
// Naveen: v1. runscript() - runs the script in a separate thread compared to host application.
unsigned __stdcall runScript( void* pArguments )
{
OleInitialize(NULL);
int result = OldWinMain(nameHinstanceP.hInstanceP, 0, nameHinstanceP.name, 0);
g_script.Destroy();
_endthreadex( result);
return 0;
}
void WaitIsReadyToExecute()
{
int lpExitCode = 0;
while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259))
{
Sleep(10);
GetExitCodeThread(hThread,(LPDWORD)&lpExitCode);
}
if (!g_script.mIsReadyToExecute)
{
CloseHandle(hThread);
hThread = NULL;
SetLastError(lpExitCode);
}
}
unsigned runThread()
{
if (hThread && g_script.mIsReadyToExecute)
{ // Small check to be done to make sure we do not start a new thread before the old is closed
Sleep(50);
int lpExitCode = 0;
GetExitCodeThread(hThread,(LPDWORD)&lpExitCode);
if ((lpExitCode == 0 || lpExitCode == 259) && g_script.mIsReadyToExecute)
Sleep(50); // make sure the script is not about to be terminated, because this might lead to problems
if (hThread && g_script.mIsReadyToExecute)
ahkTerminate(0);
}
hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, NULL, 0, 0 );
WaitIsReadyToExecute();
return (unsigned int)hThread;
}
int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args)
{
LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR));
if (!newstring)
return 1;
scriptstring = newstring;
_tcscpy(scriptstring,fileName);
_tcscpy(scriptstring + _tcslen(fileName) + 1,argv);
_tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args);
nameHinstanceP.name = scriptstring;
nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ;
nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ;
return 0;
}
EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args)
{
if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T("")))
return 0;
nameHinstanceP.istext = *fileName ? 0 : 1;
return runThread();
}
// HotKeyIt ahktextdll
EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args)
{
if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T("")))
return 0;
nameHinstanceP.istext = 1;
return runThread();
}
void reloadDll()
{
g_script.Destroy();
HANDLE oldhThread = hThread;
hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 );
g_AllowInterruption = TRUE;
CloseHandle(oldhThread);
_endthreadex( (DWORD)EARLY_EXIT );
}
ResultType terminateDll(int aExitCode)
{
g_script.Destroy();
g_AllowInterruption = TRUE;
CloseHandle(hThread);
hThread = NULL;
_endthreadex( (DWORD)aExitCode );
return (ResultType)aExitCode;
}
EXPORT int ahkReload(int timeout = 0)
{
ahkTerminate(timeout);
hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 );
return 0;
}
EXPORT int ahkReady() // HotKeyIt check if dll is ready to execute
{
diff --git a/source/script.cpp b/source/script.cpp
index 5ad23fd..2ef99e9 100644
--- a/source/script.cpp
+++ b/source/script.cpp
@@ -9707,1025 +9707,1035 @@ ResultType Script::DefineClassVars(LPTSTR aBuf, bool aStatic)
else
{
ExprTokenType token;
if (class_object->GetItem(token, _T("__Init")) && token.symbol == SYM_OBJECT
&& (init_func = dynamic_cast<Func *>(token.object))) // This cast SHOULD always succeed; done for maintainability.
{
// __Init method already exists, so find the end of its body.
for (block_end = init_func->mJumpToLine;
block_end->mActionType != ACT_BLOCK_END || !block_end->mAttribute;
block_end = block_end->mNextLine);
}
else
{
// Create an __Init method for this class.
TCHAR def[] = _T("__Init()");
if (!DefineFunc(def, NULL) || !AddLine(ACT_BLOCK_BEGIN)
|| (class_object->Base() && !ParseAndAddLine(_T("base.__Init()"), ACT_EXPRESSION))) // Initialize base-class variables first. Relies on short-circuit evaluation.
return FAIL;
mLastLine->mLineNumber = 0; // Signal the debugger to skip this line while stepping in/over/out.
init_func = g->CurrentFunc;
init_func->mDefaultVarType = VAR_DECLARE_GLOBAL; // Allow global variables/class names in initializer expressions.
if (!AddLine(ACT_BLOCK_END)) // This also resets g->CurrentFunc to NULL.
return FAIL;
block_end = mLastLine;
block_end->mLineNumber = 0; // See above.
// These must be updated as one or both have changed:
script_first_line = mFirstLine;
script_last_line = mLastLine;
}
g->CurrentFunc = init_func; // g->CurrentFunc should be NULL prior to this.
mLastLine = block_end->mPrevLine; // i.e. insert before block_end.
mLastLine->mNextLine = NULL; // For maintainability; AddLine() should overwrite it regardless.
mCurrLine = NULL; // Fix for v1.1.09.02: Leaving this non-NULL at best causes error messages to show irrelevant vicinity lines, and at worst causes a crash because the linked list is in an inconsistent state.
}
if (!ParseAndAddLine(buf, ACT_EXPRESSION))
return FAIL; // Above already displayed the error.
if (aStatic)
{
if (!mFirstStaticLine)
mFirstStaticLine = mLastLine;
mLastStaticLine = mLastLine;
// The following is necessary if there weren't any executable lines above this static
// initializer (i.e. mFirstLine was NULL and has been set to the newly created line):
mFirstLine = script_first_line;
}
else
{
if (init_func->mJumpToLine == block_end) // This can be true only for the first initializer of a class with no base-class.
init_func->mJumpToLine = mLastLine;
// Rejoin the function's block-end (and any lines following it) to the main script.
mLastLine->mNextLine = block_end;
block_end->mPrevLine = mLastLine;
// mFirstLine should be left as it is: if it was NULL, it now contains a pointer to our
// __init function's block-begin, which is now the very first executable line in the script.
g->CurrentFunc = NULL;
}
// Restore mLastLine so that any subsequent script lines are added at the correct point.
mLastLine = script_last_line;
}
return OK;
}
Object *Script::FindClass(LPCTSTR aClassName, size_t aClassNameLength)
{
if (!aClassNameLength)
aClassNameLength = _tcslen(aClassName);
if (!aClassNameLength || aClassNameLength > MAX_CLASS_NAME_LENGTH)
return NULL;
LPTSTR cp, key;
ExprTokenType token;
Object *base_object = NULL;
TCHAR class_name[MAX_CLASS_NAME_LENGTH + 2]; // Extra +1 for '.' to simplify parsing.
// Make temporary copy which we can modify.
tmemcpy(class_name, aClassName, aClassNameLength);
class_name[aClassNameLength] = '.'; // To simplify parsing.
class_name[aClassNameLength + 1] = '\0';
// Get base variable; e.g. "MyClass" in "MyClass.MySubClass".
cp = _tcschr(class_name + 1, '.');
Var *base_var = FindVar(class_name, cp - class_name, NULL, FINDVAR_GLOBAL);
if (!base_var)
return NULL;
// Although at load time only the "Object" type can exist, dynamic_cast is used in case we're called at run-time:
if ( !(base_var->IsObject() && (base_object = dynamic_cast<Object *>(base_var->Object()))) )
return NULL;
// Even if the loop below has no iterations, it initializes 'key' to the appropriate value:
for (key = cp + 1; cp = _tcschr(key, '.'); key = cp + 1) // For each key in something like TypeVar.Key1.Key2.
{
if (cp == key)
return NULL; // ScriptError(_T("Missing name."), cp);
*cp = '\0'; // Terminate at the delimiting dot.
if (!base_object->GetItem(token, key))
return NULL;
base_object = (Object *)token.object; // See comment about Object() above.
}
return base_object;
}
Object *Object::GetUnresolvedClass(LPTSTR &aName)
// This method is only valid for mUnresolvedClass.
{
if (!mFieldCount)
return NULL;
aName = mFields[0].key.s;
return (Object *)mFields[0].object;
}
ResultType Script::ResolveClasses()
{
LPTSTR name;
Object *base = mUnresolvedClasses->GetUnresolvedClass(name);
if (!base)
return OK;
// There is at least one unresolved class.
ExprTokenType token;
if (base->GetItem(token, _T("__Class")))
{
// In this case (an object in the mUnresolvedClasses list), it is always an integer
// containing the file index and line number:
mCurrFileIndex = int(token.value_int64 >> 32);
mCombinedLineNumber = LineNumberType(token.value_int64);
}
mCurrLine = NULL;
return ScriptError(_T("Unknown class."), name);
}
#ifndef AUTOHOTKEYSC
struct FuncLibrary
{
LPTSTR path;
DWORD_PTR length;
};
Func *Script::FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool &aErrorWasShown, bool &aFileWasFound, bool aIsAutoInclude)
// Caller must ensure that aFuncName doesn't already exist as a defined function.
// If aFuncNameLength is 0, the entire length of aFuncName is used.
{
aErrorWasShown = false; // Set default for this output parameter.
aFileWasFound = false;
int i;
LPTSTR char_after_last_backslash, terminate_here;
TCHAR buf[MAX_PATH+1];
DWORD attr;
TextMem tmem;
TextMem::Buffer textbuf(NULL, 0, false);
#define FUNC_LIB_EXT _T(".ahk")
#define FUNC_LIB_EXT_LENGTH (_countof(FUNC_LIB_EXT) - 1)
#define FUNC_LOCAL_LIB _T("\\Lib\\") // Needs leading and trailing backslash.
#define FUNC_LOCAL_LIB_LENGTH (_countof(FUNC_LOCAL_LIB) - 1)
#define FUNC_USER_LIB _T("\\AutoHotkey\\Lib\\") // Needs leading and trailing backslash.
#define FUNC_USER_LIB_LENGTH (_countof(FUNC_USER_LIB) - 1)
#define FUNC_STD_LIB _T("Lib\\") // Needs trailing but not leading backslash.
#define FUNC_STD_LIB_LENGTH (_countof(FUNC_STD_LIB) - 1)
#define FUNC_LIB_COUNT 4
static FuncLibrary sLib[FUNC_LIB_COUNT] = {0};
static LPTSTR winapi;
if (!sLib[0].path) // Allocate & discover paths only upon first use because many scripts won't use anything from the library. This saves a bit of memory and performance.
{
LPVOID aDataBuf;
HRSRC hResInfo = FindResource(g_hInstance, _T("WINAPI"), MAKEINTRESOURCE(10));
DecompressBuffer(LockResource(LoadResource(g_hInstance, hResInfo)), aDataBuf, g_default_pwd);
#ifdef _UNICODE
winapi = UTF8ToWide((LPCSTR)aDataBuf);
#else
winapi = (LPTSTR)aDataBuf;
#endif
for (i = 0; i < FUNC_LIB_COUNT; ++i)
#ifdef _USRDLL
if ( !(sLib[i].path = tmalloc(MAX_PATH)) ) // When dll script is restarted, SimpleHeap is deleted and we don't want to delete static memberst
#else
if ( !(sLib[i].path = (LPTSTR) SimpleHeap::Malloc(MAX_PATH * sizeof(TCHAR))) ) // Need MAX_PATH for to allow room for appending each candidate file/function name.
#endif
return NULL; // Due to rarity, simply pass the failure back to caller.
FuncLibrary *this_lib;
// DETERMINE PATH TO "LOCAL" LIBRARY:
this_lib = sLib; // For convenience and maintainability.
this_lib->length = BIV_ScriptDir(NULL, _T(""));
if (this_lib->length < MAX_PATH-FUNC_LOCAL_LIB_LENGTH)
{
this_lib->length = BIV_ScriptDir(this_lib->path, _T(""));
_tcscpy(this_lib->path + this_lib->length, FUNC_LOCAL_LIB);
this_lib->length += FUNC_LOCAL_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "USER" LIBRARY:
this_lib++; // For convenience and maintainability.
this_lib->length = BIV_MyDocuments(this_lib->path, _T(""));
if (this_lib->length < MAX_PATH-FUNC_USER_LIB_LENGTH)
{
_tcscpy(this_lib->path + this_lib->length, FUNC_USER_LIB);
this_lib->length += FUNC_USER_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "STANDARD" LIBRARY:
this_lib++; // For convenience and maintainability.
GetModuleFileName(NULL, this_lib->path, MAX_PATH); // The full path to the currently-running AutoHotkey.exe.
char_after_last_backslash = 1 + _tcsrchr(this_lib->path, '\\'); // Should always be found, so failure isn't checked.
this_lib->length = (DWORD)(char_after_last_backslash - this_lib->path); // The length up to and including the last backslash.
if (this_lib->length < MAX_PATH-FUNC_STD_LIB_LENGTH)
{
_tcscpy(this_lib->path + this_lib->length, FUNC_STD_LIB);
this_lib->length += FUNC_STD_LIB_LENGTH;
}
else // Insufficient room to build the path name.
{
*this_lib->path = '\0'; // Mark this library as disabled.
this_lib->length = 0; //
}
// DETERMINE PATH TO "AHKPATH\Lib.lnk" LIBRARY:
this_lib++; // For convenience and maintainability.
BIV_AhkPath(this_lib->path, _T(""));
_tcscpy(_tcsrchr(this_lib->path,'\\')+1,_T("Lib.lnk"));
*(_tcsrchr(this_lib->path,'\\')+8) = '\0';
CoInitialize(NULL);
IShellLink *psl;
if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *)&psl)))
{
IPersistFile *ppf;
if (SUCCEEDED(psl->QueryInterface(IID_IPersistFile, (LPVOID *)&ppf)))
{
#ifdef UNICODE
if (SUCCEEDED(ppf->Load(this_lib->path, 0)))
#else
WCHAR wsz[MAX_PATH+1]; // +1 hasn't been explained, but is retained in case it's needed.
ToWideChar(this_lib->path, wsz, MAX_PATH+1); // Dest. size is in wchars, not bytes.
if (SUCCEEDED(ppf->Load((const WCHAR*)wsz, 0)))
#endif
{
TCHAR buf[MAX_PATH+1];
psl->GetPath(buf, MAX_PATH, NULL, SLGP_UNCPRIORITY);
_tcscpy(this_lib->path,buf);
_tcscpy(this_lib->path + _tcslen(buf),_T("\\\0"));
}
ppf->Release();
}
psl->Release();
}
CoUninitialize();
if ( !_tcsrchr(FileAttribToStr(buf, GetFileAttributes(this_lib->path)),'D') )
{
this_lib->length = 0;
*this_lib->path = '\0';
}
else
this_lib->length = _tcslen(this_lib->path);
for (i = 0; i < FUNC_LIB_COUNT; ++i)
{
attr = GetFileAttributes(sLib[i].path); // Seems to accept directories that have a trailing backslash, which is good because it simplifies the code.
if (attr == 0xFFFFFFFF || !(attr & FILE_ATTRIBUTE_DIRECTORY)) // Directory doesn't exist or it's a file vs. directory. Relies on short-circuit boolean order.
{
*sLib[i].path = '\0'; // Mark this library as disabled.
sLib[i].length = 0; //
}
}
}
// Above must ensure that all sLib[].path elements are non-NULL (but they can be "" to indicate "no library").
if (!aFuncNameLength) // Caller didn't specify, so use the entire string.
aFuncNameLength = _tcslen(aFuncName);
TCHAR *dest, *first_underscore, class_name_buf[MAX_VAR_NAME_LENGTH + 1];
LPTSTR naked_filename = aFuncName; // Set up for the first iteration.
size_t naked_filename_length = aFuncNameLength; //
for (int second_iteration = 0; second_iteration < 2; ++second_iteration)
{
for (i = 0; i < FUNC_LIB_COUNT; ++i)
{
if (!*sLib[i].path) // Library is marked disabled, so skip it.
continue;
if (sLib[i].length + naked_filename_length >= MAX_PATH-FUNC_LIB_EXT_LENGTH)
continue; // Path too long to match in this library, but try others.
dest = (LPTSTR) tmemcpy(sLib[i].path + sLib[i].length, naked_filename, naked_filename_length); // Append the filename to the library path.
_tcscpy(dest + naked_filename_length, FUNC_LIB_EXT); // Append the file extension.
attr = GetFileAttributes(sLib[i].path); // Testing confirms that GetFileAttributes() doesn't support wildcards; which is good because we want filenames containing question marks to be "not found" rather than being treated as a match-pattern.
if (attr == 0xFFFFFFFF || (attr & FILE_ATTRIBUTE_DIRECTORY)) // File doesn't exist or it's a directory. Relies on short-circuit boolean order.
continue;
aFileWasFound = true; // Indicate success for #include <lib>, which doesn't necessarily expect a function to be found.
// Since above didn't "continue", a file exists whose name matches that of the requested function.
// Before loading/including that file, set the working directory to its folder so that if it uses
// #Include, it will be able to use more convenient/intuitive relative paths. This is similar to
// the "#Include DirName" feature.
// Call SetWorkingDir() vs. SetCurrentDirectory() so that it succeeds even for a root drive like
// C: that lacks a backslash (see SetWorkingDir() for details).
terminate_here = sLib[i].path + sLib[i].length - 1; // The trailing backslash in the full-path-name to this library.
*terminate_here = '\0'; // Temporarily terminate it for use with SetWorkingDir().
SetWorkingDir(sLib[i].path); // See similar section in the #Include directive.
*terminate_here = '\\'; // Undo the termination.
if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude)
{
// For each auto-included library-file, write out two #Include lines:
// 1) Use #Include in its "change working directory" mode so that any explicit #include directives
// or FileInstalls inside the library file itself will work consistently and properly.
// 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include
// the library file itself.
// We don't directly append library files onto the main script here because:
// 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files
// might contain #Include even though it's rare).
// 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or
// subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they
// wouldn't be properly interleaved/asynchronous, but instead brought out of their library file
// and deposited separately/synchronously into the temp-include file by some new logic at the
// AutoHotkey.exe's code for the #Include directive.
// 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts.
mIncludeLibraryFunctionsThenExit->Format(_T("#Include %-0.*s\n#IncludeAgain %s\n")
, sLib[i].length, sLib[i].path, sLib[i].path);
// Now continue on normally so that our caller can continue looking for syntax errors.
}
// g->CurrentFunc is non-NULL when the function-call being resolved is inside
// a function. Save and reset it for correct behaviour in the include file:
Func *current_func = g->CurrentFunc;
g->CurrentFunc = NULL;
// Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the
// above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written.
if (!LoadIncludedFile(sLib[i].path, false, false)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included).
{
g->CurrentFunc = current_func; // Restore.
aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier.
return NULL;
}
g->CurrentFunc = current_func; // Restore.
// Now that a matching filename has been found, it seems best to stop searching here even if that
// file doesn't actually contain the requested function. This helps library authors catch bugs/typos.
// HotKeyIt, override so resource can be tried too
if (current_func = FindFunc(aFuncName, aFuncNameLength))
return current_func;
continue;
} // for() each library directory.
// Now that the first iteration is done, set up for the second one that searches by class/prefix.
// Notes about ambiguity and naming collisions:
// By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a
// match in a filename that isn't really a class, it seems inconsequential because at worst it will
// still not find the function and will then say "call to nonexistent function". In addition, the
// ability to customize which libraries are searched is planned. This would allow a publicly
// distributed script to turn off all libraries except stdlib.
if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed.
break; // All loops are done because second iteration is the last possible attempt.
naked_filename_length = first_underscore - aFuncName;
if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently).
break; // All loops are done because second iteration is the last possible attempt.
naked_filename = class_name_buf; // Point it to a buffer for use below.
tmemcpy(naked_filename, aFuncName, naked_filename_length);
naked_filename[naked_filename_length] = '\0';
} // 2-iteration for().
// HotKeyIt find library in Resource
// Since above didn't return, no match found in any library.
// Search in Resource for a library
//
// If using dll, first try find function in dll resource, then function + underscore (function_) in dll resource
// If nothing in dll resource is found, search again in main executable.
tmemcpy(class_name_buf, aFuncName, aFuncNameLength);
tmemcpy(class_name_buf + aFuncNameLength,_T(".ahk"),4);
class_name_buf[aFuncNameLength + 4] = '\0';
HRSRC lib_hResource;
BOOL aUseHinstance = true;
if (!(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB"))))
{
// Now that the resource is not found, set up for the second one that searches by class/prefix.
// Notes about ambiguity and naming collisions:
// By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a
// match in a filename that isn't really a class, it seems inconsequential because at worst it will
// still not find the function and will then say "call to nonexistent function". In addition, the
// ability to customize which libraries are searched is planned. This would allow a publicly
// distributed script to turn off all libraries except stdlib.
aUseHinstance = false;
if ( !(lib_hResource = FindResource(NULL, class_name_buf, _T("LIB"))) )
{
if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed.
goto winapi;
else
{
naked_filename_length = first_underscore - aFuncName;
if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently).
return NULL;
tmemcpy(class_name_buf, aFuncName, naked_filename_length);
tmemcpy(class_name_buf + naked_filename_length,_T(".ahk"),4);
class_name_buf[naked_filename_length + 4] = '\0';
if ( !(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB"))) )
{
if ( !(lib_hResource = FindResource(NULL, class_name_buf, _T("LIB"))) )
goto winapi;
}
else
aUseHinstance = true;
}
}
}
// Now a resouce was found and it can be loaded
HGLOBAL hResData;
HINSTANCE ahInstance = aUseHinstance ? g_hInstance : NULL;
if ( !( (textbuf.mLength = SizeofResource(ahInstance, lib_hResource))
&& (hResData = LoadResource(ahInstance, lib_hResource))
&& (textbuf.mBuffer = LockResource(hResData)) ) )
{ // aErrorWasShown = true; // Do not display errors here
goto winapi;
}
if (*(unsigned int*)textbuf.mBuffer == 0x04034b50)
{
LPVOID aDataBuf;
DWORD aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf);
if (aSizeDeCompressed)
{
LPVOID buff = _alloca(aSizeDeCompressed); // will be freed when function returns
memmove(buff,aDataBuf,aSizeDeCompressed);
VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE);
textbuf.mLength = aSizeDeCompressed;
textbuf.mBuffer = buff;
}
}
aFileWasFound = true;
// NOTE: Ahk2Exe strips off the UTF-8 BOM.
LPTSTR resource_script = (LPTSTR)_alloca(textbuf.mLength * sizeof(TCHAR));
tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF8);
tmem.Read(resource_script, textbuf.mLength);
// g->CurrentFunc is non-NULL when the function-call being resolved is inside
// a function. Save and reset it for correct behaviour in the include file:
Func *current_func = g->CurrentFunc;
g->CurrentFunc = NULL;
// Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the
// above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written.
if (!LoadIncludedText(resource_script, class_name_buf)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included).
{
g->CurrentFunc = current_func; // Restore.
aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier.
return NULL;
}
g->CurrentFunc = current_func; // Restore.
return FindFunc(aFuncName, aFuncNameLength);
winapi:
TCHAR parameter[1024] = { L'#', L'D', L'l', L'l', L'I', L'm', L'p', L'o', L'r', L't', L'\\' };
memmove(¶meter[11], aFuncName, aFuncNameLength*sizeof(TCHAR));
parameter[aFuncNameLength + 11] = L',';
parameter[aFuncNameLength + 12] = '\0';
LPTSTR found;
if (found = _tcsstr(winapi, (LPTSTR)¶meter[10]))
{
parameter[10] = L',';
LPTSTR aDest = (LPTSTR)¶meter[aFuncNameLength + 12];
LPTSTR aDllName = _tcsstr(found, _T("\t")) + 1;
size_t aNameLen = _tcsstr(aDllName, _T("\\")) - aDllName + 1;
_tcsncpy(aDest, aDllName, aNameLen);
aDest = aDest + aNameLen;
_tcsncpy(aDest, found + 1, aFuncNameLength + 1);
// Override _ in the end of definition (ahk function like SendMessage, Sleep, Send, SendInput ...
if (*(aFuncName + aFuncNameLength - 1) == '_')
{
*(aDest + aFuncNameLength - 1) = ',';
*(aDest + aFuncNameLength) = '\0';
aDest = aDest + aFuncNameLength;
}
else
{
aDest = aDest + aFuncNameLength + 1;
}
for (found = _tcsstr(found, _T(",")) + 1; *found != L'\\'; found++)
{
if (*found == L'U' || *found == L'u')
{
*aDest = L'U';
aDest++;
continue;
}
- if (*found == L's' || *found == L'S')
+ else if (*found == L'z' || *found == L'Z')
+ {
+#ifdef _UNICODE
+ _tcscpy(aDest, _T("USHORT"));
+ aDest = aDest + 6;
+#else
+ _tcscpy(aDest, _T("UCHAR"));
+ aDest = aDest + 5;
+#endif
+ }
+ else if (*found == L's' || *found == L'S')
{
_tcscpy(aDest, _T("STR"));
aDest = aDest + 3;
}
else if (*found == L't' || *found == L't')
{
_tcscpy(aDest, _T("PTR"));
aDest = aDest + 3;
}
else if (*found == L'a' || *found == L'A')
{
_tcscpy(aDest, _T("ASTR"));
aDest = aDest + 4;
}
else if (*found == L'w' || *found == L'W')
{
_tcscpy(aDest, _T("WSTR"));
aDest = aDest + 4;
}
else if (*found == L'x' || *found == L'X') //TCHAR
{
#ifdef _UNICODE
_tcscpy(aDest, _T("USHORT"));
aDest = aDest + 6;
#else
_tcscpy(aDest, _T("UCHAR"));
aDest = aDest + 5;
#endif
}
else if ((*found == L'i' || *found == L'I') && *(found + 1) == L'6')
{
_tcscpy(aDest, _T("INT64"));
aDest = aDest + 5;
found++;
}
else if (*found == L'i' || *found == L'I')
{
if (*(found + 1) != L'\\' || *(aDest - 1) == 'u' || *(aDest - 1) == 'U')
{ // Not default return type int, no need to define
_tcscpy(aDest, _T("INT"));
aDest = aDest + 3;
}
else // remove last , since no return type is given
{
aDest--;
}
}
else if (*found == L'h' || *found == L'H')
{
_tcscpy(aDest, _T("SHORT"));
aDest = aDest + 5;
}
else if (*found == L'c' || *found == L'C')
{
_tcscpy(aDest, _T("CHAR"));
aDest = aDest + 4;
}
else if (*found == L'f' || *found == L'F')
{
_tcscpy(aDest, _T("FLOAT"));
aDest = aDest + 5;
}
else if (*found == L'd' || *found == L'D')
{
_tcscpy(aDest, _T("DOUBLE"));
aDest = aDest + 6;
}
if (*(found + 1) == L'*' || *(found + 1) == L'p' || *(found + 1) == L'P')
{
*aDest = *found;
aDest++;
}
_tcscpy(aDest, _T(",,"));
aDest = aDest + 2;
}
*(aDest - 2) = L'\0';
LoadDllFunction(_tcschr(parameter, L',') + 1, parameter);
return FindFunc(aFuncName, aFuncNameLength);
}
return NULL;
}
#endif
Func *Script::FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength, int *apInsertPos) // L27: Added apInsertPos for binary-search.
// Returns the Function whose name matches aFuncName (which caller has ensured isn't NULL).
// If it doesn't exist, NULL is returned.
{
if (!aFuncNameLength) // Caller didn't specify, so use the entire string.
aFuncNameLength = _tcslen(aFuncName);
if (apInsertPos) // L27: Set default for maintainability.
*apInsertPos = -1;
// For the below, no error is reported because callers don't want that. Instead, simply return
// NULL to indicate that names that are illegal or too long are not found. If the caller later
// tries to add the function, it will get an error then:
if (aFuncNameLength > MAX_VAR_NAME_LENGTH)
return NULL;
// The following copy is made because it allows the name searching to use _tcsicmp() instead of
// strlicmp(), which close to doubles the performance. The copy includes only the first aVarNameLength
// characters from aVarName:
TCHAR func_name[MAX_VAR_NAME_LENGTH + 1];
tcslcpy(func_name, aFuncName, aFuncNameLength + 1); // +1 to convert length to size.
Func *pfunc;
// Using a binary searchable array vs a linked list speeds up dynamic function calls, on average.
int left, right, mid, result;
for (left = 0, right = mFuncCount - 1; left <= right;)
{
mid = (left + right) / 2;
result = _tcsicmp(func_name, mFunc[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance.
if (result > 0)
left = mid + 1;
else if (result < 0)
right = mid - 1;
else // Match found.
return mFunc[mid];
}
if (apInsertPos)
*apInsertPos = left;
// Since above didn't return, there is no match. See if it's a built-in function that hasn't yet
// been added to the function list.
// Set defaults to be possibly overridden below:
int min_params = 1;
int max_params = 1;
BuiltInFunctionType bif;
LPTSTR suffix = func_name + 3;
#ifndef MINIDLL
if (!_tcsnicmp(func_name, _T("LV_"), 3)) // As a built-in function, LV_* can only be a ListView function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("GetNext")))
{
bif = BIF_LV_GetNextOrCount;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("GetCount")))
{
bif = BIF_LV_GetNextOrCount;
min_params = 0; // But leave max at its default of 1.
}
else if (!_tcsicmp(suffix, _T("GetText")))
{
bif = BIF_LV_GetText;
min_params = 2;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_LV_AddInsertModify;
min_params = 0; // 0 params means append a blank row.
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Insert")))
{
bif = BIF_LV_AddInsertModify;
// Leave min_params at 1. Passing only 1 param to it means "insert a blank row".
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Modify")))
{
bif = BIF_LV_AddInsertModify; // Although it shares the same function with "Insert", it can still have its own min/max params.
min_params = 2;
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
else if (!_tcsicmp(suffix, _T("Delete")))
{
bif = BIF_LV_Delete;
min_params = 0; // Leave max at its default of 1.
}
else if (!_tcsicmp(suffix, _T("InsertCol")))
{
bif = BIF_LV_InsertModifyDeleteCol;
// Leave min_params at 1 because inserting a blank column ahead of the first column
// does not seem useful enough to sacrifice the no-parameter mode, which might have
// potential future uses.
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("ModifyCol")))
{
bif = BIF_LV_InsertModifyDeleteCol;
min_params = 0;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("DeleteCol")))
bif = BIF_LV_InsertModifyDeleteCol; // Leave min/max set to 1.
else if (!_tcsicmp(suffix, _T("SetImageList")))
{
bif = BIF_LV_SetImageList;
max_params = 2; // Leave min at 1.
}
else
return NULL;
}
else if (!_tcsnicmp(func_name, _T("TV_"), 3)) // As a built-in function, TV_* can only be a TreeView function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_TV_AddModifyDelete;
max_params = 3; // Leave min at its default of 1.
}
else if (!_tcsicmp(suffix, _T("Modify")))
{
bif = BIF_TV_AddModifyDelete;
max_params = 3; // One-parameter mode is "select specified item".
}
else if (!_tcsicmp(suffix, _T("Delete")))
{
bif = BIF_TV_AddModifyDelete;
min_params = 0;
}
else if (!_tcsicmp(suffix, _T("GetParent")) || !_tcsicmp(suffix, _T("GetChild")) || !_tcsicmp(suffix, _T("GetPrev")))
bif = BIF_TV_GetRelatedItem;
else if (!_tcsicmp(suffix, _T("GetCount")) || !_tcsicmp(suffix, _T("GetSelection")))
{
bif = BIF_TV_GetRelatedItem;
min_params = 0;
max_params = 0;
}
else if (!_tcsicmp(suffix, _T("GetNext"))) // Unlike "Prev", Next also supports 0 or 2 parameters.
{
bif = BIF_TV_GetRelatedItem;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("Get")) || !_tcsicmp(suffix, _T("GetText")))
{
bif = BIF_TV_Get;
min_params = 2;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("SetImageList")))
{
bif = BIF_TV_SetImageList;
max_params = 2; // Leave min at 1.
}
else
return NULL;
}
else if (!_tcsnicmp(func_name, _T("IL_"), 3)) // It's an ImageList function.
{
suffix = func_name + 3;
if (!_tcsicmp(suffix, _T("Create")))
{
bif = BIF_IL_Create;
min_params = 0;
max_params = 3;
}
else if (!_tcsicmp(suffix, _T("Destroy")))
{
bif = BIF_IL_Destroy; // Leave Min/Max set to 1.
}
else if (!_tcsicmp(suffix, _T("Add")))
{
bif = BIF_IL_Add;
min_params = 2;
max_params = 4;
}
else
return NULL;
}
else if (!_tcsicmp(func_name, _T("SB_SetText")))
{
bif = BIF_StatusBar;
max_params = 3; // Leave min_params at its default of 1.
}
else if (!_tcsicmp(func_name, _T("SB_SetParts")))
{
bif = BIF_StatusBar;
min_params = 0;
max_params = 255; // 255 params allows for up to 256 parts, which is SB's max.
}
else if (!_tcsicmp(func_name, _T("SB_SetIcon")))
{
bif = BIF_StatusBar;
max_params = 3; // Leave min_params at its default of 1.
}
else if (!_tcsicmp(func_name, _T("StrLen")))
#else
if (!_tcsicmp(func_name, _T("StrLen")))
#endif
bif = BIF_StrLen;
else if (!_tcsicmp(func_name, _T("SubStr")))
{
bif = BIF_SubStr;
min_params = 2;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("Struct")))
{
bif = BIF_Struct;
min_params = 1;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("Sizeof")))
{
bif = BIF_sizeof;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("CriticalObject")))
{
bif = BIF_CriticalObject;
min_params = 0;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("Lock")))
{
bif = BIF_Lock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("TryLock")))
{
bif = BIF_TryLock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("UnLock")))
{
bif = BIF_UnLock;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("FindFunc"))) // addFile() Naveen v8.
{
bif = BIF_FindFunc;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("FindLabel"))) // HotKeyIt v1.1.02.00
{
bif = BIF_FindLabel;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("Alias"))) // lowlevel() Naveen v9.
{
bif = BIF_Alias;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("UnZipRawMemory"))) // lowlevel() Naveen v9.
{
bif = BIF_UnZipRawMemory;
min_params = 1;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("getTokenValue"))) // lowlevel() Naveen v9.
{
bif = BIF_getTokenValue;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("CacheEnable"))) // lowlevel() Naveen v9.
{
bif = BIF_CacheEnable;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("Getvar"))) // lowlevel() Naveen v9.
{
bif = BIF_Getvar;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("Trim")) || !_tcsicmp(func_name, _T("LTrim")) || !_tcsicmp(func_name, _T("RTrim"))) // L31
{
bif = BIF_Trim;
min_params = 1;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("InStr")))
{
bif = BIF_InStr;
min_params = 2;
max_params = 5;
}
else if (!_tcsicmp(func_name, _T("RegExMatch")))
{
bif = BIF_RegEx;
min_params = 2;
max_params = 4;
}
else if (!_tcsicmp(func_name, _T("RegExReplace")))
{
bif = BIF_RegEx;
min_params = 2;
max_params = 6;
}
else if (!_tcsicmp(func_name, _T("StrSplit")))
{
bif = BIF_StrSplit;
min_params = 1;
max_params = 3;
}
else if (!_tcsnicmp(func_name, _T("GetKey"), 6))
{
suffix = func_name + 6;
if (!_tcsicmp(suffix, _T("State")))
{
bif = BIF_GetKeyState;
max_params = 2;
}
else if (!_tcsicmp(suffix, _T("Name")) || !_tcsicmp(suffix, _T("VK")) || !_tcsicmp(suffix, _T("SC")))
bif = BIF_GetKeyName;
else
return NULL;
}
else if (!_tcsicmp(func_name, _T("Asc")))
bif = BIF_Asc;
else if (!_tcsicmp(func_name, _T("Chr")))
bif = BIF_Chr;
else if (!_tcsicmp(func_name, _T("StrGet")))
{
bif = BIF_StrGetPut;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("StrPut")))
{
bif = BIF_StrGetPut;
max_params = 4;
}
else if (!_tcsicmp(func_name, _T("NumGet")))
{
bif = BIF_NumGet;
max_params = 3;
}
else if (!_tcsicmp(func_name, _T("NumPut")))
{
bif = BIF_NumPut;
min_params = 2;
max_params = 4;
}
else if (!_tcsicmp(func_name, _T("IsLabel")))
bif = BIF_IsLabel;
else if (!_tcsicmp(func_name, _T("Func")))
bif = BIF_Func;
else if (!_tcsicmp(func_name, _T("IsFunc")))
bif = BIF_IsFunc;
else if (!_tcsicmp(func_name, _T("IsByRef")))
bif = BIF_IsByRef;
#ifdef ENABLE_DLLCALL
else if (!_tcsicmp(func_name, _T("DllCall")))
{
bif = BIF_DllCall;
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
#endif
else if (!_tcsicmp(func_name, _T("ResourceLoadLibrary")))
{
bif = BIF_ResourceLoadLibrary;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("MemoryLoadLibrary")))
{
bif = BIF_MemoryLoadLibrary;
min_params = 1;
max_params = 5;
}
else if (!_tcsicmp(func_name, _T("MemoryGetProcAddress")))
{
bif = BIF_MemoryGetProcAddress;
min_params = 2;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("MemoryFreeLibrary")))
{
bif = BIF_MemoryFreeLibrary;
min_params = 1;
max_params = 1;
}
else if (!_tcsicmp(func_name, _T("MemoryFindResource")))
{
bif = BIF_MemoryFindResource;
min_params = 3;
max_params = 4;
}
else if (!_tcsicmp(func_name, _T("MemorySizeOfResource")))
{
bif = BIF_MemorySizeOfResource;
min_params = 2;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("MemoryLoadResource")))
{
bif = BIF_MemoryLoadResource;
min_params = 2;
max_params = 2;
}
else if (!_tcsicmp(func_name, _T("MemoryLoadString")))
{
bif = BIF_MemoryLoadString;
min_params = 2;
max_params = 5;
}
else if (!_tcsicmp(func_name, _T("DynaCall")))
{
bif = BIF_DynaCall;
min_params = 0;
max_params = 10000; // An arbitrarily high limit that will never realistically be reached.
}
diff --git a/source/script_struct.cpp b/source/script_struct.cpp
index 2c60728..8d888c4 100644
--- a/source/script_struct.cpp
+++ b/source/script_struct.cpp
@@ -1012,899 +1012,899 @@ ResultType STDMETHODCALLTYPE Struct::Invoke(
++name; // ++ to exclude '_' from further consideration.
++aParam; --aParamCount; // Exclude the method identifier. A prior check ensures there was at least one param in this case.
if (!_tcsicmp(name, _T("NewEnum")))
{
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return _NewEnum(aResultToken, aParam, aParamCount);
}
// if first function parameter is a field get it
if (!mTypeOnly && aParamCount && !TokenIsPureNumeric(*aParam[0]))
{
if (field = FindField(TokenToString(*aParam[0])))
{ // exclude parameter in aParam
++aParam; --aParamCount;
}
}
aResultToken.symbol = SYM_INTEGER; // mostly used
aResultToken.value_int64 = 0; // set default
if (!_tcsicmp(name, _T("SetCapacity")))
{ // Set strcuture its capacity or fields capacity
if (!field)
{
if (!aParamCount || !TokenIsPureNumeric(*aParam[0]) || !TokenToInt64(*aParam[0]) || TokenToInt64(*aParam[0]) == 0)
{ // 0 or no parameters were given to free memory
if (mMemAllocated > 0)
{
mMemAllocated = 0;
free(mStructMem);
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (mMemAllocated > 0)
free(mStructMem);
// allocate memory and zero-fill
if (mStructMem = (UINT_PTR*)malloc((size_t)TokenToInt64(*aParam[0])))
{
mMemAllocated = (int)TokenToInt64(*aParam[0]);
memset(mStructMem,NULL,(size_t)mMemAllocated);
aResultToken.value_int64 = mMemAllocated;
}
else
mMemAllocated = 0;
}
else if (aParamCount)
{ // we must have to parmeters here since first parameter is field
if (!TokenIsPureNumeric(*aParam[0]) || !TokenToInt64(*aParam[0]) || TokenToInt64(*aParam[0]) == 0)
{
if (field->mMemAllocated > 0)
{
field->mMemAllocated = 0;
free(field->mStructMem);
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK; // not numeric
}
if (field->mMemAllocated > 0)
free(field->mStructMem);
// allocate memory and zero-fill
if (field->mStructMem = (UINT_PTR*)malloc((size_t)TokenToInt64(*aParam[0])))
{
field->mMemAllocated = (int)TokenToInt64(*aParam[0]);
memset(field->mStructMem,NULL,(size_t)field->mMemAllocated);
*((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)field->mStructMem;
aResultToken.value_int64 = mMemAllocated;
}
else
field->mMemAllocated = 0;
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("GetCapacity")))
{
if (field)
aResultToken.value_int64 = field->mMemAllocated;
else
aResultToken.value_int64 = mMemAllocated;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("Offset")))
{
if (field)
aResultToken.value_int64 = field->mOffset;
else if (aParamCount && TokenIsPureNumeric(*aParam[0]))
// calculate size if item is an array
aResultToken.value_int64 = mSize / (mArraySize ? mArraySize : 1) * (TokenToInt64(*aParam[0])-1);
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("IsPointer")))
{
if (field)
aResultToken.value_int64 = field->mIsPointer;
else
aResultToken.value_int64 = mIsPointer;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("Encoding")))
{
if (field)
aResultToken.value_int64 = field->mEncoding == 65535 ? -1 : field->mEncoding;
else
aResultToken.value_int64 = mEncoding == 65535 ? -1 : mEncoding;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("GetPointer")))
{
if (!field && aParamCount && mIsPointer)
{ // resolve array item
if (mArraySize && TokenIsPureNumeric(*aParam[0]))
aResultToken.value_int64 = *((UINT_PTR*)((UINT_PTR)target + ((mIsPointer ? ptrsize : (mSize/mArraySize)) * (TokenToInt64(*aParam[0])-1))));
else
aResultToken.value_int64 = *target;
}
else if (field)
aResultToken.value_int64 = *((UINT_PTR*)((UINT_PTR)target + field->mOffset));
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("Fill")))
{
if (!field) // only allow to fill main structure
{
if (aParamCount && TokenIsPureNumeric(*aParam[0]))
memset(objclone ? objclone->mStructMem : mStructMem,TokenIsPureNumeric(*aParam[0]),mSize);
else if (aParamCount && *TokenToString(*aParam[0]))
memset(objclone ? objclone->mStructMem : mStructMem,*TokenToString(*aParam[0]),mSize);
else
memset(objclone ? objclone->mStructMem : mStructMem,NULL,mSize);
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("GetAddress")))
{
if (!field)
{
if (mArraySize && aParamCount && TokenIsPureNumeric(*aParam[0]))
aResultToken.value_int64 = (UINT_PTR)target + (mSize / mArraySize * (TokenToInt64(*aParam[0])-1));
else
aResultToken.value_int64 = (UINT_PTR)target;
}
else
aResultToken.value_int64 = (UINT_PTR)target + field->mOffset;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("Size")))
{
if (!field)
{
if (mArraySize && aParamCount && TokenIsPureNumeric(*aParam[0]))
// we do not care which item was requested because all are same size
aResultToken.value_int64 = mSize / mArraySize;
else
aResultToken.value_int64 = mSize;
}
else
aResultToken.value_int64 = field->mSize;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("CountOf")))
{
if (!field)
aResultToken.value_int64 = mArraySize;
else
aResultToken.value_int64 = field->mArraySize;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (!_tcsicmp(name, _T("Clone")) || !_tcsicmp(name, _T("_New")))
{
if (!field)
{
if (!releaseobj) // else we have a clone already
objclone = this->Clone();
}
else
{
Struct* tempobj = objclone;
if (releaseobj) // release object, it is not requred anymore
{
objclone = objclone->CloneField(field);
tempobj->Release();
}
else
objclone = this->CloneField(field);
}
if (aParamCount)
{ // structure pointer and / or init object were given
if (TokenIsPureNumeric(*aParam[0]))
{
objclone->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[0]);
objclone->mMemAllocated = 0;
if (aParamCount > 1 && TokenToObject(*aParam[1]))
objclone->ObjectToStruct(TokenToObject(*aParam[1]));
}
else if (TokenToObject(*aParam[0]))
{
objclone->mStructMem = (UINT_PTR*)malloc(objclone->mSize);
objclone->mMemAllocated = objclone->mSize;
memset(objclone->mStructMem,NULL,objclone->mSize);
objclone->ObjectToStruct(TokenToObject(*aParam[0]));
}
}
else
{
objclone->mStructMem = (UINT_PTR*)malloc(objclone->mSize);
objclone->mMemAllocated = objclone->mSize;
memset(objclone->mStructMem,NULL,objclone->mSize);
}
// small fix for _New to work properly because aThisToken contains the new object
if (!_tcsicmp(name, _T("_New")))
{
if (aThisToken.symbol == SYM_OBJECT)
aThisToken.object->Release();
else
aThisToken.symbol = SYM_OBJECT;
aThisToken.object = objclone;
objclone->AddRef();
}
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = objclone;
if (deletefield) // we created the field from a structure
delete field;
// do not release objclone because it is returned
return OK;
}
// For maintainability: explicitly return since above has done ++aParam, --aParamCount.
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
aResultToken.symbol = SYM_STRING;
aResultToken.marker = _T(""); // identify that method was not found
return INVOKE_NOT_HANDLED;
}
else if (!field)
{ // field was not found
if (releaseobj)
objclone->Release();
return INVOKE_NOT_HANDLED;
}
// MULTIPARAM[x,y] -- may be SET[x,y]:=z or GET[x,y], but always treated like GET[x].
else if (param_count_excluding_rvalue > 1)
{ // second parameter = "", so caller wants get/set field pointer
if (TokenIsEmptyString(*aParam[1]))
{
aResultToken.symbol = SYM_INTEGER;
if (IS_INVOKE_SET)
{
if (param_count_excluding_rvalue < 3)
{ // set simple pointer
*((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)TokenToInt64(*aParam[2]);
aResultToken.value_int64 = (UINT_PTR)*(target + field->mOffset);
}
else // set pointer to pointer
{
UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + field->mOffset));
for (int i = param_count_excluding_rvalue - 2;i && aDeepPointer;i--)
aDeepPointer = (UINT_PTR*)*aDeepPointer;
*aDeepPointer = (UINT_PTR)TokenToInt64(*aParam[aParamCount]);
aResultToken.value_int64 = *aDeepPointer;
}
}
else // GET pointer
{
if (param_count_excluding_rvalue < 3)
aResultToken.value_int64 = (mIsPointer ? *target : (UINT_PTR)target) + field->mOffset;
else
{ // get pointer to pointer
UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + field->mOffset));
for (int i = param_count_excluding_rvalue - 2;i && *aDeepPointer;i--)
aDeepPointer = (UINT_PTR*)*aDeepPointer;
aResultToken.value_int64 = (__int64)aDeepPointer;
}
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
else // clone field to object and invoke again
{
if (releaseobj)
objclone->Release();
objclone = CloneField(field,true);
/*
if (!field->mArraySize && field->mIsPointer)
{
objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset));
//objclone->mIsPointer--;
if (--objclone->mIsPointer) // it is a pointer to array of pointers, set mArraySize to 1 to identify an array
objclone->mArraySize = 1;
}
else
objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[1])-1)*(field->mIsPointer ? ptrsize : field->mSize));
*/
objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + field->mOffset);
objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1);
objclone->Release();
if (deletefield) // we created the field from a structure
delete field;
return OK;
}
} // MULTIPARAM[x,y] x[y]
// SET
else if (IS_INVOKE_SET)
{
if (field->mVarRef && TokenToObject(*aParam[1]))
{ // field is a structure, assign objct to structure
if (releaseobj)
objclone->Release();
objclone = this->CloneField(field,true);
objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + field->mOffset);
objclone->ObjectToStruct(TokenToObject(*aParam[1]));
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = objclone;
return OK;
}
if (mIsPointer && objclone == NULL)
{ // resolve pointer
for (int i = mIsPointer;i;i--)
target = (UINT_PTR*)*target;
}
else if (objclone && objclone->mIsPointer)
{ // resolve pointer for objclone
for (int i = objclone->mIsPointer;i;i--)
target = (UINT_PTR*)*target;
}
if (field->mIsPointer)
{ // field is a pointer, clone to structure and invoke again
if (releaseobj)
objclone->Release();
objclone = this->CloneField(field,true);
objclone->mIsPointer--;
objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset));
objclone->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount);
objclone->Release();
return OK;
}
// StrPut (code stolen from BIF_StrPut())
if (field->mEncoding != 65535)
{ // field is [T|W|U]CHAR or LP[TC]STR, set get character or string
source_string = (LPCVOID)TokenToString(*aParam[1], aResultToken.buf);
source_length = (int)((aParam[1]->symbol == SYM_VAR) ? aParam[1]->var->CharLength() : _tcslen((LPCTSTR)source_string));
if (!source_length)
{ // Take a shortcut when source_string is empty, since some paths below might not handle it correctly.
if (field->mSize > 2 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset))) // no memory allocated, don't allocate just return
{
aResultToken.value_int64 = 0;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (field->mEncoding == CP_UTF16)
*(LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)) = '\0';
else
*(LPSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)) = '\0';
aResultToken.value_int64 = 1;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return g_script.ScriptError(ERR_MUST_INIT_STRUCT);
}
if (field->mSize > 2) // not [T|W|U]CHAR
source_length++; // for terminating character
if (field->mSize > 2 && (!target || !*((UINT_PTR*)((UINT_PTR)target + field->mOffset)) || (field->mMemAllocated > 0 && (field->mMemAllocated < ((source_length + 1) * (int)(field->mEncoding == 1200 ? sizeof(WCHAR) : sizeof(CHAR)))))))
{ // no memory allocated yet, allocate now
if (field->mMemAllocated == -1 && (!target || !*((UINT_PTR*)((UINT_PTR)target + field->mOffset)))){
if (deletefield) // we created the field from a structure so no memory can be allocated
delete field;
if (releaseobj)
objclone->Release();
return g_script.ScriptError(ERR_MUST_INIT_STRUCT);
}
else if (field->mMemAllocated > 0) // free previously allocated memory
free(field->mStructMem);
field->mMemAllocated = (source_length + 1) * (field->mEncoding == 1200 ? sizeof(WCHAR) : sizeof(CHAR)); // + 1 for terminating character
field->mStructMem = (UINT_PTR*)malloc(field->mMemAllocated);
*((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)field->mStructMem;
}
if (field->mEncoding == UorA(CP_UTF16, CP_ACP))
tmemcpy((LPTSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), (LPTSTR)source_string, field->mSize < 4 ? 1 : source_length);
else
{
// Conversion is required. For Unicode builds, this means encoding != CP_UTF16;
#ifndef UNICODE // therefore, this section is relevant only to ANSI builds:
if (field->mEncoding == CP_UTF16)
{
// See similar section below for comments.
char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, NULL, 0);
if (!char_count)
{
aResultToken.value_int64 = char_count;
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (field->mSize > 2) // Not TCHAR or CHAR or WCHAR
++char_count; // + 1 for null-terminator (source_length causes it to be excluded from char_count).
length = char_count;
char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, (LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length);
if (field->mSize > 2 && char_count && char_count < length)
((LPWSTR)*(UINT_PTR*)((UINT_PTR)target + field->mOffset))[char_count] = '\0';
}
else // encoding != CP_UTF16
{
// Convert native ANSI string to UTF-16 first.
CStringWCharFromChar wide_buf((LPCSTR)source_string, source_length, CP_ACP);
source_string = wide_buf.GetString();
source_length = wide_buf.GetLength();
#endif
char_count = WideCharToMultiByte(field->mEncoding, WC_NO_BEST_FIT_CHARS, (LPCWSTR)source_string, source_length, NULL, 0, NULL, NULL);
if (!char_count) // Above has ensured source is not empty, so this must be an error.
{
if (GetLastError() == ERROR_INVALID_FLAGS)
{
// Try again without flags. MSDN lists a number of code pages for which flags must be 0, including UTF-7 and UTF-8 (but UTF-8 is handled above).
flags = 0; // Must be set for this call and the call further below.
char_count = WideCharToMultiByte(field->mEncoding, flags, (LPCWSTR)source_string, source_length, NULL, 0, NULL, NULL);
}
if (!char_count)
{
aResultToken.symbol = SYM_STRING;
aResultToken.marker = _T("");
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
}
// Assume there is sufficient buffer space and hope for the best:
length = char_count;
// Convert to target encoding.
char_count = WideCharToMultiByte(field->mEncoding, flags, (LPCWSTR)source_string, source_length, (LPSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), char_count, NULL, NULL);
// Since above did not null-terminate, check for buffer space and null-terminate if there's room.
// It is tempting to always null-terminate (potentially replacing the last byte of data),
// but that would exclude this function as a means to copy a string into a fixed-length array.
if (field->mSize > 2 && char_count && char_count < length) // NOT TCHAR or CHAR or WCHAR
((LPSTR)*(UINT_PTR*)((UINT_PTR)target + field->mOffset))[char_count] = '\0';
#ifndef UNICODE
}
#endif
}
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = char_count;
}
else // NumPut
{ // code stolen from BIF_NumPut
switch(field->mSize)
{
case 4: // Listed first for performance.
if (field->mIsInteger)
{
*((unsigned int *)((UINT_PTR)target + field->mOffset)) = (unsigned int)TokenToInt64(*aParam[1]);
aResultToken.symbol = SYM_INTEGER;
- aResultToken.value_int64 = TokenToInt64(*aParam[1]);
+ aResultToken.value_int64 = *((unsigned int *)((UINT_PTR)target + field->mOffset));
}
else // Float (32-bit).
{
*((float *)((UINT_PTR)target + field->mOffset)) = (float)TokenToDouble(*aParam[1]);
aResultToken.symbol = SYM_FLOAT;
- aResultToken.value_double = TokenToDouble(*aParam[1]);
+ aResultToken.value_double = *((float *)((UINT_PTR)target + field->mOffset));
}
break;
case 8:
if (field->mIsInteger)
{
// v1.0.48: Support unsigned 64-bit integers like DllCall does:
*((__int64 *)((UINT_PTR)target + field->mOffset)) = (field->mIsUnsigned && !IS_NUMERIC(aParam[1]->symbol)) // Must not be numeric because those are already signed values, so should be written out as signed so that whoever uses them can interpret negatives as large unsigned values.
? (__int64)ATOU64(TokenToString(*aParam[1])) // For comments, search for ATOU64 in BIF_DllCall().
: TokenToInt64(*aParam[1]);
aResultToken.symbol = SYM_INTEGER;
aResultToken.value_int64 = TokenToInt64(*aParam[1]);
}
else // Double (64-bit).
{
*((double *)((UINT_PTR)target + field->mOffset)) = TokenToDouble(*aParam[1]);
aResultToken.symbol = SYM_FLOAT;
- aResultToken.value_double = TokenToDouble(*aParam[1]);
+ aResultToken.value_double = *((double *)((UINT_PTR)target + field->mOffset));
}
break;
case 2:
*((unsigned short *)((UINT_PTR)target + field->mOffset)) = (unsigned short)TokenToInt64(*aParam[1]);
aResultToken.symbol = SYM_INTEGER;
- aResultToken.value_int64 = TokenToInt64(*aParam[1]);
+ aResultToken.value_int64 = *((unsigned short *)((UINT_PTR)target + field->mOffset));
break;
default: // size 1
*((unsigned char *)((UINT_PTR)target + field->mOffset)) = (unsigned char)TokenToInt64(*aParam[1]);
aResultToken.symbol = SYM_INTEGER;
- aResultToken.value_int64 = TokenToInt64(*aParam[1]);
+ aResultToken.value_int64 = *((unsigned char *)((UINT_PTR)target + field->mOffset));
}
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
// GET
else if (field)
{
if (field->mArraySize || field->mVarRef)
{ // filed is an array or variable reference, return a structure object.
if (field->mArraySize || field->mIsPointer)
{ // field is array or a pointer to variable
objclone = CloneField(field,true);
objclone->mStructMem = (UINT_PTR *)((UINT_PTR)target + field->mOffset);
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = objclone;
}
else // field is refference to a variable and not pointer, create structure
{
Var1.symbol = SYM_STRING;
Var2.symbol = SYM_VAR;
Var2.var = field->mVarRef;
if (TokenToObject(Var2))
{ // Variable is a structure object
objclone = ((Struct *)TokenToObject(Var2))->Clone(true);
objclone->mStructMem = (UINT_PTR *)((UINT_PTR)target + (UINT_PTR)field->mOffset);
aResultToken.object = objclone;
aResultToken.symbol = SYM_OBJECT;
}
else // Variable is a string definition
{
Var1.marker = TokenToString(Var2);
Var2.symbol = SYM_INTEGER;
Var2.value_int64 = field->mIsPointer ? *(UINT_PTR*)((UINT_PTR)target + field->mOffset) : (UINT_PTR)((UINT_PTR)target + field->mOffset);
if (objclone = Struct::Create(param,2))
{ // create and clone object because it is created dynamically
Struct *tempobj = objclone;
objclone = objclone->Clone(true);
objclone->mStructMem = tempobj->mStructMem;
tempobj->Release();
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = objclone;
}
}
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (mIsPointer && objclone == NULL)
{ // resolve pointer of main structure
for (int i = mIsPointer;i;i--)
target = (UINT_PTR*)*target;
}
else if (objclone && objclone->mIsPointer)
{ // resolve pointer for objclone
for (int i = objclone->mIsPointer;i;i--)
target = (UINT_PTR*)*target;
}
if (field->mIsPointer)
{ // field is a pointer we need to return an object
if (releaseobj)
objclone->Release();
objclone = this->CloneField(field,true);
objclone->mIsPointer--;
objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset));
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = objclone;
return OK;
}
// StrGet (code stolen from BIF_StrGet())
if (field->mEncoding != 65535)
{
if (field->mEncoding != UorA(CP_UTF16, CP_ACP))
{
// Conversion is required.
int conv_length;
if (field->mSize < 4) // TCHAR or CHAR or WCHAR
length = 1;
#ifdef UNICODE
// Convert multi-byte encoded string to UTF-16.
conv_length = MultiByteToWideChar(field->mEncoding, 0, (LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, NULL, 0);
if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator.
{
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
conv_length = MultiByteToWideChar(field->mEncoding, 0, (LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, aResultToken.marker, conv_length);
#else
CStringW wide_buf;
// If the target string is not UTF-16, convert it to that first.
if (field->mEncoding != CP_UTF16)
{
StringCharToWChar((LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), wide_buf, length, field->mEncoding);
(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : *(UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)wide_buf.GetString();
length = wide_buf.GetLength();
}
// Now convert UTF-16 to ACP.
conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, NULL, 0, NULL, NULL);
if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator.
{
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK; // Out of memory.
}
conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, aResultToken.marker, conv_length, NULL, NULL);
#endif
if (conv_length && !aResultToken.marker[conv_length - 1])
--conv_length; // Exclude null-terminator.
else
aResultToken.marker[conv_length] = '\0';
aResultToken.marker_length = conv_length; // Update this in case TokenSetResult used mem_to_free.
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
else // no conversation required
{
if (field->mSize > 2 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset)))
{
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
aResultToken.symbol = SYM_STRING;
if (!TokenSetResult(aResultToken, (LPCTSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)),field->mSize < 4 ? 1 : -1))
aResultToken.marker = _T("");
}
aResultToken.symbol = SYM_STRING;
}
else // NumGet (code stolen from BIF_NumGet())
{
switch(field->mSize)
{
case 4: // Listed first for performance.
if (!field->mIsInteger)
{
aResultToken.value_double = *((float *)((UINT_PTR)target + field->mOffset));
aResultToken.symbol = SYM_FLOAT;
}
else if (!field->mIsUnsigned)
{
aResultToken.value_int64 = *((int *)((UINT_PTR)target + field->mOffset)); // aResultToken.symbol was set to SYM_FLOAT or SYM_INTEGER higher above.
aResultToken.symbol = SYM_INTEGER;
}
else
{
aResultToken.value_int64 = *((unsigned int *)((UINT_PTR)target + field->mOffset));
aResultToken.symbol = SYM_INTEGER;
}
break;
case 8:
// The below correctly copies both DOUBLE and INT64 into the union.
// Unsigned 64-bit integers aren't supported because variables/expressions can't support them.
aResultToken.value_int64 = *((__int64 *)((UINT_PTR)target + field->mOffset));
if (!field->mIsInteger)
aResultToken.symbol = SYM_FLOAT;
else
aResultToken.symbol = SYM_INTEGER;
break;
case 2:
if (!field->mIsUnsigned) // Don't use ternary because that messes up type-casting.
aResultToken.value_int64 = *((short *)((UINT_PTR)target + field->mOffset));
else
aResultToken.value_int64 = *((unsigned short *)((UINT_PTR)target + field->mOffset));
aResultToken.symbol = SYM_INTEGER;
break;
default: // size 1
if (!field->mIsUnsigned) // Don't use ternary because that messes up type-casting.
aResultToken.value_int64 = *((char *)((UINT_PTR)target + field->mOffset));
else
aResultToken.value_int64 = *((unsigned char *)((UINT_PTR)target + field->mOffset));
aResultToken.symbol = SYM_INTEGER;
}
}
if (deletefield) // we created the field from a structure
delete field;
if (releaseobj)
objclone->Release();
return OK;
}
if (releaseobj)
objclone->Release();
return INVOKE_NOT_HANDLED;
}
//
// Struct:: Internal Methods
//
Struct::FieldType *Struct::FindField(LPTSTR val)
{
for (int i = 0;i < mFieldCount;i++)
{
FieldType &field = mFields[i];
if (!_tcsicmp(field.key,val))
return &field;
}
return NULL;
}
bool Struct::SetInternalCapacity(IndexType new_capacity)
// Expands mFields to the specified number if fields.
// Caller *must* ensure new_capacity >= 1 && new_capacity >= mFieldCount.
{
FieldType *new_fields = (FieldType *)realloc(mFields, new_capacity * sizeof(FieldType));
if (!new_fields)
return false;
mFields = new_fields;
mFieldCountMax = new_capacity;
return true;
}
ResultType Struct::_NewEnum(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount)
{
if (aParamCount == 0)
{
IObject *newenum;
if (newenum = new Enumerator(this))
{
aResultToken.symbol = SYM_OBJECT;
aResultToken.object = newenum;
}
}
return OK;
}
int Struct::Enumerator::Next(Var *aKey, Var *aVal)
{
if (++mOffset < mObject->mFieldCount)
{
FieldType &field = mObject->mFields[mOffset];
if (aKey)
aKey->Assign(field.key);
if (aVal)
{ // We need to invoke the structure to retrieve the value
ExprTokenType aResultToken;
// not sure about the buffer
TCHAR buf[MAX_PATH];
aResultToken.buf = buf;
ExprTokenType aThisToken;
aThisToken.symbol = SYM_OBJECT;
aThisToken.object = mObject;
ExprTokenType *aVarToken = new ExprTokenType();
aVarToken->symbol = SYM_STRING;
aVarToken->marker = field.key;
mObject->Invoke(aResultToken,aThisToken,0,&aVarToken,1);
switch (aResultToken.symbol)
{
case SYM_STRING: aVal->AssignString(aResultToken.marker); break;
case SYM_INTEGER: aVal->Assign(aResultToken.value_int64); break;
case SYM_FLOAT: aVal->Assign(aResultToken.value_double); break;
case SYM_OBJECT: aVal->Assign(aResultToken.object); break;
}
delete aVarToken;
}
return true;
}
else if (mOffset < mObject->mArraySize)
{ // structure is an array
if (aKey)
aKey->Assign(mOffset + 1); // mOffset starts at 1
if (aVal)
{ // again we need to invoke structure to retrieve the value
ExprTokenType aResultToken;
TCHAR buf[MAX_PATH];
aResultToken.buf = buf;
ExprTokenType aThisToken;
aThisToken.symbol = SYM_OBJECT;
aThisToken.object = mObject;
ExprTokenType *aVarToken = new ExprTokenType();
aVarToken->symbol = SYM_INTEGER;
aVarToken->value_int64 = mOffset + 1; // mOffset starts at 1
mObject->Invoke(aResultToken,aThisToken,0,&aVarToken,1);
switch (aResultToken.symbol)
{
case SYM_STRING: aVal->AssignString(aResultToken.marker); break;
case SYM_INTEGER: aVal->Assign(aResultToken.value_int64); break;
case SYM_FLOAT: aVal->Assign(aResultToken.value_double); break;
case SYM_OBJECT: aVal->Assign(aResultToken.object); break;
}
delete aVarToken;
}
return true;
}
return false;
}
Struct::FieldType *Struct::Insert(LPTSTR key, IndexType at,UCHAR aIspointer,int aOffset,int aArrsize,Var *variableref,int aFieldsize,bool aIsinteger,bool aIsunsigned,USHORT aEncoding)
// Inserts a single field with the given key at the given offset.
// Caller must ensure 'at' is the correct offset for this key.
{
if (!*key)
{
// empty key = only type was given so assign all to structure object
// do not assign size here since it will be assigned in StructCreate later
mArraySize = aArrsize;
mIsPointer = aIspointer;
mIsInteger = aIsinteger;
mIsUnsigned = aIsunsigned;
mEncoding = aEncoding;
mVarRef = variableref;
return (FieldType*)true;
}
if (mFieldCount == mFieldCountMax && !Expand() // Attempt to expand if at capacity.
|| !(key = _tcsdup(key))) // Attempt to duplicate key-string.
{ // Out of memory.
return NULL;
}
// There is now definitely room in mFields for a new field.
FieldType &field = mFields[at];
if (at < mFieldCount)
// Move existing fields to make room.
memmove(&field + 1, &field, (mFieldCount - at) * sizeof(FieldType));
++mFieldCount; // Only after memmove above.
// Update key-type offsets based on where and what was inserted; also update this key's ref count:
field.mSize = aFieldsize; // Init to ensure safe behaviour in Assign().
field.key = key; // Above has already copied string
field.mArraySize = aArrsize;
field.mIsPointer = aIspointer;
field.mOffset = aOffset;
field.mIsInteger = aIsinteger;
field.mIsUnsigned = aIsunsigned;
field.mEncoding = aEncoding;
field.mVarRef = variableref;
field.mMemAllocated = 0;
return &field;
}
|
tinku99/ahkdll
|
9f19362b0afac35fa2b1a9137fa7ef821ebbca04
|
Deleted and added some WinApi functions
|
diff --git a/source/resources/WINAPI.zip b/source/resources/WINAPI.zip
index 6f2a4fc..b4cea80 100644
Binary files a/source/resources/WINAPI.zip and b/source/resources/WINAPI.zip differ
|
tinku99/ahkdll
|
862e300e4e9bb41d2361e9837c421c5b59ab6df2
|
Show only first line of file in ListLines for ahkdll
|
diff --git a/source/script.cpp b/source/script.cpp
index 0118def..5ad23fd 100644
--- a/source/script.cpp
+++ b/source/script.cpp
@@ -17995,1686 +17995,1750 @@ __forceinline ResultType Line::Perform() // As of 2/9/2009, __forceinline() redu
g.IntervalBeforeRest = -1; // Disable the new method in favor of the old one below:
// This value is signed 64-bits to support variable reference (i.e. containing a large int)
// the user might throw at it:
if ( !(g.LinesPerCycle = ArgToInt64(1)) )
// Don't interpret zero as "infinite" because zero can accidentally
// occur if the dereferenced var was blank:
g.LinesPerCycle = 10; // The old default, which is retained for compatibility with existing scripts.
}
return OK;
case ACT_SETSTORECAPSLOCKMODE:
if ( (toggle = ConvertOnOff(ARG1, NEUTRAL)) != NEUTRAL )
g.StoreCapslockMode = (toggle == TOGGLED_ON);
return OK;
case ACT_SETTITLEMATCHMODE:
switch (ConvertTitleMatchMode(ARG1))
{
case FIND_IN_LEADING_PART: g.TitleMatchMode = FIND_IN_LEADING_PART; return OK;
case FIND_ANYWHERE: g.TitleMatchMode = FIND_ANYWHERE; return OK;
case FIND_REGEX: g.TitleMatchMode = FIND_REGEX; return OK;
case FIND_EXACT: g.TitleMatchMode = FIND_EXACT; return OK;
case FIND_FAST: g.TitleFindFast = true; return OK;
case FIND_SLOW: g.TitleFindFast = false; return OK;
}
return LineError(ERR_PARAM1_INVALID, FAIL, ARG1);
case ACT_SETFORMAT:
// For now, it doesn't seem necessary to have runtime validation of the first parameter.
// Just ignore the command if it's not valid:
if (!_tcsnicmp(ARG1, _T("Float"), 5)) // "nicmp" vs. "icmp" so that Float and FloatFast are treated the same (loadtime validation already took notice of the Fast flag).
{
// -2 to allow room for the letter 'f' and the '%' that will be added:
if (ArgLength(2) >= _countof(g.FormatFloat) - 2) // A variable that resolved to something too long.
return OK; // Seems best not to bother with a runtime error for something so rare.
// Make sure the formatted string wouldn't exceed the buffer size:
__int64 width = ArgToInt64(2);
LPTSTR dot_pos = _tcschr(ARG2, '.');
__int64 precision = dot_pos ? ATOI64(dot_pos + 1) : 0;
if (width + precision + 2 > MAX_NUMBER_LENGTH) // +2 to allow room for decimal point itself and leading minus sign.
return OK; // Don't change it.
// Create as "%ARG2f". Note that %f can handle doubles in MSVC++:
_stprintf(g.FormatFloat, _T("%%%s%s%s"), ARG2
, dot_pos ? _T("") : _T(".") // Add a dot if none was specified so that "0" is the same as "0.", which seems like the most user-friendly approach; it's also easier to document in the help file.
, IsPureNumeric(ARG2, true, true, true) ? _T("f") : _T("")); // If it's not pure numeric, assume the user already included the desired letter (e.g. SetFormat, Float, 0.6e).
}
else if (!_tcsnicmp(ARG1, _T("Integer"), 7)) // "nicmp" vs. "icmp" so that Integer and IntegerFast are treated the same (loadtime validation already took notice of the Fast flag).
{
switch(*ARG2)
{
case 'd':
case 'D':
g.FormatInt = 'D';
break;
case 'h':
case 'H':
g.FormatInt = (char) *ARG2;
break;
// Otherwise, since the first letter isn't recognized, do nothing since 99% of the time such a
// probably would be caught at load-time.
}
}
// Otherwise, ignore invalid type at runtime since 99% of the time it would be caught at load-time:
return OK;
case ACT_FORMATTIME:
return FormatTime(ARG2, ARG3);
#ifndef MINIDLL
case ACT_MENU:
return g_script.PerformMenu(SIX_ARGS); // L17: Changed from FIVE_ARGS to access previously "reserved" arg (for use by Menu,,Icon).
case ACT_GUI:
return g_script.PerformGui(FOUR_ARGS);
case ACT_GUICONTROL:
return GuiControl(THREE_ARGS);
case ACT_GUICONTROLGET:
return GuiControlGet(ARG2, ARG3, ARG4);
////////////////////////////////////////////////////////////////////////////////////////
// For these, it seems best not to report an error during runtime if there's
// an invalid value (e.g. something other than On/Off/Blank) in a param containing
// a dereferenced variable, since settings are global and affect all subroutines,
// not just the one that we would otherwise report failure for:
case ACT_SUSPEND:
switch (ConvertOnOffTogglePermit(ARG1))
{
case NEUTRAL:
case TOGGLE:
ToggleSuspendState();
break;
case TOGGLED_ON:
if (!g_IsSuspended)
ToggleSuspendState();
break;
case TOGGLED_OFF:
if (g_IsSuspended)
ToggleSuspendState();
break;
case TOGGLE_PERMIT:
// In this case do nothing. The user is just using this command as a flag to indicate that
// this subroutine should not be suspended.
break;
// We know it's a variable because otherwise the loading validation would have caught it earlier:
case TOGGLE_INVALID:
return LineError(ERR_PARAM1_INVALID, FAIL, ARG1);
}
return OK;
#endif //MINIDLL
case ACT_PAUSE:
return ChangePauseState(ConvertOnOffToggle(ARG1), (bool)ArgToInt(2));
case ACT_AUTOTRIM:
if ( (toggle = ConvertOnOff(ARG1, NEUTRAL)) != NEUTRAL )
g.AutoTrim = (toggle == TOGGLED_ON);
return OK;
case ACT_STRINGCASESENSE:
if ((g.StringCaseSense = ConvertStringCaseSense(ARG1)) == SCS_INVALID)
g.StringCaseSense = SCS_INSENSITIVE; // For simplicity, just fall back to default if value is invalid (normally its caught at load-time; only rarely here).
return OK;
case ACT_DETECTHIDDENWINDOWS:
if ( (toggle = ConvertOnOff(ARG1, NEUTRAL)) != NEUTRAL )
g.DetectHiddenWindows = (toggle == TOGGLED_ON);
return OK;
case ACT_DETECTHIDDENTEXT:
if ( (toggle = ConvertOnOff(ARG1, NEUTRAL)) != NEUTRAL )
g.DetectHiddenText = (toggle == TOGGLED_ON);
return OK;
case ACT_BLOCKINPUT:
switch (toggle = ConvertBlockInput(ARG1))
{
case TOGGLED_ON:
ScriptBlockInput(true);
break;
case TOGGLED_OFF:
ScriptBlockInput(false);
break;
case TOGGLE_SEND:
case TOGGLE_MOUSE:
case TOGGLE_SENDANDMOUSE:
case TOGGLE_DEFAULT:
g_BlockInputMode = toggle;
break;
#ifndef MINIDLL
case TOGGLE_MOUSEMOVE:
g_BlockMouseMove = true;
Hotkey::InstallMouseHook();
break;
case TOGGLE_MOUSEMOVEOFF:
g_BlockMouseMove = false; // But the mouse hook is left installed because it might be needed by other things. This approach is similar to that used by the Input command.
break;
#endif
// default (NEUTRAL or TOGGLE_INVALID): do nothing.
}
return OK;
////////////////////////////////////////////////////////////////////////////////////////
// For these, it seems best not to report an error during runtime if there's
// an invalid value (e.g. something other than On/Off/Blank) in a param containing
// a dereferenced variable, since settings are global and affect all subroutines,
// not just the one that we would otherwise report failure for:
case ACT_SETNUMLOCKSTATE:
return SetToggleState(VK_NUMLOCK, g_ForceNumLock, ARG1);
case ACT_SETCAPSLOCKSTATE:
return SetToggleState(VK_CAPITAL, g_ForceCapsLock, ARG1);
case ACT_SETSCROLLLOCKSTATE:
return SetToggleState(VK_SCROLL, g_ForceScrollLock, ARG1);
#ifndef MINIDLL
case ACT_EDIT:
g_script.Edit();
return OK;
#endif
case ACT_RELOAD:
g_script.Reload(true);
// Even if the reload failed, it seems best to return OK anyway. That way,
// the script can take some follow-on action, e.g. it can sleep for 1000
// after issuing the reload command and then take action under the assumption
// that the reload didn't work (since obviously if the process and thread
// in which the Sleep is running still exist, it didn't work):
return OK;
case ACT_SLEEP:
{
// Only support 32-bit values for this command, since it seems unlikely anyone would to have
// it sleep more than 24.8 days or so. It also helps performance on 32-bit hardware because
// MsgSleep() is so heavily called and checks the value of the first parameter frequently:
int sleep_time = ArgToInt(1); // Keep it signed vs. unsigned for backward compatibility (e.g. scripts that do Sleep -1).
// Do a true sleep on Win9x because the MsgSleep() method is very inaccurate on Win9x
// for some reason (a MsgSleep(1) causes a sleep between 10 and 55ms, for example).
// But only do so for short sleeps, for which the user has a greater expectation of
// accuracy. UPDATE: Do not change the 25 below without also changing it in Critical's
// documentation.
if (g_MainThreadID != aThreadID || (sleep_time < 25 && sleep_time > 0 && g_os.IsWin9x())) // Ordered for short-circuit performance. v1.0.38.05: Added "sleep_time > 0" so that Sleep -1/0 will work the same on Win9x as it does on other OSes.
Sleep(sleep_time);
else
MsgSleep(sleep_time);
return OK;
}
case ACT_INIREAD:
return IniRead(ARG2, ARG3, ARG4, ARG5);
case ACT_INIWRITE:
return IniWrite(FOUR_ARGS);
case ACT_INIDELETE:
// To preserve maximum compatibility with existing scripts, only send NULL if ARG3
// was explicitly omitted. This is because some older scripts might rely on the
// fact that a blank ARG3 does not delete the entire section, but rather does
// nothing (that fact is untested):
return IniDelete(ARG1, ARG2, mArgc < 3 ? NULL : ARG3);
case ACT_REGREAD:
if (mArgc < 2 && g.mLoopRegItem) // Uses the registry loop's current item.
// If g.mLoopRegItem->name specifies a subkey rather than a value name, do this anyway
// so that it will set ErrorLevel to ERROR and set the output variable to be blank.
// Also, do not use RegCloseKey() on this, even if it's a remote key, since our caller handles that:
return RegRead(g.mLoopRegItem->root_key, g.mLoopRegItem->subkey, g.mLoopRegItem->name);
// Otherwise:
if (mArgc > 4 || RegConvertValueType(ARG2)) // The obsolete 5-param method (ARG2 is unused).
result = RegRead(root_key = RegConvertRootKey(ARG3, &is_remote_registry), ARG4, ARG5);
else
result = RegRead(root_key = RegConvertRootKey(ARG2, &is_remote_registry), ARG3, ARG4);
if (is_remote_registry && root_key) // Never try to close local root keys, which the OS keeps always-open.
RegCloseKey(root_key);
return result;
case ACT_REGWRITE:
if (mArgc < 2 && g.mLoopRegItem) // Uses the registry loop's current item.
// If g.mLoopRegItem->name specifies a subkey rather than a value name, do this anyway
// so that it will set ErrorLevel to ERROR. An error will also be indicated if
// g.mLoopRegItem->type is an unsupported type:
return RegWrite(g.mLoopRegItem->type, g.mLoopRegItem->root_key, g.mLoopRegItem->subkey, g.mLoopRegItem->name, ARG1);
// Otherwise:
result = RegWrite(RegConvertValueType(ARG1), root_key = RegConvertRootKey(ARG2, &is_remote_registry)
, ARG3, ARG4, ARG5); // If RegConvertValueType(ARG1) yields REG_NONE, RegWrite() will set ErrorLevel rather than displaying a runtime error.
if (is_remote_registry && root_key) // Never try to close local root keys, which the OS keeps always-open.
RegCloseKey(root_key);
return result;
case ACT_REGDELETE:
if (mArgc < 1 && g.mLoopRegItem) // Uses the registry loop's current item.
{
// In this case, if the current reg item is a value, just delete it normally.
// But if it's a subkey, append it to the dir name so that the proper subkey
// will be deleted as the user intended:
if (g.mLoopRegItem->type == REG_SUBKEY)
{
sntprintf(buf_temp, _countof(buf_temp), _T("%s\\%s"), g.mLoopRegItem->subkey, g.mLoopRegItem->name);
return RegDelete(g.mLoopRegItem->root_key, buf_temp, _T(""));
}
else
return RegDelete(g.mLoopRegItem->root_key, g.mLoopRegItem->subkey, g.mLoopRegItem->name);
}
// Otherwise:
result = RegDelete(root_key = RegConvertRootKey(ARG1, &is_remote_registry), ARG2, ARG3);
if (is_remote_registry && root_key) // Never try to close local root keys, which the OS always keeps open.
RegCloseKey(root_key);
return result;
case ACT_SETREGVIEW:
{
DWORD reg_view = RegConvertView(ARG1);
// Validate the parameter even if it's not going to be used.
if (reg_view == -1)
return LineError(ERR_PARAM1_INVALID, FAIL, ARG1);
// Since these flags cause the registry functions to fail on Win2k and have no effect on
// any later 32-bit OS, ignore this command when the OS is 32-bit. Leave A_RegView blank.
if (IsOS64Bit())
g.RegView = reg_view;
return OK;
}
case ACT_OUTPUTDEBUG:
#ifndef CONFIG_DEBUGGER
OutputDebugString(ARG1); // It does not return a value for the purpose of setting ErrorLevel.
#else
g_Debugger.OutputDebug(ARG1);
#endif
return OK;
case ACT_SHUTDOWN:
return Util_Shutdown(ArgToInt(1)) ? OK : FAIL; // Range of ARG1 is not validated in case other values are supported in the future.
#ifdef MINIDLL
case ACT_IMAGESEARCH:
case ACT_PIXELGETCOLOR:
case ACT_HOTKEY:
case ACT_FILEINSTALL:
case ACT_FILESELECTFILE:
case ACT_FILESELECTFOLDER:
case ACT_KEYHISTORY:
case ACT_LISTLINES:
case ACT_LISTVARS:
case ACT_LISTHOTKEYS:
case ACT_INPUTBOX:
case ACT_SPLASHTEXTON:
case ACT_SPLASHTEXTOFF:
case ACT_PROGRESS:
case ACT_SPLASHIMAGE:
case ACT_TRAYTIP:
case ACT_INPUT:
case ACT_MENU:
case ACT_GUI:
case ACT_GUICONTROL:
case ACT_GUICONTROLGET:
case ACT_SUSPEND:
case TOGGLE_MOUSEMOVE:
case TOGGLE_MOUSEMOVEOFF:
case ACT_EDIT:
return LineError(_T("Command is not supported by AutoHotkeyMini.dll\n\nThe current Thread will exit."));
//return OK; //do not show error for not supported commands
#endif
case ACT_FILEENCODING:
UINT new_encoding = ConvertFileEncoding(ARG1);
if (new_encoding == -1)
return LineError(ERR_PARAM1_INVALID, FAIL, ARG1); // Probably a variable, otherwise load-time validation would've caught it.
g.Encoding = new_encoding;
return OK;
} // switch()
// Since above didn't return, this line's mActionType isn't handled here,
// so caller called it wrong. ACT_INVALID should be impossible because
// Script::AddLine() forbids it.
#ifdef _DEBUG
return LineError(_T("DEBUG: Perform(): Unhandled action type."));
#else
return FAIL;
#endif
}
ResultType Line::Deref(Var *aOutputVar, LPTSTR aBuf)
// Similar to ExpandArg(), except it parses and expands all variable references contained in aBuf.
{
aOutputVar = aOutputVar->ResolveAlias(); // Necessary for proper detection below of whether it's invalidly used as a source for itself.
// This transient variable is used resolving environment variables that don't already exist
// in the script's variable list (due to the fact that they aren't directly referenced elsewhere
// in the script):
TCHAR var_name[MAX_VAR_NAME_LENGTH + 1] = _T("");
Var *var;
VarSizeType expanded_length;
size_t var_name_length;
LPTSTR cp, cp1, dest;
// Do two passes:
// #1: Calculate the space needed so that aOutputVar can be given more capacity if necessary.
// #2: Expand the contents of aBuf into aOutputVar.
for (int which_pass = 0; which_pass < 2; ++which_pass)
{
if (which_pass) // Starting second pass.
{
// Set up aOutputVar, enlarging it if necessary. If it is of type VAR_CLIPBOARD,
// this call will set up the clipboard for writing:
if (aOutputVar->AssignString(NULL, expanded_length) != OK)
return FAIL;
dest = aOutputVar->Contents(); // Init, and for performance.
}
else // First pass.
expanded_length = 0; // Init prior to accumulation.
for (cp = aBuf; ; ++cp) // Increment to skip over the deref/escape just found by the inner for().
{
// Find the next escape char or deref symbol:
for (; *cp && *cp != g_EscapeChar && *cp != g_DerefChar; ++cp)
{
if (which_pass) // 2nd pass
*dest++ = *cp; // Copy all non-variable-ref characters literally.
else // just accumulate the length
++expanded_length;
}
if (!*cp) // End of string while scanning/copying. The current pass is now complete.
break;
if (*cp == g_EscapeChar)
{
if (which_pass) // 2nd pass
{
cp1 = cp + 1;
switch (*cp1) // See ConvertEscapeSequences() for more details.
{
// Only lowercase is recognized for these:
case 'a': *dest = '\a'; break; // alert (bell) character
case 'b': *dest = '\b'; break; // backspace
case 'f': *dest = '\f'; break; // formfeed
case 'n': *dest = '\n'; break; // newline
case 'r': *dest = '\r'; break; // carriage return
case 't': *dest = '\t'; break; // horizontal tab
case 'v': *dest = '\v'; break; // vertical tab
default: *dest = *cp1; // These other characters are resolved just as they are, including '\0'.
}
++dest;
}
else
++expanded_length;
// Increment cp here and it will be incremented again by the outer loop, i.e. +2.
// In other words, skip over the escape character, treating it and its target character
// as a single character.
++cp;
continue;
}
// Otherwise, it's a dereference symbol, so calculate the size of that variable's contents
// and add that to expanded_length (or copy the contents into aOutputVar if this is the
// second pass).
// Find the reference's ending symbol (don't bother with catching escaped deref chars here
// -- e.g. %MyVar`% -- since it seems too troublesome to justify given how extremely rarely
// it would be an issue):
for (cp1 = cp + 1; *cp1 && *cp1 != g_DerefChar; ++cp1);
if (!*cp1) // Since end of string was found, this deref is not correctly terminated.
continue; // For consistency, omit it entirely.
var_name_length = cp1 - cp - 1;
if (var_name_length && var_name_length <= MAX_VAR_NAME_LENGTH)
{
tcslcpy(var_name, cp + 1, var_name_length + 1); // +1 to convert var_name_length to size.
// Fixed for v1.0.34: Use FindOrAddVar() vs. FindVar() so that environment or built-in
// variables that aren't directly referenced elsewhere in the script will still work:
if ( !(var = g_script.FindOrAddVar(var_name, var_name_length)) )
return FAIL; // Above already displayed the error.
var = var->ResolveAlias();
// Don't allow the output variable to be read into itself this way because its contents
if (var != aOutputVar) // Both of these have had ResolveAlias() called, if required, to make the comparison accurate.
{
if (which_pass) // 2nd pass
dest += var->Get(dest);
else // just accumulate the length
expanded_length += var->Get(); // Add in the length of the variable's contents.
}
}
// else since the variable name between the deref symbols is blank or too long: for consistency in behavior,
// it seems best to omit the dereference entirely (don't put it into aOutputVar).
cp = cp1; // For the next loop iteration, continue at the char after this reference's final deref symbol.
} // for()
} // for() (first and second passes)
*dest = '\0'; // Terminate the output variable.
aOutputVar->SetCharLength((VarSizeType)_tcslen(aOutputVar->Contents())); // Update to actual in case estimate was too large.
return aOutputVar->Close(); // In case it's the clipboard.
}
LPTSTR Line::LogToText(LPTSTR aBuf, int aBufSize) // aBufSize should be an int to preserve negatives from caller (caller relies on this).
// aBufSize is an int so that any negative values passed in from caller are not lost.
// Translates sLog into its text equivalent, putting the result into aBuf and
// returning the position in aBuf of its new string terminator.
// Caller has ensured that aBuf is non-NULL and that aBufSize is reasonable (at least 256).
{
LPTSTR aBuf_orig = aBuf;
// Store the position of where each retry done by the outer loop will start writing:
LPTSTR aBuf_log_start = aBuf + sntprintf(aBuf, aBufSize, _T("Script lines most recently executed (oldest first).")
_T(" Press [F5] to refresh. The seconds elapsed between a line and the one after it is in parentheses to")
_T(" the right (if not 0). The bottommost line's elapsed time is the number of seconds since it executed.\r\n\r\n"));
int i, lines_to_show, line_index, line_index2, space_remaining; // space_remaining must be an int to detect negatives.
#ifndef AUTOHOTKEYSC
int last_file_index = -1;
#endif
DWORD elapsed;
bool this_item_is_special, next_item_is_special;
// In the below, sLogNext causes it to start at the oldest logged line and continue up through the newest:
for (lines_to_show = LINE_LOG_SIZE, line_index = sLogNext;;) // Retry with fewer lines in case the first attempt doesn't fit in the buffer.
{
aBuf = aBuf_log_start; // Reset target position in buffer to the place where log should begin.
for (next_item_is_special = false, i = 0; i < lines_to_show; ++i, ++line_index)
{
if (line_index >= LINE_LOG_SIZE) // wrap around, because sLog is a circular queue
line_index -= LINE_LOG_SIZE; // Don't just reset it to zero because an offset larger than one may have been added to it.
if (!sLog[line_index]) // No line has yet been logged in this slot.
continue; // ACT_LISTLINES and other things might rely on "continue" isntead of halting the loop here.
this_item_is_special = next_item_is_special;
next_item_is_special = false; // Set default.
if (i + 1 < lines_to_show) // There are still more lines to be processed
{
if (this_item_is_special) // And we know from the above that this special line is not the last line.
// Due to the fact that these special lines are usually only useful when they appear at the
// very end of the log, omit them from the log-display when they're not the last line.
// In the case of a high-frequency SetTimer, this greatly reduces the log clutter that
// would otherwise occur:
continue;
// Since above didn't continue, this item isn't special, so display it normally.
elapsed = sLogTick[line_index + 1 >= LINE_LOG_SIZE ? 0 : line_index + 1] - sLogTick[line_index];
if (elapsed > INT_MAX) // INT_MAX is about one-half of DWORD's capacity.
{
// v1.0.30.02: Assume that huge values (greater than 24 days or so) were caused by
// the new policy of storing WinWait/RunWait/etc.'s line in the buffer whenever
// it was interrupted and later resumed by a thread. In other words, there are now
// extra lines in the buffer which are considered "special" because they don't indicate
// a line that actually executed, but rather one that is still executing (waiting).
// See ACT_WINWAIT for details.
next_item_is_special = true; // Override the default.
if (i + 2 == lines_to_show) // The line after this one is not only special, but the last one that will be shown, so recalculate this one correctly.
elapsed = GetTickCount() - sLogTick[line_index];
else // Neither this line nor the special one that follows it is the last.
{
// Refer to the line after the next (special) line to get this line's correct elapsed time.
line_index2 = line_index + 2;
if (line_index2 >= LINE_LOG_SIZE)
line_index2 -= LINE_LOG_SIZE;
elapsed = sLogTick[line_index2] - sLogTick[line_index];
}
}
}
else // This is the last line (whether special or not), so compare it's time against the current time instead.
elapsed = GetTickCount() - sLogTick[line_index];
#ifndef AUTOHOTKEYSC
// If the this line and the previous line are in different files, display the filename:
if (last_file_index != sLog[line_index]->mFileIndex)
{
last_file_index = sLog[line_index]->mFileIndex;
+#ifdef _USRDLL
+ // terminate source file if it contains new lines
+ LPTSTR new_line_pos = _tcschr(sSourceFile[last_file_index], '\r');
+ if (!new_line_pos)
+ new_line_pos = _tcschr(sSourceFile[last_file_index], '\n');
+ TCHAR new_line_char = NULL;
+ if (new_line_pos)
+ {
+ new_line_char = *new_line_pos;
+ *new_line_pos = '\0';
+ }
+#endif
aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("---- %s\r\n"), sSourceFile[last_file_index]);
+#ifdef _USRDLL
+ if (new_line_pos)
+ *new_line_pos = new_line_char;
+#endif
}
#endif
space_remaining = BUF_SPACE_REMAINING; // Resolve macro only once for performance.
// Truncate really huge lines so that the Edit control's size is less likely to be exhausted.
// In v1.0.30.02, this is even more likely due to having increased the line-buf's capacity from
// 200 to 400, therefore the truncation point was reduced from 500 to 200 to make it more likely
// that the first attempt to fit the lines_to_show number of lines into the buffer will succeed.
aBuf = sLog[line_index]->ToText(aBuf, space_remaining < 200 ? space_remaining : 200, true, elapsed, this_item_is_special);
// If the line above can't fit everything it needs into the remaining space, it will fill all
// of the remaining space, and thus the check against LINE_LOG_FINAL_MESSAGE_LENGTH below
// should never fail to catch that, and then do a retry.
} // Inner for()
#define LINE_LOG_FINAL_MESSAGE _T("\r\nPress [F5] to refresh.") // Keep the next line in sync with this.
#define LINE_LOG_FINAL_MESSAGE_LENGTH 24
if (BUF_SPACE_REMAINING > LINE_LOG_FINAL_MESSAGE_LENGTH || lines_to_show < 120) // Either success or can't succeed.
break;
// Otherwise, there is insufficient room to put everything in, but there's still room to retry
// with a smaller value of lines_to_show:
lines_to_show -= 100;
line_index = sLogNext + (LINE_LOG_SIZE - lines_to_show); // Move the starting point forward in time so that the oldest log entries are omitted.
} // outer for() that retries the log-to-buffer routine.
// Must add the return value, not LINE_LOG_FINAL_MESSAGE_LENGTH, in case insufficient room (i.e. in case
// outer loop terminated due to lines_to_show being too small).
return aBuf + sntprintf(aBuf, BUF_SPACE_REMAINING, LINE_LOG_FINAL_MESSAGE);
}
LPTSTR Line::VicinityToText(LPTSTR aBuf, int aBufSize) // aBufSize should be an int to preserve negatives from caller (caller relies on this).
// aBufSize is an int so that any negative values passed in from caller are not lost.
// Caller has ensured that aBuf isn't NULL.
// Translates the current line and the lines above and below it into their text equivalent
// putting the result into aBuf and returning the position in aBuf of its new string terminator.
{
LPTSTR aBuf_orig = aBuf;
#define LINES_ABOVE_AND_BELOW 7
// Determine the correct value for line_start and line_end:
int i;
Line *line_start, *line_end;
for (i = 0, line_start = this
; i < LINES_ABOVE_AND_BELOW && line_start->mPrevLine != NULL
; ++i, line_start = line_start->mPrevLine);
for (i = 0, line_end = this
; i < LINES_ABOVE_AND_BELOW && line_end->mNextLine != NULL
; ++i, line_end = line_end->mNextLine);
#ifdef AUTOHOTKEYSC
if (!g_AllowMainWindow) // Override the above to show only a single line, to conceal the script's source code.
{
line_start = this;
line_end = this;
}
#endif
// Now line_start and line_end are the first and last lines of the range
// we want to convert to text, and they're non-NULL.
aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("\tLine#\n"));
int space_remaining; // Must be an int to preserve any negative results.
// Start at the oldest and continue up through the newest:
for (Line *line = line_start;;)
{
if (line == this)
tcslcpy(aBuf, _T("--->\t"), BUF_SPACE_REMAINING);
else
tcslcpy(aBuf, _T("\t"), BUF_SPACE_REMAINING);
aBuf += _tcslen(aBuf);
space_remaining = BUF_SPACE_REMAINING; // Resolve macro only once for performance.
// Truncate large lines so that the dialog is more readable:
aBuf = line->ToText(aBuf, space_remaining < 500 ? space_remaining : 500, false);
if (line == line_end)
break;
line = line->mNextLine;
}
return aBuf;
}
LPTSTR Line::ToText(LPTSTR aBuf, int aBufSize, bool aCRLF, DWORD aElapsed, bool aLineWasResumed) // aBufSize should be an int to preserve negatives from caller (caller relies on this).
// aBufSize is an int so that any negative values passed in from caller are not lost.
// Caller has ensured that aBuf isn't NULL.
// Translates this line into its text equivalent, putting the result into aBuf and
// returning the position in aBuf of its new string terminator.
{
if (aBufSize < 3)
return aBuf;
else
aBufSize -= (1 + aCRLF); // Reserve one char for LF/CRLF after each line (so that it always get added).
LPTSTR aBuf_orig = aBuf;
aBuf += sntprintf(aBuf, aBufSize, _T("%03u: "), mLineNumber);
if (aLineWasResumed)
aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("STILL WAITING (%0.2f): "), (float)aElapsed / 1000.0);
if (mActionType == ACT_IFBETWEEN || mActionType == ACT_IFNOTBETWEEN)
aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("if %s %s %s and %s")
, *mArg[0].text ? mArg[0].text : VAR(mArg[0])->mName // i.e. don't resolve dynamic variable names.
, g_act[mActionType].Name, RAW_ARG2, RAW_ARG3);
else if (ACT_IS_ASSIGN(mActionType) || (ACT_IS_IF(mActionType) && mActionType < ACT_FIRST_COMMAND))
aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("%s%s %s %s")
, ACT_IS_IF(mActionType) ? _T("if ") : _T("")
, *mArg[0].text ? mArg[0].text : VAR(mArg[0])->mName // i.e. don't resolve dynamic variable names.
, g_act[mActionType].Name, RAW_ARG2);
else if (mActionType == ACT_FOR)
aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("For %s,%s in %s")
, *mArg[0].text ? mArg[0].text : VAR(mArg[0])->mName // i.e. don't resolve dynamic variable names.
, *mArg[1].text || !VAR(mArg[1]) ? mArg[1].text : VAR(mArg[1])->mName // can be omitted.
, mArg[2].text);
else
{
aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("%s"), g_act[mActionType].Name);
for (int i = 0; i < mArgc; ++i)
// This method a little more efficient than using snprintfcat().
// Also, always use the arg's text for input and output args whose variables haven't
// been resolved at load-time, since the text has everything in it we want to display
// and thus there's no need to "resolve" dynamic variables here (e.g. array%i%).
aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T(",%s"), (mArg[i].type != ARG_TYPE_NORMAL && !*mArg[i].text)
? VAR(mArg[i])->mName : mArg[i].text);
}
if (aElapsed && !aLineWasResumed)
aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T(" (%0.2f)"), (float)aElapsed / 1000.0);
// UPDATE for v1.0.25: It seems that MessageBox(), which is the only way these lines are currently
// displayed, prefers \n over \r\n because otherwise, Ctrl-C on the MsgBox copies the lines all
// onto one line rather than formatted nicely as separate lines.
// Room for LF or CRLF was reserved at the top of this function:
if (aCRLF)
*aBuf++ = '\r';
*aBuf++ = '\n';
*aBuf = '\0';
return aBuf;
}
#ifndef MINIDLL
void Line::ToggleSuspendState()
{
// If suspension is being turned on:
// It seems unnecessary, and possibly undesirable, to purge any pending hotkey msgs from the msg queue.
// Even if there are some, it's possible that they are exempt from suspension so we wouldn't want to
// globally purge all messages anyway.
g_IsSuspended = !g_IsSuspended;
Hotstring::SuspendAll(g_IsSuspended); // Must do this prior to ManifestAllHotkeysHotstringsHooks() to avoid incorrect removal of hook.
Hotkey::ManifestAllHotkeysHotstringsHooks(); // Update the state of all hotkeys based on the complex interdependencies hotkeys have with each another.
g_script.UpdateTrayIcon();
CheckMenuItem(GetMenu(g_hWnd), ID_FILE_SUSPEND, g_IsSuspended ? MF_CHECKED : MF_UNCHECKED);
}
#endif
void Line::PauseUnderlyingThread(bool aTrueForPauseFalseForUnpause)
{
if (g <= g_array) // Guard against underflow. This condition can occur when the script thread that called us is the AutoExec section or a callback running in the idle/0 thread.
return;
if (g[-1].IsPaused == aTrueForPauseFalseForUnpause) // It's already in the right state.
return; // Return early because doing the updates further below would be wrong in this case.
g[-1].IsPaused = aTrueForPauseFalseForUnpause; // Update the pause state to that specified by caller.
if (aTrueForPauseFalseForUnpause) // The underlying thread is being paused when it was unpaused before.
++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread.
else // The underlying thread is being unpaused when it was paused before.
--g_nPausedThreads;
}
ResultType Line::ChangePauseState(ToggleValueType aChangeTo, bool aAlwaysOperateOnUnderlyingThread)
// Currently designed to be called only by the Pause command (ACT_PAUSE).
// Returns OK or FAIL.
{
switch (aChangeTo)
{
case TOGGLED_ON:
break; // By breaking instead of returning, pause will be put into effect further below.
case TOGGLED_OFF:
// v1.0.37.06: The old method was to unpause the the nearest paused thread on the call stack;
// but it was flawed because if the thread that made the flag true is interrupted, and the new
// thread is paused via the pause command, and that thread is then interrupted, when the paused
// thread resumes it would automatically and wrongly be unpaused (i.e. the unpause ticket would
// be used at a level higher in the call stack than intended).
// Flag this thread so that when it ends, the thread beneath it will be unpaused. If that thread
// (which can be the idle thread) isn't paused the following flag-change will be ignored at a later
// stage. This method also relies on the fact that the current thread cannot itself be paused right
// now because it is what got us here.
PauseUnderlyingThread(false); // Necessary even for the "idle thread" (otherwise, the Pause command wouldn't be able to unpause it).
return OK;
case NEUTRAL: // the user omitted the parameter entirely, which is considered the same as "toggle"
case TOGGLE:
// Update for v1.0.37.06: "Pause" and "Pause Toggle" are more useful if they always apply to the
// thread immediately beneath the current thread rather than "any underlying thread that's paused".
if (g > g_array && g[-1].IsPaused) // Checking g>g_array avoids any chance of underflow, which might otherwise happen if this is called by the AutoExec section or a threadless callback running in thread #0.
{
PauseUnderlyingThread(false);
return OK;
}
//ELSE since the underlying thread is not paused, continue onward to do the "pause enabled" logic below.
// (This is the historical behavior because it allows a hotkey like F1::Pause to toggle the script's
// pause state on and off -- even though what's really happening involves multiple threads.)
break;
default: // TOGGLE_INVALID or some other disallowed value.
// We know it's a variable because otherwise the loading validation would have caught it earlier:
return LineError(ERR_PARAM1_INVALID, FAIL, ARG1);
}
// Since above didn't return, pause should be turned on.
if (aAlwaysOperateOnUnderlyingThread) // v1.0.37.06: Allow underlying thread to be directly paused rather than pausing the current thread.
{
PauseUnderlyingThread(true); // If the underlying thread is already paused, this flag change will be ignored at a later stage.
return OK;
}
// Otherwise, pause the current subroutine (which by definition isn't paused since it had to be
// active to call us). It seems best not to attempt to change the Hotkey mRunAgainAfterFinished
// attribute for the current hotkey (assuming it's even a hotkey that got us here) or
// for them all. This is because it's conceivable that this Pause command occurred
// in a background thread, such as a timed subroutine, in which case we wouldn't want the
// pausing of that thread to affect anything else the user might be doing with hotkeys.
// UPDATE: The above is flawed because by definition the script's quasi-thread that got
// us here is now active. Since it is active, the script will immediately become dormant
// when this is executed, waiting for the user to press a hotkey to launch a new
// quasi-thread. Thus, it seems best to reset all the mRunAgainAfterFinished flags
// in case we are in a hotkey subroutine and in case this hotkey has a buffered repeat-again
// action pending, which the user probably wouldn't want to happen after the script is unpaused:
#ifndef MINIDLL
Hotkey::ResetRunAgainAfterFinished();
#endif
g->IsPaused = true;
++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread.
#ifndef MINIDLL
g_script.UpdateTrayIcon();
#endif
return OK;
}
ResultType Line::ScriptBlockInput(bool aEnable)
// Always returns OK for caller convenience.
{
// Must be running Win98/2000+ for this function to be successful.
// We must dynamically load the function to retain compatibility with Win95 (program won't launch
// at all otherwise).
typedef void (CALLBACK *BlockInput)(BOOL);
static BlockInput lpfnDLLProc = (BlockInput)GetProcAddress(GetModuleHandle(_T("user32")), "BlockInput");
// Always turn input ON/OFF even if g_BlockInput says its already in the right state. This is because
// BlockInput can be externally and undetectably disabled, e.g. if the user presses Ctrl-Alt-Del:
if (lpfnDLLProc)
(*lpfnDLLProc)(aEnable ? TRUE : FALSE);
g_BlockInput = aEnable;
return OK; // By design, it never returns FAIL.
}
Line *Line::PreparseError(LPTSTR aErrorText, LPTSTR aExtraInfo)
// Returns a different type of result for use with the Pre-parsing methods.
{
// Make all preparsing errors critical because the runtime reliability
// of the program relies upon the fact that the aren't any kind of
// problems in the script (otherwise, unexpected behavior may result).
// Update: It's okay to return FAIL in this case. CRITICAL_ERROR should
// be avoided whenever OK and FAIL are sufficient by themselves, because
// otherwise, callers can't use the NOT operator to detect if a function
// failed (since FAIL is value zero, but CRITICAL_ERROR is non-zero):
LineError(aErrorText, FAIL, aExtraInfo);
return NULL; // Always return NULL because the callers use it as their return value.
}
IObject *Line::CreateRuntimeException(LPCTSTR aErrorText, LPCTSTR aWhat, LPCTSTR aExtraInfo)
{
// Build the parameters for Object::Create()
ExprTokenType aParams[5*2]; int aParamCount = 4*2;
ExprTokenType* aParam[5*2] = { aParams + 0, aParams + 1, aParams + 2, aParams + 3, aParams + 4
, aParams + 5, aParams + 6, aParams + 7, aParams + 8, aParams + 9 };
aParams[0].symbol = SYM_STRING; aParams[0].marker = _T("What");
aParams[1].symbol = SYM_STRING; aParams[1].marker = aWhat ? (LPTSTR)aWhat : g_act[mActionType].Name;
aParams[2].symbol = SYM_STRING; aParams[2].marker = _T("File");
aParams[3].symbol = SYM_STRING; aParams[3].marker = Line::sSourceFile[mFileIndex];
aParams[4].symbol = SYM_STRING; aParams[4].marker = _T("Line");
aParams[5].symbol = SYM_INTEGER; aParams[5].value_int64 = mLineNumber;
aParams[6].symbol = SYM_STRING; aParams[6].marker = _T("Message");
aParams[7].symbol = SYM_STRING; aParams[7].marker = (LPTSTR)aErrorText;
if (aExtraInfo && *aExtraInfo)
{
aParamCount += 2;
aParams[8].symbol = SYM_STRING; aParams[8].marker = _T("Extra");
aParams[9].symbol = SYM_STRING; aParams[9].marker = (LPTSTR)aExtraInfo;
}
return Object::Create(aParam, aParamCount);
}
ResultType Line::ThrowRuntimeException(LPCTSTR aErrorText, LPCTSTR aWhat, LPCTSTR aExtraInfo)
{
// ThrownToken may already exist if Assign() fails in ACT_CATCH, or possibly
// in other extreme cases. In such a case, just free the old token. If this
// line is CATCH, it won't handle the new exception; an outer TRY/CATCH will.
if (g->ThrownToken)
g_script.FreeExceptionToken(g->ThrownToken);
ExprTokenType *token;
if ( !(token = new ExprTokenType)
|| !(token->object = CreateRuntimeException(aErrorText, aWhat, aExtraInfo)) )
{
// Out of memory. It's likely that we were called for this very reason.
// Since we don't even have enough memory to allocate an exception object,
// just show an error message and exit the thread. Don't call LineError(),
// since that would recurse into this function.
if (token)
delete token;
MsgBox(ERR_OUTOFMEM ERR_ABORT);
return FAIL;
}
token->symbol = SYM_OBJECT;
token->mem_to_free = NULL;
g->ThrownToken = token;
g->ExcptLine = this;
// Returning FAIL causes each caller to also return FAIL, until either the
// thread has fully exited or the recursion layer handling ACT_TRY is reached:
return FAIL;
}
ResultType Script::ThrowRuntimeException(LPCTSTR aErrorText, LPCTSTR aWhat, LPCTSTR aExtraInfo)
{
return g_script.mCurrLine->ThrowRuntimeException(aErrorText, aWhat, aExtraInfo);
}
ResultType Line::SetErrorLevelOrThrowBool(bool aError)
{
if (!aError)
return g_ErrorLevel->Assign(ERRORLEVEL_NONE);
if (!g->InTryBlock)
return g_ErrorLevel->Assign(ERRORLEVEL_ERROR);
// Otherwise, an error occurred and there is a try block, so throw an exception:
return ThrowRuntimeException(ERRORLEVEL_ERROR);
}
ResultType Line::SetErrorLevelOrThrowStr(LPCTSTR aErrorValue)
{
if ((*aErrorValue == '0' && !aErrorValue[1]) || !g->InTryBlock)
return g_ErrorLevel->Assign(aErrorValue);
// Otherwise, an error occurred and there is a try block, so throw an exception:
return ThrowRuntimeException(aErrorValue);
}
ResultType Line::SetErrorLevelOrThrowInt(int aErrorValue)
{
if (!aErrorValue || !g->InTryBlock)
return g_ErrorLevel->Assign(aErrorValue);
TCHAR buf[12];
// Otherwise, an error occurred and there is a try block, so throw an exception:
return ThrowRuntimeException(_itot(aErrorValue, buf, 10));
}
// Logic from the above functions is duplicated in the below functions rather than calling
// g_script.mCurrLine->SetErrorLevelOrThrow() to squeeze out a little extra performance for
// "success" cases. These are done as overloads vs making aMessage optional to reduce code
// size, since they're called from numerous places. (Even omitted parameters are passed
// "explicitly" in the compiled code.)
ResultType Script::SetErrorLevelOrThrowBool(bool aError)
{
if (!aError)
return g_ErrorLevel->Assign(ERRORLEVEL_NONE);
if (!g->InTryBlock)
return g_ErrorLevel->Assign(ERRORLEVEL_ERROR);
// Otherwise, an error occurred and there is a try block, so throw an exception:
return ThrowRuntimeException(ERRORLEVEL_ERROR);
}
ResultType Script::SetErrorLevelOrThrowStr(LPCTSTR aErrorValue, LPCTSTR aWhat)
{
if ((*aErrorValue == '0' && !aErrorValue[1]) || !g->InTryBlock)
return g_ErrorLevel->Assign(aErrorValue);
// Otherwise, an error occurred and there is a try block, so throw an exception:
return ThrowRuntimeException(aErrorValue, aWhat);
}
ResultType Script::SetErrorLevelOrThrowInt(int aErrorValue, LPCTSTR aWhat)
{
if (!aErrorValue || !g->InTryBlock)
return g_ErrorLevel->Assign(aErrorValue);
TCHAR buf[12];
// Otherwise, an error occurred and there is a try block, so throw an exception:
return ThrowRuntimeException(_itot(aErrorValue, buf, 10), aWhat);
}
ResultType Line::SetErrorsOrThrow(bool aError, DWORD aLastErrorOverride)
{
// LastError is set even if we're going to throw an exception, for simplicity:
g->LastError = aLastErrorOverride == -1 ? GetLastError() : aLastErrorOverride;
return SetErrorLevelOrThrowBool(aError);
}
#define ERR_PRINT(fmt, ...) _ftprintf(stderr, fmt, __VA_ARGS__)
ResultType Line::LineError(LPCTSTR aErrorText, ResultType aErrorType, LPCTSTR aExtraInfo)
{
if (!aErrorText)
aErrorText = _T("");
if (!aExtraInfo)
aExtraInfo = _T("");
if (g->InTryBlock && (aErrorType == FAIL || aErrorType == EARLY_EXIT)) // FAIL is most common, but EARLY_EXIT is used by ComError(). WARN and CRITICAL_ERROR are excluded.
return ThrowRuntimeException(aErrorText, NULL, aExtraInfo);
if (g_script.mErrorStdOut && !g_script.mIsReadyToExecute && aErrorType != WARN) // i.e. runtime errors are always displayed via dialog.
{
// JdeB said:
// Just tested it in Textpad, Crimson and Scite. they all recognise the output and jump
// to the Line containing the error when you double click the error line in the output
// window (like it works in C++). Had to change the format of the line to:
// printf("%s (%d) : ==> %s: \n%s \n%s\n",szInclude, nAutScriptLine, szText, szScriptLine, szOutput2 );
// MY: Full filename is required, even if it's the main file, because some editors (EditPlus)
// seem to rely on that to determine which file and line number to jump to when the user double-clicks
// the error message in the output window.
// v1.0.47: Added a space before the colon as originally intended. Toralf said, "With this minor
// change the error lexer of Scite recognizes this line as a Microsoft error message and it can be
// used to jump to that line."
#define STD_ERROR_FORMAT _T("%s (%d) : ==> %s\n")
+#ifdef _USRDLL
+ // terminate source file if it contains new lines
+ LPTSTR new_line_pos = _tcschr(Line::sSourceFile[mFileIndex], '\r');
+ if (!new_line_pos)
+ new_line_pos = _tcschr(Line::sSourceFile[mFileIndex], '\n');
+ TCHAR new_line_char = NULL;
+ if (new_line_pos)
+ {
+ new_line_char = *new_line_pos;
+ *new_line_pos = '\0';
+ }
+#endif
ERR_PRINT(STD_ERROR_FORMAT, sSourceFile[mFileIndex], mLineNumber, aErrorText); // printf() does not significantly increase the size of the EXE, probably because it shares most of the same code with sprintf(), etc.
+#ifdef _USRDLL
+ if (new_line_pos)
+ *new_line_pos = new_line_char;
+#endif
if (*aExtraInfo)
ERR_PRINT(_T(" Specifically: %s\n"), aExtraInfo);
}
else
{
TCHAR buf[MSGBOX_TEXT_SIZE];
FormatError(buf, _countof(buf), aErrorType, aErrorText, aExtraInfo, this
// The last parameter determines the final line of the message:
, (aErrorType == FAIL && g_script.mIsReadyToExecute) ? ERR_ABORT_NO_SPACES
: (aErrorType == CRITICAL_ERROR || aErrorType == FAIL) ? (g_script.mIsRestart ? OLD_STILL_IN_EFFECT : WILL_EXIT)
: (aErrorType == EARLY_EXIT) ? _T("Continue running the script?")
: _T("For more details, read the documentation for #Warn."));
g_script.mCurrLine = this; // This needs to be set in some cases where the caller didn't.
#ifdef CONFIG_DEBUGGER
if (g_Debugger.HasStdErrHook())
g_Debugger.OutputDebug(buf);
else
#endif
if (MsgBox(buf, MB_TOPMOST | (aErrorType == EARLY_EXIT ? MB_YESNO : 0)) == IDNO)
aErrorType = CRITICAL_ERROR;
}
if (aErrorType == CRITICAL_ERROR && g_script.mIsReadyToExecute)
// Also ask the main message loop function to quit and announce to the system that
// we expect it to quit. In most cases, this is unnecessary because all functions
// called to get to this point will take note of the CRITICAL_ERROR and thus keep
// return immediately, all the way back to main. However, there may cases
// when this isn't true:
// Note: Must do this only after MsgBox, since it appears that new dialogs can't
// be created once it's done. Update: Using ExitApp() now, since it's known to be
// more reliable:
//PostQuitMessage(CRITICAL_ERROR);
// This will attempt to run the OnExit subroutine, which should be okay since that subroutine
// will terminate the script if it encounters another runtime error:
g_script.ExitApp(EXIT_ERROR);
return aErrorType; // The caller told us whether it should be a critical error or not.
}
int Line::FormatError(LPTSTR aBuf, int aBufSize, ResultType aErrorType, LPCTSTR aErrorText, LPCTSTR aExtraInfo, Line *aLine, LPCTSTR aFooter)
{
TCHAR source_file[MAX_PATH * 2];
if (aLine && aLine->mFileIndex)
sntprintf(source_file, _countof(source_file), _T(" in #include file \"%s\""), sSourceFile[aLine->mFileIndex]);
else
*source_file = '\0'; // Don't bother cluttering the display if it's the main script file.
LPTSTR aBuf_orig = aBuf;
// Error message:
aBuf += sntprintf(aBuf, aBufSize, _T("%s%s:%s %-1.500s\n\n") // Keep it to a sane size in case it's huge.
, aErrorType == WARN ? _T("Warning") : (aErrorType == CRITICAL_ERROR ? _T("Critical Error") : _T("Error"))
, source_file, *source_file ? _T("\n ") : _T(" "), aErrorText);
// Specifically:
if (*aExtraInfo)
// Use format specifier to make sure really huge strings that get passed our
// way, such as a var containing clipboard text, are kept to a reasonable size:
aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("Specifically: %-1.100s%s\n\n")
, aExtraInfo, _tcslen(aExtraInfo) > 100 ? _T("...") : _T(""));
// Relevant lines of code:
if (aLine)
aBuf = aLine->VicinityToText(aBuf, BUF_SPACE_REMAINING);
// What now?:
if (aFooter)
aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("\n%s"), aFooter);
return (int)(aBuf - aBuf_orig);
}
ResultType Script::ScriptError(LPCTSTR aErrorText, LPCTSTR aExtraInfo) //, ResultType aErrorType)
// Even though this is a Script method, including it here since it shares
// a common theme with the other error-displaying functions:
{
if (mCurrLine)
// If a line is available, do LineError instead since it's more specific.
// If an error occurs before the script is ready to run, assume it's always critical
// in the sense that the program will exit rather than run the script.
// Update: It's okay to return FAIL in this case. CRITICAL_ERROR should
// be avoided whenever OK and FAIL are sufficient by themselves, because
// otherwise, callers can't use the NOT operator to detect if a function
// failed (since FAIL is value zero, but CRITICAL_ERROR is non-zero):
return mCurrLine->LineError(aErrorText, FAIL, aExtraInfo);
// Otherwise: The fact that mCurrLine is NULL means that the line currently being loaded
// has not yet been successfully added to the linked list. Such errors will always result
// in the program exiting.
if (!aErrorText)
aErrorText = _T("Unk"); // Placeholder since it shouldn't be NULL.
if (!aExtraInfo) // In case the caller explicitly called it with NULL.
aExtraInfo = _T("");
if (g_script.mErrorStdOut && !g_script.mIsReadyToExecute) // i.e. runtime errors are always displayed via dialog.
{
+#ifdef _USRDLL
+ // terminate source file if it contains new lines
+ LPTSTR new_line_pos = _tcschr(Line::sSourceFile[mCurrFileIndex], '\r');
+ if (!new_line_pos)
+ new_line_pos = _tcschr(Line::sSourceFile[mCurrFileIndex], '\n');
+ TCHAR new_line_char = NULL;
+ if (new_line_pos)
+ {
+ new_line_char = *new_line_pos;
+ *new_line_pos = '\0';
+ }
+#endif
// See LineError() for details.
ERR_PRINT(STD_ERROR_FORMAT, Line::sSourceFile[mCurrFileIndex], mCombinedLineNumber, aErrorText);
+#ifdef _USRDLL
+ if (new_line_pos)
+ *new_line_pos = new_line_char;
+#endif
if (*aExtraInfo)
ERR_PRINT(_T(" Specifically: %s\n"), aExtraInfo);
}
else
{
TCHAR buf[MSGBOX_TEXT_SIZE], *cp = buf;
int buf_space_remaining = (int)_countof(buf);
cp += sntprintf(cp, buf_space_remaining, _T("Error at line %u"), mCombinedLineNumber); // Don't call it "critical" because it's usually a syntax error.
buf_space_remaining = (int)(_countof(buf) - (cp - buf));
if (mCurrFileIndex)
{
cp += sntprintf(cp, buf_space_remaining, _T(" in #include file \"%s\""), Line::sSourceFile[mCurrFileIndex]);
buf_space_remaining = (int)(_countof(buf) - (cp - buf));
}
//else don't bother cluttering the display if it's the main script file.
cp += sntprintf(cp, buf_space_remaining, _T(".\n\n"));
buf_space_remaining = (int)(_countof(buf) - (cp - buf));
if (*aExtraInfo)
{
cp += sntprintf(cp, buf_space_remaining, _T("Line Text: %-1.100s%s\nError: ") // i.e. the word "Error" is omitted as being too noisy when there's no ExtraInfo to put into the dialog.
, aExtraInfo // aExtraInfo defaults to "" so this is safe.
, _tcslen(aExtraInfo) > 100 ? _T("...") : _T(""));
buf_space_remaining = (int)(_countof(buf) - (cp - buf));
}
sntprintf(cp, buf_space_remaining, _T("%s\n\n%s"), aErrorText, mIsRestart ? OLD_STILL_IN_EFFECT : WILL_EXIT);
//ShowInEditor();
#ifdef CONFIG_DEBUGGER
if (g_Debugger.HasStdErrHook())
g_Debugger.OutputDebug(buf);
else
#endif
MsgBox(buf);
}
return FAIL; // See above for why it's better to return FAIL than CRITICAL_ERROR.
}
ResultType Script::UnhandledException(ExprTokenType*& aToken, Line* aLine)
{
LPCTSTR message = _T(""), extra = _T("");
TCHAR extra_buf[MAX_NUMBER_SIZE], message_buf[MAX_NUMBER_SIZE];
if (Object *ex = dynamic_cast<Object *>(TokenToObject(*aToken)))
{
// For simplicity and safety, we call into the Object directly rather than via Invoke().
ExprTokenType t;
if (ex->GetItem(t, _T("Message")))
message = TokenToString(t, message_buf);
if (ex->GetItem(t, _T("Extra")))
extra = TokenToString(t, extra_buf);
if (ex->GetItem(t, _T("Line")))
{
LineNumberType line_no = (LineNumberType)TokenToInt64(t);
if (ex->GetItem(t, _T("File")))
{
LPCTSTR file = TokenToString(t);
// Locate the line by number and file index, then display that line instead
// of the caller supplied one since it's probably more relevant.
int file_index;
for (file_index = 0; file_index < Line::sSourceFileCount; ++file_index)
if (!_tcsicmp(file, Line::sSourceFile[file_index]))
break;
Line *line;
for (line = g_script.mFirstLine;
line && (line->mLineNumber != line_no || line->mFileIndex != file_index);
line = line->mNextLine);
if (line)
aLine = line;
}
}
}
else
{
// Assume it's a string or number.
message = TokenToString(*aToken, message_buf);
}
// If message is empty or numeric, display a default message for clarity.
if (!*extra && IsPureNumeric(message, TRUE, TRUE, TRUE))
{
extra = message;
message = _T("Unhandled exception.");
}
TCHAR buf[MSGBOX_TEXT_SIZE];
Line::FormatError(buf, _countof(buf), FAIL, message, extra, aLine, _T("The thread has exited."));
MsgBox(buf);
FreeExceptionToken(aToken);
return FAIL;
}
void Script::FreeExceptionToken(ExprTokenType*& aToken)
{
// If an object was thrown, release it.
if (aToken->symbol == SYM_OBJECT)
aToken->object->Release();
// If a string was thrown and memory allocated for it, free it.
if (aToken->mem_to_free)
free(aToken->mem_to_free);
// Free the token itself.
delete aToken;
// Clear caller's variable.
aToken = NULL;
}
void Script::ScriptWarning(WarnMode warnMode, LPCTSTR aWarningText, LPCTSTR aExtraInfo, Line *line)
{
if (warnMode == WARNMODE_OFF)
return;
if (!line) line = mCurrLine;
int fileIndex = line ? line->mFileIndex : mCurrFileIndex;
FileIndexType lineNumber = line ? line->mLineNumber : mCombinedLineNumber;
TCHAR buf[MSGBOX_TEXT_SIZE], *cp = buf;
int buf_space_remaining = (int)_countof(buf);
#define STD_WARNING_FORMAT _T("%s (%d) : ==> Warning: %s\n")
+#ifdef _USRDLL
+ // terminate source file if it contains new lines
+ LPTSTR new_line_pos = _tcschr(Line::sSourceFile[fileIndex], '\r');
+ if (!new_line_pos)
+ new_line_pos = _tcschr(Line::sSourceFile[fileIndex], '\n');
+ TCHAR new_line_char = NULL;
+ if (new_line_pos)
+ {
+ new_line_char = *new_line_pos;
+ *new_line_pos = '\0';
+ }
+#endif
cp += sntprintf(cp, buf_space_remaining, STD_WARNING_FORMAT, Line::sSourceFile[fileIndex], lineNumber, aWarningText);
+#ifdef _USRDLL
+ if (new_line_pos)
+ *new_line_pos = new_line_char;
+#endif
buf_space_remaining = (int)(_countof(buf) - (cp - buf));
if (*aExtraInfo)
{
cp += sntprintf(cp, buf_space_remaining, _T(" Specifically: %s\n"), aExtraInfo);
buf_space_remaining = (int)(_countof(buf) - (cp - buf));
}
if (warnMode == WARNMODE_STDOUT)
#ifndef CONFIG_DEBUGGER
_fputts(buf, stdout);
else
OutputDebugString(buf);
#else
g_Debugger.FileAppendStdOut(buf);
else
g_Debugger.OutputDebug(buf);
#endif
// In MsgBox mode, MsgBox is in addition to OutputDebug
if (warnMode == WARNMODE_MSGBOX)
{
if (!line)
line = mCurrLine; // Call mCurrLine->LineError() vs ScriptError() to pass WARN.
if (line)
line->LineError(aWarningText, WARN, aExtraInfo);
else
// Realistically shouldn't happen. If it does, the message might be slightly
// misleading since ScriptError isn't equipped to display "warning" messages.
ScriptError(aWarningText, aExtraInfo);
}
}
void Script::WarnUninitializedVar(Var *var)
{
bool isGlobal = !var->IsLocal();
WarnMode warnMode = isGlobal ? g_Warn_UseUnsetGlobal : g_Warn_UseUnsetLocal;
if (!warnMode)
return;
// Note: If warning mode is MsgBox, this method has side effect of marking the var initialized, so that
// only a single message box gets raised per variable. (In other modes, e.g. OutputDebug, the var remains
// uninitialized because it may be beneficial to see the quantity and various locations of uninitialized
// uses, and doesn't present the same user interface problem that multiple message boxes can.)
if (warnMode == WARNMODE_MSGBOX)
var->MarkInitialized();
bool isNonStaticLocal = var->IsNonStaticLocal();
LPCTSTR varClass = isNonStaticLocal ? _T("local") : (isGlobal ? _T("global") : _T("static"));
LPCTSTR sameNameAsGlobal = (isNonStaticLocal && FindVar(var->mName, 0, NULL, FINDVAR_GLOBAL)) ? _T(" with same name as a global") : _T("");
TCHAR buf[DIALOG_TITLE_SIZE], *cp = buf;
int buf_space_remaining = (int)_countof(buf);
sntprintf(cp, buf_space_remaining, _T("%s (a %s variable%s)"), var->mName, varClass, sameNameAsGlobal);
ScriptWarning(warnMode, WARNING_USE_UNSET_VARIABLE, buf);
}
void Script::MaybeWarnLocalSameAsGlobal(Func &func, Var &var)
// Caller has verified the following:
// 1) var is not a declared variable.
// 2) a global variable with the same name definitely exists.
{
if (!g_Warn_LocalSameAsGlobal)
return;
#ifdef ENABLE_DLLCALL
if (IsDllArgTypeName(var.mName))
// Exclude unquoted DllCall arg type names. Although variable names like "str" and "ptr"
// might be used for other purposes, it seems far more likely that both this var and its
// global counterpart (if it exists) are blank vars which were used as DllCall arg types.
return;
#endif
Line *line = func.mJumpToLine;
while (line && line->mActionType != ACT_BLOCK_BEGIN) line = line->mPrevLine;
if (!line) line = func.mJumpToLine;
TCHAR buf[DIALOG_TITLE_SIZE], *cp = buf;
int buf_space_remaining = (int)_countof(buf);
sntprintf(cp, buf_space_remaining, _T("%s (in function %s)"), var.mName, func.mName);
ScriptWarning(g_Warn_LocalSameAsGlobal, WARNING_LOCAL_SAME_AS_GLOBAL, buf, line);
}
void Script::PreprocessLocalVars(Func &aFunc, Var **aVarList, int &aVarCount)
{
for (int v = 0; v < aVarCount; ++v)
{
Var &var = *aVarList[v];
if (var.IsDeclared()) // Not a canditate for a super-global or warning.
continue;
Var *global_var = FindVar(var.mName, 0, NULL, FINDVAR_GLOBAL);
if (!global_var) // No global variable with that name.
continue;
if (global_var->IsSuperGlobal())
{
// Make this local variable an alias for the super-global. Above has already
// verified this var was not declared and therefore isn't a function parameter.
var.UpdateAlias(global_var);
// Remove the variable from the local list to prevent it from being shown in
// ListVars or being reset when the function returns.
memmove(aVarList + v, aVarList + v + 1, (--aVarCount - v) * sizeof(Var *));
--v; // Counter the loop's increment.
}
else
// Since this undeclared local variable has the same name as a global, there's
// a chance the user intended it to be global. So consider warning the user:
MaybeWarnLocalSameAsGlobal(aFunc, var);
}
}
#ifndef MINIDLL
LPTSTR Script::ListVars(LPTSTR aBuf, int aBufSize) // aBufSize should be an int to preserve negatives from caller (caller relies on this).
// aBufSize is an int so that any negative values passed in from caller are not lost.
// Translates this script's list of variables into text equivalent, putting the result
// into aBuf and returning the position in aBuf of its new string terminator.
{
LPTSTR aBuf_orig = aBuf;
Func *current_func = g->CurrentFunc ? g->CurrentFunc : g->CurrentFuncGosub;
if (current_func)
{
// This definition might help compiler string pooling by ensuring it stays the same for both usages:
#define LIST_VARS_UNDERLINE _T("\r\n--------------------------------------------------\r\n")
// Start at the oldest and continue up through the newest:
aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("Static Variables for %s()%s"), current_func->mName, LIST_VARS_UNDERLINE);
Func &func = *current_func; // For performance.
for (int i = 0; i < func.mStaticVarCount; ++i)
if (func.mStaticVar[i]->Type() == VAR_NORMAL) // Don't bother showing clipboard and other built-in vars.
aBuf = func.mStaticVar[i]->ToText(aBuf, BUF_SPACE_REMAINING, true);
// Start at the oldest and continue up through the newest:
aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("\r\n\r\nLocal Variables for %s()%s"), current_func->mName, LIST_VARS_UNDERLINE);
for (int i = 0; i < func.mVarCount; ++i)
if (func.mVar[i]->Type() == VAR_NORMAL) // Don't bother showing clipboard and other built-in vars.
aBuf = func.mVar[i]->ToText(aBuf, BUF_SPACE_REMAINING, true);
}
// v1.0.31: The description "alphabetical" is kept even though it isn't quite true
// when the lazy variable list exists, since those haven't yet been sorted into the main list.
// However, 99.9% of scripts do not use the lazy list, so it seems too rare to worry about other
// than document it in the ListVars command in the help file:
aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("%sGlobal Variables (alphabetical)%s")
, current_func ? _T("\r\n\r\n") : _T(""), LIST_VARS_UNDERLINE);
// Start at the oldest and continue up through the newest:
for (int i = 0; i < mVarCount; ++i)
if (mVar[i]->Type() == VAR_NORMAL) // Don't bother showing clipboard and other built-in vars.
aBuf = mVar[i]->ToText(aBuf, BUF_SPACE_REMAINING, true);
return aBuf;
}
LPTSTR Script::ListKeyHistory(LPTSTR aBuf, int aBufSize) // aBufSize should be an int to preserve negatives from caller (caller relies on this).
// aBufSize is an int so that any negative values passed in from caller are not lost.
// Translates this key history into text equivalent, putting the result
// into aBuf and returning the position in aBuf of its new string terminator.
{
LPTSTR aBuf_orig = aBuf; // Needed for the BUF_SPACE_REMAINING macro.
// I was initially concerned that GetWindowText() can hang if the target window is
// hung. But at least on newer OS's, this doesn't seem to be a problem: MSDN says
// "If the window does not have a caption, the return value is a null string. This
// behavior is by design. It allows applications to call GetWindowText without hanging
// if the process that owns the target window is hung. However, if the target window
// is hung and it belongs to the calling application, GetWindowText will hang the
// calling application."
HWND target_window = GetForegroundWindow();
TCHAR win_title[100];
if (target_window)
GetWindowText(target_window, win_title, _countof(win_title));
else
*win_title = '\0';
TCHAR timer_list[128] = _T("");
for (ScriptTimer *timer = mFirstTimer; timer != NULL; timer = timer->mNextTimer)
if (timer->mEnabled)
sntprintfcat(timer_list, _countof(timer_list) - 3, _T("%s "), timer->mLabel->mName); // Allow room for "..."
if (*timer_list)
{
size_t length = _tcslen(timer_list);
if (length > (_countof(timer_list) - 5))
tcslcpy(timer_list + length, _T("..."), _countof(timer_list) - length);
else if (timer_list[length - 1] == ' ')
timer_list[--length] = '\0'; // Remove the last space if there was room enough for it to have been added.
}
TCHAR LRtext[256];
aBuf += sntprintf(aBuf, aBufSize,
_T("Window: %s")
//"\r\nBlocks: %u"
_T("\r\nKeybd hook: %s")
_T("\r\nMouse hook: %s")
_T("\r\nEnabled Timers: %u of %u (%s)")
//"\r\nInterruptible?: %s"
_T("\r\nInterrupted threads: %d%s")
_T("\r\nPaused threads: %d of %d (%d layers)")
_T("\r\nModifiers (GetKeyState() now) = %s")
_T("\r\n")
, win_title
//, SimpleHeap::GetBlockCount()
, g_KeybdHook == NULL ? _T("no") : _T("yes")
, g_MouseHook == NULL ? _T("no") : _T("yes")
, mTimerEnabledCount, mTimerCount, timer_list
//, INTERRUPTIBLE ? "yes" : "no"
, g_nThreads > 1 ? g_nThreads - 1 : 0
, g_nThreads > 1 ? _T(" (preempted: they will resume when the current thread finishes)") : _T("")
, g_nPausedThreads - (g_array[0].IsPaused && !mAutoExecSectionIsRunning) // Historically thread #0 isn't counted as a paused thread unless the auto-exec section is running but paused.
, g_nThreads, g_nLayersNeedingTimer
, ModifiersLRToText(GetModifierLRState(true), LRtext));
GetHookStatus(aBuf, BUF_SPACE_REMAINING);
aBuf += _tcslen(aBuf); // Adjust for what GetHookStatus() wrote to the buffer.
return aBuf + sntprintf(aBuf, BUF_SPACE_REMAINING, g_KeyHistory ? _T("\r\nPress [F5] to refresh.")
: _T("\r\nKey History has been disabled via #KeyHistory 0."));
}
#endif
ResultType Script::ActionExec(LPTSTR aAction, LPTSTR aParams, LPTSTR aWorkingDir, bool aDisplayErrors
, LPTSTR aRunShowMode, HANDLE *aProcess, bool aUpdateLastError, bool aUseRunAs, Var *aOutputVar)
// Caller should specify NULL for aParams if it wants us to attempt to parse out params from
// within aAction. Caller may specify empty string ("") instead to specify no params at all.
// Remember that aAction and aParams can both be NULL, so don't dereference without checking first.
// Note: For the Run & RunWait commands, aParams should always be NULL. Params are parsed out of
// the aActionString at runtime, here, rather than at load-time because Run & RunWait might contain
// dereferenced variable(s), which can only be resolved at runtime.
{
HANDLE hprocess_local;
HANDLE &hprocess = aProcess ? *aProcess : hprocess_local; // To simplify other things.
hprocess = NULL; // Init output param if the caller gave us memory to store it. Even if caller didn't, other things below may rely on this being initialized.
if (aOutputVar) // Same
aOutputVar->Assign();
// Launching nothing is always a success:
if (!aAction || !*aAction) return OK;
// Make sure this is set to NULL because CreateProcess() won't work if it's the empty string:
if (aWorkingDir && !*aWorkingDir)
aWorkingDir = NULL;
#define IS_VERB(str) ( !_tcsicmp(str, _T("find")) || !_tcsicmp(str, _T("explore")) || !_tcsicmp(str, _T("open"))\
|| !_tcsicmp(str, _T("edit")) || !_tcsicmp(str, _T("print")) || !_tcsicmp(str, _T("properties")) )
// Set default items to be run by ShellExecute(). These are also used by the error
// reporting at the end, which is why they're initialized even if CreateProcess() works
// and there's no need to use ShellExecute():
LPTSTR shell_verb = NULL;
LPTSTR shell_action = aAction;
LPTSTR shell_params = NULL;
///////////////////////////////////////////////////////////////////////////////////
// This next section is done prior to CreateProcess() because when aParams is NULL,
// we need to find out whether aAction contains a system verb.
///////////////////////////////////////////////////////////////////////////////////
if (aParams) // Caller specified the params (even an empty string counts, for this purpose).
{
if (IS_VERB(shell_action))
{
shell_verb = shell_action;
shell_action = aParams;
}
else
shell_params = aParams;
}
else // Caller wants us to try to parse params out of aAction.
{
// Find out the "first phrase" in the string to support the special "find" and "explore" operations.
LPTSTR phrase;
size_t phrase_len;
// Set phrase_end to be the location of the first whitespace char, if one exists:
LPTSTR phrase_end = StrChrAny(shell_action, _T(" \t")); // Find space or tab.
if (phrase_end) // i.e. there is a second phrase.
{
phrase_len = phrase_end - shell_action;
// Create a null-terminated copy of the phrase for comparison.
phrase = tmemcpy(talloca(phrase_len + 1), shell_action, phrase_len);
phrase[phrase_len] = '\0';
// Firstly, treat anything following '*' as a verb, to support custom verbs like *Compile.
if (*phrase == '*')
shell_verb = phrase + 1;
// Secondly, check for common system verbs like "find" and "edit".
else if (IS_VERB(phrase))
shell_verb = phrase;
if (shell_verb)
// Exclude the verb and its trailing space or tab from further consideration.
shell_action += phrase_len + 1;
// Otherwise it's not a verb, and may be re-parsed later.
}
// shell_action will be split into action and params at a later stage if ShellExecuteEx is to be used.
}
// This is distinct from hprocess being non-NULL because the two aren't always the
// same. For example, if the user does "Run, find D:\" or "RunWait, www.yahoo.com",
// no new process handle will be available even though the launch was successful:
bool success = false;
TCHAR system_error_text[512] = _T("");
bool use_runas = aUseRunAs && (!mRunAsUser.IsEmpty() || !mRunAsPass.IsEmpty() || !mRunAsDomain.IsEmpty());
if (use_runas && shell_verb)
{
if (aDisplayErrors)
ScriptError(_T("System verbs unsupported with RunAs."));
return FAIL;
}
size_t action_length = _tcslen(shell_action); // shell_action == aAction if shell_verb == NULL.
if (action_length >= LINE_SIZE) // Max length supported by CreateProcess() is 32 KB. But there hasn't been any demand to go above 16 KB, so seems little need to support it (plus it reduces risk of stack overflow).
{
if (aDisplayErrors)
ScriptError(_T("String too long.")); // Short msg since so rare.
return FAIL;
}
// If the caller originally gave us NULL for aParams, always try CreateProcess() before
// trying ShellExecute(). This is because ShellExecute() is usually a lot slower.
// The only exception is if the action appears to be a verb such as open, edit, or find.
// In that case, we'll also skip the CreateProcess() attempt and do only the ShellExecute().
// If the user really meant to launch find.bat or find.exe, for example, he should add
// the extension (e.g. .exe) to differentiate "find" from "find.exe":
if (!shell_verb)
{
STARTUPINFO si = {0}; // Zero fill to be safer.
si.cb = sizeof(si);
// The following are left at the default of NULL/0 set higher above:
//si.lpReserved = si.lpDesktop = si.lpTitle = NULL;
//si.lpReserved2 = NULL;
si.dwFlags = STARTF_USESHOWWINDOW; // This tells it to use the value of wShowWindow below.
si.wShowWindow = (aRunShowMode && *aRunShowMode) ? Line::ConvertRunMode(aRunShowMode) : SW_SHOWNORMAL;
PROCESS_INFORMATION pi = {0};
// Since CreateProcess() requires that the 2nd param be modifiable, ensure that it is
// (even if this is ANSI and not Unicode; it's just safer):
LPTSTR command_line;
if (aParams && *aParams)
{
command_line = talloca(action_length + _tcslen(aParams) + 10); // +10 to allow room for space, terminator, and any extra chars that might get added in the future.
_stprintf(command_line, _T("%s %s"), aAction, aParams);
}
else // We're running the original action from caller.
{
command_line = talloca(action_length + 1);
_tcscpy(command_line, aAction); // CreateProcessW() requires modifiable string. Although non-W version is used now, it feels safer to make it modifiable anyway.
}
if (use_runas)
{
if (!DoRunAs(command_line, aWorkingDir, aDisplayErrors, aUpdateLastError, si.wShowWindow // wShowWindow (min/max/hide).
, aOutputVar, pi, success, hprocess, system_error_text)) // These are output parameters it will set for us.
return FAIL; // It already displayed the error, if appropriate.
}
else
{
// MSDN: "If [lpCurrentDirectory] is NULL, the new process is created with the same
// current drive and directory as the calling process." (i.e. since caller may have
// specified a NULL aWorkingDir). Also, we pass NULL in for the first param so that
// it will behave the following way (hopefully under all OSes): "the first white-space delimited
// token of the command line specifies the module name. If you are using a long file name that
// contains a space, use quoted strings to indicate where the file name ends and the arguments
// begin (see the explanation for the lpApplicationName parameter). If the file name does not
// contain an extension, .exe is appended. Therefore, if the file name extension is .com,
// this parameter must include the .com extension. If the file name ends in a period (.) with
// no extension, or if the file name contains a path, .exe is not appended. If the file name does
// not contain a directory path, the system searches for the executable file in the following
// sequence...".
// Provide the app name (first param) if possible, for greater expected reliability.
// UPDATE: Don't provide the module name because if it's enclosed in double quotes,
// CreateProcess() will fail, at least under XP:
//if (CreateProcess(aParams && *aParams ? aAction : NULL
if (CreateProcess(NULL, command_line, NULL, NULL, FALSE, 0, NULL, aWorkingDir, &si, &pi))
{
success = true;
if (pi.hThread)
CloseHandle(pi.hThread); // Required to avoid memory leak.
hprocess = pi.hProcess;
if (aOutputVar)
aOutputVar->Assign(pi.dwProcessId);
}
else
GetLastErrorText(system_error_text, _countof(system_error_text), aUpdateLastError);
}
}
if (!success) // Either the above wasn't attempted, or the attempt failed. So try ShellExecute().
{
if (use_runas)
{
// Since CreateProcessWithLogonW() was either not attempted or did not work, it's probably
// best to display an error rather than trying to run it without the RunAs settings.
// This policy encourages users to have RunAs in effect only when necessary:
if (aDisplayErrors)
ScriptError(_T("Launch Error (possibly related to RunAs)."), system_error_text);
return FAIL;
}
SHELLEXECUTEINFO sei = {0};
// sei.hwnd is left NULL to avoid potential side-effects with having a hidden window be the parent.
// However, doing so may result in the launched app appearing on a different monitor than the
// script's main window appears on (for multimonitor systems). This seems fairly inconsequential
// since scripted workarounds are possible.
sei.cbSize = sizeof(sei);
// Below: "indicate that the hProcess member receives the process handle" and not to display error dialog:
sei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;
sei.lpDirectory = aWorkingDir; // OK if NULL or blank; that will cause current dir to be used.
sei.nShow = (aRunShowMode && *aRunShowMode) ? Line::ConvertRunMode(aRunShowMode) : SW_SHOWNORMAL;
if (shell_verb)
{
sei.lpVerb = shell_verb;
if (!_tcsicmp(shell_verb, _T("properties")))
sei.fMask |= SEE_MASK_INVOKEIDLIST; // Need to use this for the "properties" verb to work reliably.
}
if (!shell_params) // i.e. above hasn't determined the params yet.
{
// Rather than just consider the first phrase to be the executable and the rest to be the param, we check it
// for a proper extension so that the user can launch a document name containing spaces, without having to
// enclose it in double quotes. UPDATE: Want to be able to support executable filespecs without requiring them
// to be enclosed in double quotes. Therefore, search the entire string, rather than just first_phrase, for
// the left-most occurrence of a valid executable extension. This should be fine since the user can still
// pass in EXEs and such as params as long as the first executable is fully qualified with its real extension
// so that we can tell that it's the action and not one of the params. UPDATE: Since any file type may
// potentially accept parameters (.lnk or .ahk files for instance), the first space-terminated substring which
// is either an existing file or ends in one of .exe,.bat,.com,.cmd,.hta is considered the executable and the
// rest is considered the param. Remaining shortcomings of this method include:
// - It doesn't handle an extensionless executable such as "notepad test.txt"
// - It doesn't handle custom file types (scripts etc.) which don't exist in the working directory but can
// still be executed due to %PATH% and %PATHEXT% even when our caller doesn't supply an absolute path.
// These limitations seem acceptable since the caller can allow even those cases to work by simply wrapping
// the action in quote marks.
// Make a copy so that we can modify it (i.e. split it into action & params).
// Using talloca ensures it will stick around until the function exits:
LPTSTR parse_buf = talloca(action_length + 1);
_tcscpy(parse_buf, shell_action);
LPTSTR action_extension, action_end;
// Let quotation marks be used to remove all ambiguity:
if (*parse_buf == '"' && (action_end = _tcschr(parse_buf + 1, '"')))
{
shell_action = parse_buf + 1;
*action_end = '\0';
if (action_end[1])
{
shell_params = action_end + 1;
// Omit the space which should follow, but only one, in case spaces
// are meaningful to the target program.
if (*shell_params == ' ')
++shell_params;
}
// Otherwise, there's only the action in quotation marks and no params.
}
else
{
if (aWorkingDir) // Set current directory temporarily in case the action is a relative path:
SetCurrentDirectory(aWorkingDir);
// For each space which possibly delimits the action and params:
for (action_end = parse_buf + 1; action_end = _tcschr(action_end, ' '); ++action_end)
{
// Find the beginning of the substring or file extension; if \ is encountered, this might be
// an extensionless filename, but it probably wouldn't be meaningful to pass params to such a
// file since it can't be associated with anything, so skip to the next space in that case.
for ( action_extension = action_end - 1;
action_extension > parse_buf && !_tcschr(_T("\\/."), *action_extension);
--action_extension );
if (*action_extension == '.') // Potential file extension; even if action_extension == parse_buf since ".ext" on its own is a valid filename.
{
*action_end = '\0'; // Temporarily terminate.
// If action_extension is a common executable extension, don't call GetFileAttributes() since
// the file might actually be in a location listed in %PATH% or the App Paths registry key:
if ( (action_end-action_extension == 4 && tcscasestr(_T(".exe.bat.com.cmd.hta"), action_extension))
// Otherwise the file might still be something capable of accepting params, like a script,
// so check if what we have is the name of an existing file:
|| !(GetFileAttributes(parse_buf) & FILE_ATTRIBUTE_DIRECTORY) ) // i.e. THE FILE EXISTS and is not a directory. This works because (INVALID_FILE_ATTRIBUTES & FILE_ATTRIBUTE_DIRECTORY) is non-zero.
{
shell_action = parse_buf;
shell_params = action_end + 1;
break;
}
// What we have so far isn't an obvious executable file type or the path of an existing
// file, so assume it isn't a valid action. Unterminate and continue the loop:
*action_end = ' ';
}
}
if (aWorkingDir)
SetCurrentDirectory(g_WorkingDir); // Restore to proper value.
}
}
//else aParams!=NULL, so the extra parsing in the block above isn't necessary.
// Not done because it may have been set to shell_verb above:
//sei.lpVerb = NULL;
sei.lpFile = shell_action;
sei.lpParameters = shell_params; // NULL if no parameters were present.
// Above was fixed v1.0.42.06 to be NULL rather than the empty string to prevent passing an
// extra space at the end of a parameter list (this might happen only when launching a shortcut
// [.lnk file]). MSDN states: "If the lpFile member specifies a document file, lpParameters should
// be NULL." This implies that NULL is a suitable value for lpParameters in cases where you don't
// want to pass any parameters at all.
if (ShellExecuteEx(&sei)) // Relies on short-circuit boolean order.
{
typedef DWORD (WINAPI *GetProcessIDType)(HANDLE);
// GetProcessID is only available on WinXP SP1 or later, so load it dynamically.
static GetProcessIDType fnGetProcessID = (GetProcessIDType)GetProcAddress(GetModuleHandle(_T("kernel32.dll")), "GetProcessId");
if (hprocess = sei.hProcess)
{
// A new process was created, so get its ID if possible.
if (aOutputVar && fnGetProcessID)
aOutputVar->Assign(fnGetProcessID(hprocess));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.